Index: trunk/MagicSoft/Mars/mtemp/Changelog
===================================================================
--- trunk/MagicSoft/Mars/mtemp/Changelog	(revision 4136)
+++ trunk/MagicSoft/Mars/mtemp/Changelog	(revision 4137)
@@ -18,4 +18,10 @@
 
                                                  -*-*- END OF LINE -*-*-
+
+ 2004/05/23: Thomas Hengstebeck
+   * mberlin/macros/ScaleHillas.C , SrcCorrect.C , Convert2Matrix.C , 
+     CutOptim.C , AlphaPlot.C , IOMkn421.h
+     - Added analysis macros
+
 
  2004/05/18: Daniel Mazin
Index: trunk/MagicSoft/Mars/mtemp/mberlin/macros/AlphaPlot.C
===================================================================
--- trunk/MagicSoft/Mars/mtemp/mberlin/macros/AlphaPlot.C	(revision 4137)
+++ trunk/MagicSoft/Mars/mtemp/mberlin/macros/AlphaPlot.C	(revision 4137)
@@ -0,0 +1,250 @@
+#include "TString.h"
+#include "TChain.h"
+#include "TCanvas.h"
+#include "TH1F.h"
+#include "TF1.h"
+#include "TLegend.h"
+#include "TArrayF.h"
+#include "TGraphErrors.h"
+#include "MRawRunHeader.h"
+#include "TPad.h"
+#include "TPaveText.h"
+#include "iostream.h"
+#include "TObjArray.h"
+#include "TFile.h"
+
+//--------------------------------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//--------------------------------------------------------------------------------------
+
+Double_t signal(Double_t *x, Double_t *par)
+{
+    return par[0]/(TMath::Sqrt(2.*TMath::Pi())*par[1])*TMath::Exp(-(x[0]-par[2])*(x[0]-par[2])/2./par[1]/par[1]);
+}
+
+Double_t background(Double_t *x, Double_t *par)
+{
+    return par[0]+par[1]*x[0]+par[2]*x[0]*x[0]+par[3]*x[0]*x[0]*x[0];
+}
+
+Double_t fitFunction(Double_t *x, Double_t *par)
+{
+    return signal(x,par) + background(x,&par[3]);
+}
+
+void AlphaPlot()
+{
+    DistLo*=deg2mm;
+    DistUp*=deg2mm;
+
+    Double_t acut = 10; // alpha region of excess
+    Int_t nbins   = 36;
+    Int_t nbin_flat= nbins/3;
+
+    // input file chain
+    TChain *fEvents=new TChain("Events");
+    fEvents->Add(fileOn1.Data());
+    fEvents->Add(fileOn2.Data());
+
+    TChain *fEventsOff=new TChain("Events");
+    fEventsOff->Add(fileOff1.Data());
+    fEventsOff->Add(fileOff2.Data());
+
+
+    cout<<"Non="<<fEvents->GetEntries()<<"  Noff="<<fEventsOff->GetEntries()<<endl;
+    //************************************************************************
+    // alpha plot + fit
+
+    // make alpha plot (after cuts)
+    TCanvas *c1 = new TCanvas("c1","Alpha distribution after g/h separation",200,10,800,500);
+    c1->SetFillColor(0);
+    c1->SetBorderMode(0);
+    c1->cd();
+
+    TH1F *halpha=new TH1F("halpha","",nbins,0.,90.);
+    halpha->GetXaxis()->SetTitle("Alpha [deg]");
+    halpha->GetYaxis()->SetTitle("Counts");
+
+    TH1F *halphaOff=new TH1F("halphaOff","",nbins,0.,90.);
+    halpha->SetStats(kFALSE);
+    halphaOff->SetStats(kFALSE);
+
+    TString strcut=Form("MHillas.fSize>%f",SizeLo);
+
+    strcut+=Form("&& MHillasSrc.fDist>%f",DistLo);
+    strcut+=Form("&& MHillasSrc.fDist<%f",DistUp);
+
+    strcut+=Form("&& MHillas.fWidth>%f",WidthLo);
+    strcut+=Form("&& MHillas.fWidth<%f",WidthUp);
+
+    strcut+=Form("&& MHillas.fLength>%f",LengthLo);
+    strcut+=Form("&& MHillas.fLength<%f",LengthUp);
+
+    // fill histograms
+    fEvents->Project("halpha","TMath::Abs(MHillasSrc.fAlpha)",strcut.Data());
+    halpha->SetLineWidth(2);
+    halpha->DrawCopy("e");
+
+    fEventsOff->Project("halphaOff","TMath::Abs(MHillasSrc.fAlpha)",strcut.Data());
+    halphaOff->SetLineColor(2);
+    halphaOff->SetLineWidth(2);
+
+
+    // scale Off histogram to On data using bins nbin_flat(first bin after peak) - nbins
+    Double_t nsample_on=0;
+    Double_t nsample_off=0;
+    for(Int_t i=nbin_flat;i<nbins;i++)
+        nsample_on+=halpha->GetBinContent(i);
+    for(Int_t i=nbin_flat;i<nbins;i++)
+        nsample_off+=halphaOff->GetBinContent(i);
+
+    Double_t scal=nsample_on/nsample_off;
+    halphaOff->Sumw2();
+    halphaOff->Scale(scal);
+    halphaOff->Draw("e same");
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    //--------------------------------------------------------------------------
+    // fit alpha hist
+    TF1 *backFcn = new TF1("backFcn",background,20.,89.5,4);
+    backFcn->SetLineWidth(2);
+    backFcn->SetLineColor(kRed);
+
+    TF1 *signalFcn = new TF1("signalFcn",signal,0.,89.5,3);
+    signalFcn->SetLineWidth(2);
+    signalFcn->SetLineColor(kBlue);
+    signalFcn->SetNpx(500);
+
+    TF1 *fitFcn = new TF1("fitFcn",fitFunction,0.,89.5,7);
+    fitFcn->SetNpx(500);
+    fitFcn->SetLineWidth(2);
+    fitFcn->SetLineColor(kMagenta);
+
+    // start-parameters
+    Double_t p3start=halpha->GetBinContent(halpha->GetNbinsX()-1);
+    Double_t p4start=0.;
+    Double_t p5start=0.;
+    Double_t p6start=0.;
+
+    Double_t p0start=(halpha->GetEntries()-p3start*nbins)*halpha->GetBinWidth(1);
+    Double_t p1start=5.;
+    Double_t p2start=0.;
+
+    cout<<"Start values for fit:"<<endl;
+
+    cout<<" Gaussian:"<<endl;
+    cout<<"  p0 = "<<p0start<<endl;
+    cout<<"  p1 = "<<p1start<<endl;
+    cout<<"  p2 = "<<p2start<<endl;
+
+    cout<<" Pol3:"<<endl;
+    cout<<"  p0 = "<<p3start<<endl;
+    cout<<"  p1 = "<<p4start<<endl;
+    cout<<"  p2 = "<<p5start<<endl;
+    cout<<"  p3 = "<<p6start<<endl<<endl<<endl;
+
+    // background fit
+    Double_t parb[4];
+    backFcn->SetParameters(p3start,p4start,p5start,p6start);
+    backFcn->FixParameter(1,0);   // deriv. at zero equal zero
+    //backFcn->FixParameter(2,0); // no 2nd order term
+    backFcn->FixParameter(3,0);   // no 3rd order term
+    halpha->Fit ("backFcn","RN");
+    backFcn->GetParameters(parb);
+
+    // total fit
+    Double_t par[7];
+    fitFcn->SetParameters(p0start,p1start,p2start,
+                          parb[0],parb[1],parb[2],parb[3]);
+
+    fitFcn->FixParameter(2,0.);
+    fitFcn->FixParameter(3,parb[0]);
+    fitFcn->FixParameter(4,parb[1]);
+    fitFcn->FixParameter(5,parb[2]);
+    fitFcn->FixParameter(6,parb[3]);
+    halpha->Fit ("fitFcn","RN");
+
+    // draw fit results + legend
+    TLegend *legend=new TLegend(0.4,0.5,0.93,0.65);
+    legend->SetTextFont(40);
+    legend->SetTextSize(0.04);
+    legend->SetFillColor(19);
+    legend->AddEntry(halpha,"Data","lp");
+    TString strpol("");
+    strpol=Form("Polynom");
+    legend->AddEntry(backFcn,strpol.Data(),"l");
+    legend->AddEntry(fitFcn,"Global Fit","l");
+    //legend->Draw();
+
+    fitFcn->GetParameters(par);
+    fitFcn->SetRange(-90.,90.);
+    fitFcn->SetLineWidth(2);
+    fitFcn->Draw("same");
+
+    signalFcn->SetParameters(par);
+    //signalFcn->SetLineWidth(2);
+    //signalFcn->Draw("same");
+
+    backFcn->SetParameters(&par[3]);
+    backFcn->SetRange(-90,90);
+    backFcn->SetLineWidth(2);
+    backFcn->Draw("same");
+
+    //-----------------------------------------------------------------------
+    // calculate significance
+
+    // analytical method
+    Double_t nSig=signalFcn->Integral(0.,acut)/halpha->GetBinWidth(1);
+    Double_t nOffScaled=backFcn->Integral(0.,acut)/halpha->GetBinWidth(1);
+
+    Double_t nOn=nSig+nOffScaled;
+
+    // significance after Li/Ma
+    Double_t theta=1.; // should be = Ton/Toff ???
+    Double_t nOff=nOffScaled/theta;
+    Double_t siglima = sqrt(2*(nOn*TMath::Log((1+theta)*nOn/(theta*(nOn+nOff)))
+                               +nOff*TMath::Log((1+theta)*(nOff/(nOn+nOff)))));
+
+    // "standard" significance
+    Double_t sigstd  = nSig/sqrt(nOn+nOffScaled);
+
+    TPaveText *pt = new TPaveText(0.25,0.75,0.56,0.98,"brNDC");
+    pt->SetTextFont(60);
+    pt->SetTextSize(0.03);
+    pt->SetTextAlign(12);
+
+    TString strcut1(Form("cuts:"));
+    TString strcut3(Form(" |alpha| <  %4.2f ",acut));
+    pt->AddText(strcut3.Data());
+    TString str("");
+    pt->AddText(str);
+
+    TString strsig(Form("NExcess = %d",Int_t(nSig)));
+    pt->AddText(strsig.Data());
+    TString strbak(Form("NOff    = %d",Int_t(nOffScaled)));
+    pt->AddText(strbak.Data());
+    pt->AddText(str);
+
+    TString strsg(Form("Significance (Li/Ma) = %4.2f",siglima));
+    pt->AddText(strsg.Data());
+    strsg=Form("Significance (std) = %4.2f",sigstd);
+    pt->AddText(strsg.Data());
+    pt->Draw();
+
+    cout<<endl<<"Results for events with |alpha| < "<<acut<<" degrees :"<<endl;
+    cout<<" noff         ="<<nOffScaled<<endl;
+    cout<<" nexcess      ="<<nSig<<endl;
+    cout<<" sig. (Li/Ma) ="<<siglima<<endl;
+    cout<<" sig.-std     ="<<sigstd<<endl<<endl<<endl;
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    c1->Update();
+
+    return;
+}
Index: trunk/MagicSoft/Mars/mtemp/mberlin/macros/Convert2Matrix.C
===================================================================
--- trunk/MagicSoft/Mars/mtemp/mberlin/macros/Convert2Matrix.C	(revision 4137)
+++ trunk/MagicSoft/Mars/mtemp/mberlin/macros/Convert2Matrix.C	(revision 4137)
@@ -0,0 +1,93 @@
+#include "TString.h"
+#include "TChain.h"
+#include "TFile.h"
+#include "TH1F.h"
+#include "TMatrix.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MReadTree.h"
+#include "MHMatrix.h"
+#include "MFillH.h"
+#include "MEvtLoop.h"
+
+//--------------------------------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//--------------------------------------------------------------------------------------
+
+void Convert2Matrix()
+{
+    //------------------------------------------------------
+    // ON + OFF data to be filled into matrix
+
+    MReadTree readOn("Events", fileOptOn);
+    MReadTree readOff("Events", fileOptOff);
+
+    const Int_t nent=readOn.GetEntries();
+
+    //------------------------------------------------------
+
+    // process On data
+    MParList plistOn;
+    MTaskList tlistOn;
+    plistOn.AddToList(&tlistOn);
+
+    readOn.DisableAutoScheme();
+
+    TString sdist  = Form("MHillasSrc.fDist*%f",mm2deg);
+  
+    MHMatrix matOn("Matrix");
+    matOn.AddColumn("MHillas.fSize");  // 0
+    matOn.AddColumn(sdist.Data());     // 1
+    matOn.AddColumn("MHillas.fWidth"); // 2
+    matOn.AddColumn("MHillas.fLength");// 3
+    matOn.AddColumn("MHillasSrc.fAlpha");
+    plistOn.AddToList(&matOn);
+    MFillH fillOn("Matrix");
+
+    tlistOn.AddToList(&readOn);
+    tlistOn.AddToList(&fillOn);
+
+    MEvtLoop evtloopOn;
+    evtloopOn.SetParList(&plistOn);
+
+    if (!evtloopOn.Eventloop(0.5*nent))
+        return;
+
+    tlistOn.PrintStatistics();
+
+    TFile fileOn2(fileMatOn.Data(),"recreate","");
+    matOn.Write();
+    fileOn2.Close();
+
+
+    // process Off data
+
+    MParList plistOff;
+    MTaskList tlistOff;
+    plistOff.AddToList(&tlistOff);
+
+    readOff.DisableAutoScheme();
+
+    MHMatrix matOff("Matrix");
+    matOff.AddColumns(matOn.GetColumns());
+    plistOff.AddToList(&matOff);
+    MFillH fillOff("Matrix");
+
+    tlistOff.AddToList(&readOff);
+    tlistOff.AddToList(&fillOff);
+
+    MEvtLoop evtloopOff;
+    evtloopOff.SetParList(&plistOff);
+
+    if (!evtloopOff.Eventloop())
+        return;
+
+    tlistOff.PrintStatistics();
+
+    TFile fileOff2(fileMatOff.Data(),"recreate","");
+    matOff.Write();
+    fileOff2.Close();
+}
Index: trunk/MagicSoft/Mars/mtemp/mberlin/macros/CutOptim.C
===================================================================
--- trunk/MagicSoft/Mars/mtemp/mberlin/macros/CutOptim.C	(revision 4137)
+++ trunk/MagicSoft/Mars/mtemp/mberlin/macros/CutOptim.C	(revision 4137)
@@ -0,0 +1,468 @@
+#include "TMinuit.h"
+#include "TMatrix.h"
+#include "TString.h"
+#include "TCanvas.h"
+#include "TH1F.h"
+#include "TF1.h"
+#include "TLegend.h"
+#include "TFile.h"
+#include "TArrayF.h"
+#include "TGraphErrors.h"
+#include "MRawRunHeader.h"
+#include "TPad.h"
+#include "TPaveText.h"
+#include "iostream.h"
+#include "TObjArray.h"
+
+#include "MHMatrix.h"
+
+//--------------------------------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//--------------------------------------------------------------------------------------
+
+Double_t acut = 10; // alpha region of excess
+Bool_t aplot  = 1;  // make only alpha plot (1) , do sig. optimization and alpha plot (0)
+
+//--------------------------------------------------------------------------------------------------------------
+//--------------------------------------------------------------------------------------------------------------
+
+const TMatrix *matOn;
+const TMatrix *matOff;
+
+Int_t isize   = 0;
+Int_t idist   = 1;
+Int_t iwidth  = 2;
+Int_t ilength = 3;
+Int_t ialpha  = 4;
+
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+
+Double_t signal(Double_t *x, Double_t *par){
+    return par[0]/(TMath::Sqrt(2.*TMath::Pi())*par[1])*TMath::Exp(-(x[0]-par[2])*(x[0]-par[2])/2./par[1]/par[1]);
+}
+
+Double_t background(Double_t *x, Double_t *par){
+    return par[0]+par[1]*x[0]+par[2]*pow(x[0],2.)+par[3]*x[0]*x[0]*x[0];
+    //return par[0]+par[1]*x[0]+par[2]*x[0]*x[0]+par[3]*x[0]*x[0]*x[0];
+}
+
+Double_t fitFunction(Double_t *x, Double_t *par){
+    return signal(x,par) + background(x,&par[3]);
+}
+
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    Double_t w1=par[0];
+    Double_t w2=par[1];
+    Double_t l1=par[2];
+    Double_t l2=par[3];
+    Double_t d1=par[4];
+    Double_t d2=par[5];
+
+    Double_t non=0;
+    Double_t noff=0;
+
+    TH1F hon("hon","",18,0.,90.);//5 deg bins
+    for(Int_t i=0;i<matOn->GetNrows();i++)
+    {
+        if( (*matOn)(i,isize)<SizeLo) continue;
+        if(((*matOn)(i,idist)>d1)  ||((*matOn)(i,idist)<d2  )) continue;
+
+        if(((*matOn)(i,iwidth)>w1) ||((*matOn)(i,iwidth)<w2))  continue;
+        if(((*matOn)(i,ilength)>l1)||((*matOn)(i,ilength)<l2)) continue;
+
+        Float_t alpha=(*matOn)(i,ialpha);
+        hon.Fill(TMath::Abs(alpha));
+    }
+
+    for(Int_t i=1;i<=4;i++)
+        non+=hon.GetBinContent(i);
+
+    //-----------------------------------------------------------------
+    /*TH1F hoff("hoff","",18,0.,90.);//5 deg bins
+    for(Int_t i=0;i<matOff->GetNrows();i++)
+    {
+        if( (*matOff)(i,isize)<SizeLo) continue;
+        if(((*matOff)(i,idist)>d1)  ||((*matOff)(i,idist)<d2  )) continue;
+
+        if(((*matOff)(i,iwidth)>w1) ||((*matOff)(i,iwidth)<w2))  continue;
+        if(((*matOff)(i,ilength)>l1)||((*matOff)(i,ilength)<l2)) continue;
+
+        Float_t alpha=(*matOff)(i,ialpha);
+        hoff.Fill(TMath::Abs(alpha));
+    }
+
+    for(Int_t i=1;i<=4;i++)
+        noff+=hoff.GetBinContent(i);*/
+    //-----------------------------------------------------------------
+
+    // flat background region
+    for(Int_t i=7;i<=15;i++)
+        noff+=hon.GetBinContent(i);
+
+    Float_t offscale=4./9.;
+    noff*=offscale;
+
+    if(non+noff<0.001)
+        f=0.;
+    else
+        f = -(non-noff)/(TMath::Sqrt(non+noff));
+
+    cout<<"Non="<<non<<" Noff="<<noff*offscale<<" Sig="<<-f<<endl;
+}
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+void CutOptim()
+{
+    //-----------------------------------------------------------------------
+    // read matrices
+
+    MHMatrix hmatOn;
+    TFile *fileOn=new TFile(fileMatOn.Data());
+    hmatOn.Read("Matrix");
+    delete fileOn;
+    const TMatrix &mOn=hmatOn.GetM();
+    matOn=(const TMatrix*)&mOn;
+
+    MHMatrix hmatOff;
+    TFile *fileOff=new TFile(fileMatOff.Data());
+    hmatOff.Read("Matrix");
+    delete fileOff;
+    const TMatrix &mOff=hmatOff.GetM();
+    matOff=(const TMatrix*)&mOff;
+
+    //-----------------------------------------------------------------------
+
+    Int_t nrowOn  = matOn->GetNrows();
+    Int_t nrowOff = matOff->GetNrows();
+
+    Int_t ncolOn  = matOn->GetNcols();
+    Int_t ncolOff = matOff->GetNcols();
+
+    cout<<"matrix On:  ncol="<<ncolOn<<" nrow="<<nrowOn<<endl;
+    cout<<"matrix Off: ncol="<<ncolOff<<" nrow="<<nrowOff<<endl;
+
+    TCanvas *c = new TCanvas("c1","Alpha distribution after g/h separation",200,10,800,500);
+    c->SetFillColor(0);
+
+    //-----------------------------------------------------------------------
+    // optimize cuts
+
+    Int_t iflag;
+    Double_t val;
+    Double_t vstart[6];
+
+    Double_t *gin=NULL;
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    TMinuit *gMinuit = new TMinuit(10);
+    TGraph* gr=NULL;
+
+    if(!aplot)
+        c->Divide(2,1);
+    else
+        goto APlot;
+
+    // start values
+    vstart[0]=WidthUp;
+    vstart[1]=WidthLo;
+    vstart[2]=LengthUp;
+    vstart[3]=LengthLo;
+    vstart[4]=DistUp;
+    vstart[5]=DistLo;
+
+    gMinuit->SetFCN(fcn);
+
+    arglist[0] = 1;
+    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
+
+    // Set starting values and step sizes for parameters
+    static Double_t step[6];
+    const Double_t def_step=0.2;
+    step[0]=def_step;
+    step[1]=def_step;
+    step[2]=def_step;
+    step[3]=def_step;
+    step[4]=def_step;
+    step[5]=def_step;
+
+    gMinuit->mnparm(0,"w1", vstart[0], step[0], 0.,0.,ierflg);
+    gMinuit->mnparm(1,"w2", vstart[1], step[1], 0.,0.,ierflg);
+    gMinuit->mnparm(2,"l1", vstart[2], step[2], 0.,0.,ierflg);
+    gMinuit->mnparm(3,"l2", vstart[3], step[3], 0.,0.,ierflg);
+    gMinuit->mnparm(4,"d1", vstart[4], step[4], 0.2,1.,ierflg);
+    gMinuit->mnparm(5,"d2", vstart[5], step[5], 0.5,1.5,ierflg);
+
+    //gMinuit->FixParameter(0);  // WidthUp
+    gMinuit->FixParameter(1);   // WidthLo
+    //gMinuit->FixParameter(2);  // LengthUp
+    gMinuit->FixParameter(3);   // LengthLo
+    gMinuit->FixParameter(4);   // DistUp
+    gMinuit->FixParameter(5);   // DistLo
+
+    gMinuit->Eval(6,gin,val,vstart,iflag);
+
+    arglist[0] = 5000;
+    arglist[1] = 1.;
+
+    //gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg);
+    gMinuit->mnexcm("SIM", arglist ,2,ierflg);
+
+    // Print results
+    Double_t amin,edm,errdef;
+    Int_t nvpar,nparx,icstat;
+    gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
+    gMinuit->mnprin(3,amin);
+
+    Double_t fpar[6];
+    Double_t fparerr[6];
+    for(Int_t i=0;i<6;i++)
+        gMinuit->GetParameter(i,fpar[i],fparerr[i]);
+
+    WidthUp  = fpar[0];
+    WidthLo  = fpar[1];
+    LengthUp = fpar[2];
+    LengthLo = fpar[3];
+    DistUp   = fpar[4];
+    DistLo   = fpar[5];
+
+
+    // parameter's sigma plots
+    c->cd(2);
+    // 2 sigma contour
+    /*
+    gMinuit->SetErrorDef(4);
+    gr = (TGraph*) gMinuit->Contour(100,0,2);
+    gr->DrawClone("AL");*/
+
+    // 1 sigma contour
+    gMinuit->SetErrorDef(1);
+    gr = (TGraph*) gMinuit->Contour(100,0,2);
+    gr->DrawClone("AL");
+    /*
+    // contour of min. function
+    c->cd(2);
+    arglist[0] = 1; // WidthUp
+    gMinuit->mnexcm("SCA", arglist ,1,ierflg);
+    TGraph* gr = (TGraph*)gMinuit->GetPlot();
+    gr->DrawClone("al");
+
+    c->cd(4);
+    arglist[0] = 4; // LengthLo
+    gMinuit->mnexcm("SCA", arglist ,1,ierflg);
+    gr = (TGraph*)gMinuit->GetPlot();
+    gr->DrawClone("al");//*/
+
+    c->cd(1);
+
+APlot:
+    //-----------------------------------------------------------------------
+    // plot alpha histogram with current cuts and calc significance
+
+    // alpha histogram
+    TH1F *halpha=new TH1F("halpha","",18,0.,90.);
+    TH1F *halphaOff=new TH1F("halphaOff","",18,0.,90.);
+
+    halpha->SetStats(kFALSE);
+    halphaOff->SetStats(kFALSE);
+
+    for(Int_t i=0;i<nrowOn;i++)
+    {
+        if (mOn(i,isize)<SizeLo) continue;
+        if((mOn(i,idist)<DistLo)||(mOn(i,idist)>DistUp)) continue;
+
+        if((mOn(i,iwidth) < WidthLo) ||(mOn(i,iwidth) > WidthUp))  continue;
+        if((mOn(i,ilength)< LengthLo)||(mOn(i,ilength)> LengthUp)) continue;
+
+        halpha->Fill(TMath::Abs(mOn(i,ialpha)));
+    }
+    halpha->SetLineWidth(2);
+    halpha->DrawClone();
+
+    for(Int_t i=0;i<nrowOff;i++)
+    {
+        if (mOff(i,isize)<SizeLo) continue;
+        if((mOff(i,idist)<DistLo)||(mOff(i,idist)>DistUp)) continue;
+
+        if((mOff(i,iwidth) < WidthLo) ||(mOff(i,iwidth) > WidthUp))  continue;
+        if((mOff(i,ilength)< LengthLo)||(mOff(i,ilength)> LengthUp)) continue;
+
+        halphaOff->Fill(TMath::Abs(mOff(i,ialpha)));
+
+    }
+
+    // scale Off histogram to On data using bins 6-18
+    Double_t nsample_on=0;
+    Double_t nsample_off=0;
+    for(Int_t i=6;i<18;i++)
+        nsample_on+=halpha->GetBinContent(i);
+    for(Int_t i=6;i<18;i++)
+        nsample_off+=halphaOff->GetBinContent(i);
+
+    Double_t scal=nsample_on/nsample_off;
+
+    halphaOff->SetLineColor(2);
+    halphaOff->Scale(scal);
+    halphaOff->Draw("same");
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    // define functions
+    TF1 *backFcn = new TF1("backFcn",background,20.,89.5,4);
+    backFcn->SetLineWidth(2);
+    backFcn->SetLineColor(kRed);
+
+    TF1 *signalFcn = new TF1("signalFcn",signal,0.,89.5,3);
+    signalFcn->SetLineWidth(2);
+    signalFcn->SetLineColor(kBlue);
+    signalFcn->SetNpx(500);
+
+    TF1 *fitFcn = new TF1("fitFcn",fitFunction,0.,89.5,7);
+    fitFcn->SetNpx(500);
+    fitFcn->SetLineWidth(2);
+    fitFcn->SetLineColor(kMagenta);
+
+    // start-parameters
+    Double_t p3start=halpha->GetBinContent(halpha->GetNbinsX()-1);
+    Double_t p4start=0.;
+    Double_t p5start=0.;
+    Double_t p6start=0.;
+
+    Double_t p0start=(halpha->GetEntries()*halpha->GetBinWidth(1)-p3start)*0.05;
+    Double_t p1start=5.;
+    Double_t p2start=0.;
+
+    cout<<"start values:"<<endl;
+
+    cout<<" gaussian:"<<endl;
+    cout<<"  p0 = "<<p0start<<endl;
+    cout<<"  p1 = "<<p1start<<endl;
+    cout<<"  p2 = "<<p2start<<endl;
+
+    cout<<" pol3:"<<endl;
+    cout<<"  p0 = "<<p3start<<endl;
+    cout<<"  p1 = "<<p4start<<endl;
+    cout<<"  p2 = "<<p5start<<endl;
+    cout<<"  p3 = "<<p6start<<endl<<endl;
+
+
+    // background fit
+    Double_t parb[4];
+    backFcn->SetParameters(p3start,p4start,p5start,p6start);
+    backFcn->FixParameter(1,0);    // deriv. at zero equal zero
+    //backFcn->FixParameter(2,0);  // no 2nd order term
+    backFcn->FixParameter(3,0);    // no 3rd order term
+    //halphaOff->Fit ("backFcn","RN");
+    halpha->Fit ("backFcn","RN");
+    backFcn->GetParameters(parb);
+
+    // total fit
+    Double_t par[7];
+    fitFcn->SetParameters(p0start,p1start,p2start,
+                          parb[0],parb[1],parb[2],parb[3]);
+
+    fitFcn->FixParameter(2,0.);
+    fitFcn->FixParameter(3,parb[0]);
+    fitFcn->FixParameter(4,parb[1]);
+    fitFcn->FixParameter(5,parb[2]);
+    fitFcn->FixParameter(6,parb[3]);
+    halpha->Fit ("fitFcn","RN");
+
+    // draw the legend
+    TLegend *legend=new TLegend(0.4,0.5,0.93,0.65);
+    legend->SetTextFont(40);
+    legend->SetTextSize(0.04);
+    legend->SetFillColor(19);
+    legend->AddEntry(halpha,"Data","lp");
+    TString strpol("");
+    strpol=Form("Polynom");
+    legend->AddEntry(backFcn,strpol.Data(),"l");
+    legend->AddEntry(fitFcn,"Global Fit","l");
+    //legend->Draw();
+
+    // drawing the functions
+    fitFcn->GetParameters(par);
+    fitFcn->SetRange(-90.,90.);
+    fitFcn->SetLineWidth(2);
+    fitFcn->Draw("same");
+
+    signalFcn->SetParameters(par);
+    signalFcn->SetLineWidth(2);
+    //signalFcn->Draw("same");
+
+    backFcn->SetParameters(&par[3]);
+    backFcn->SetRange(-90,90);
+    backFcn->SetLineWidth(2);
+    backFcn->Draw("same");
+
+
+    //-----------------------------------------------------------------------
+    // calculate significance
+
+    // analytical method
+    Double_t nSig=signalFcn->Integral(0.,acut)/halpha->GetBinWidth(1);
+    Double_t nOffScaled=backFcn->Integral(0.,acut)/halpha->GetBinWidth(1);
+
+    Double_t nOn=nSig+nOffScaled;
+
+    // significance after Li/Ma
+    Double_t theta=1.; // should be = Ton/Toff ???
+    nSig=nOn-nOffScaled;
+    Double_t nOff=nOffScaled/theta;
+
+    Double_t siglima = sqrt(2*(nOn*TMath::Log((1+theta)*nOn/(theta*(nOn+nOff)))
+                               +nOff*TMath::Log((1+theta)*(nOff/(nOn+nOff)))));
+
+    // "standard" significance
+    Double_t sigstd  = nSig/sqrt(nOn+nOffScaled);
+
+
+    TPaveText *pt = new TPaveText(0.25,0.75,0.56,0.98,"brNDC");
+ 
+    pt->SetTextFont(60);
+    pt->SetTextSize(0.03);
+    pt->SetTextAlign(12);
+
+    TString strcut1(Form("cuts:"));
+    TString strcut3(Form(" |alpha| <  %4.2f ",acut));
+    pt->AddText(strcut3.Data());
+    TString str("");
+    pt->AddText(str);
+
+    TString strsig(Form("NExcess = %d",Int_t(nSig)));
+    pt->AddText(strsig.Data());
+    TString strbak(Form("NOff    = %d",Int_t(nOffScaled)));
+    pt->AddText(strbak.Data());
+    pt->AddText(str);
+
+    TString strsg(Form("Significance (Li/Ma) = %4.2f",siglima));
+    pt->AddText(strsg.Data());
+
+    cout<<"results for events with alpha < "<<acut<<" degrees :"<<endl;
+    cout<<" nbackground  = "<<nOffScaled<<endl;
+    cout<<" theta        = "<<theta<<endl;
+    cout<<" nsignal      = "<<nSig<<endl;
+    cout<<" sig. (Li/Ma) = "<<siglima<<endl;
+    cout<<" sig.-std     = "<<sigstd<<endl;
+    pt->Draw();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    c->Update();
+
+    cout<<endl<<"Optimized Cuts:"<<endl;
+    cout<<" "<<DistLo<<" < dist <"<<DistUp<<endl;
+    cout<<" "<<WidthLo<<" < width <"<<WidthUp<<endl;
+    cout<<" "<<LengthLo<<" < length <"<<LengthUp<<endl;
+
+    return;
+}
+
Index: trunk/MagicSoft/Mars/mtemp/mberlin/macros/IOMkn421.h
===================================================================
--- trunk/MagicSoft/Mars/mtemp/mberlin/macros/IOMkn421.h	(revision 4137)
+++ trunk/MagicSoft/Mars/mtemp/mberlin/macros/IOMkn421.h	(revision 4137)
@@ -0,0 +1,152 @@
+//**************************************************************************************************************
+//
+// Sample A ON  = Runs 17206 - 17265
+// Sample A OFF = Runs 17269 - 17283
+//
+// Sample B ON  = Runs 17286 - 17456
+// Sample B OFF = Runs 17459 - 17543
+//
+//**************************************************************************************************************
+
+//**************************************************************************************************************
+// general INPUT
+//**************************************************************************************************************
+
+// pi
+const double  PI=3.14159265358979333;  //atan(1)*4.0
+
+// conversion from deg to mm and vice versa
+const Double_t mm2deg = 180./17000./PI;
+const Double_t deg2mm = 1./mm2deg;
+
+// conversion from rad to deg and vice versa
+const Double_t rad2deg = 180./PI;
+const Double_t deg2rad = 1./rad2deg;
+
+// conversion from millisec to min
+const Double_t msec2min=1./1000./60.;
+
+//--------------------------------------------------------------------------------------------------------------
+// main path
+
+// HUB
+TString inpath = "/users/eeh/hengsteb/MAGIC/Mkn421Feb2004/SlidingWindow/";
+TString path = "/users/eeh/hengsteb/MAGIC/Mkn421Feb2004/";
+
+// laptop
+//TString inpath = "/home/hengsteb/MAGIC/Mkn421Feb2004/";
+//TString path = "/home/hengsteb/MAGIC/Mkn421Feb2004/";
+
+//**************************************************************************************************************
+// INPUT/OUTPUT for MagicHillas.C, ScaleHillas.C, SrcCorrect.C, FSrcPlot.C
+//**************************************************************************************************************
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 ON A
+TString dataOnA="SLIDINGRun17206-17265CalibRun17193_D_Mkn421On_E";
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 OFF A
+TString dataOffA="SLIDINGRun17269-17283CalibRun17268_D_OffMkn421_E";
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 ON B
+TString dataOnB="SLIDINGRun17286-17456CalibRun17285_D_Mkn421On_E";
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 OFF B
+TString dataOffB="SLIDINGRun17459-17543CalibRun17458_D_OffMkn421_E";
+
+//--------------------------------------------------------------------------------------------------------------
+// select the sample!
+TString data=dataOnB;
+
+TString fileCalibData =  inpath + data + ".root";
+TString fileHillas    =  path + data + "_Hillas.root";
+TString fileHScaled   =  path + data + "_HScaled.root";
+TString fileHScalHist =  path + data + "_HScalHist.root";
+
+TString fileFSrcPlot  =  path + data + "_FSrcPlot.root";
+TString fileSrcPos    =  path + data + "_SrcPos.dat";
+
+TString fileFSrcPlotC =  path + data + "_FSrcPlotC.root"; //corrected with known src pos
+TString fileHScaledC  =  path + data + "_HScaledC.root";  //corrected with known src pos
+
+//--------------------------------------------------------------------------------------------------------------
+// dead pixels
+
+const Int_t NDEAD=54;
+const Short_t DEADPIX[NDEAD]=
+{  0,  25,  26,  34,  38,  46,  54, 124, 125, 155, 156, 157, 158, 162, 170, 172, 201, 202, 203, 204, 205,
+ 206, 207, 208, 224, 388, 395 ,397, 440, 441, 442, 443, 444, 445, 446, 483, 484, 485, 486, 487, 488, 489,
+ 490, 532, 533, 534, 535, 536, 537, 538, 539, 540, 543, 559 };
+// 1    2    3    4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21
+
+TArrayS blindpix(NDEAD,DEADPIX);
+
+//--------------------------------------------------------------------------------------------------------------
+// default cuts for false source plots
+/*
+//Double_t SizeLo   = 1000.; // #ph
+//Double_t SizeLo   = 1111.; // #ph
+Double_t SizeLo   = 2000.; // #ph
+Double_t DistLo   = 0.6;   // degree
+Double_t DistUp   = 1.4;   // degree
+
+// static cuts
+//Double_t LengthLo = 0.14*deg2mm;  // degree
+//Double_t LengthUp = 0.26*deg2mm;  // degree
+//Double_t WidthLo  = 0.05*deg2mm;  // degree
+//Double_t WidthUp  = 0.14*deg2mm;  // degree
+
+// scaled Hillas
+
+Double_t LengthLo = 0.2525;
+Double_t LengthUp = 0.9312;
+Double_t WidthLo  = 0.2875;
+Double_t WidthUp  = 0.738;
+//*/
+
+//**************************************************************************************************************
+// INPUT/OUTPUT for AlphaPlot.C, CutOptim.C
+//**************************************************************************************************************
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 A + B
+
+// AlphaPlot + LightCurve, CutOptim
+TString fileOn1      = path + dataOnA + "_HScaledC.root";
+TString fileOn2      = path + dataOnB + "_HScaledC.root";
+
+TString fileOff1     = path + dataOffA + "_HScaled.root";
+TString fileOff2     = path + dataOffB + "_HScaled.root";
+
+TString fileRateCFac = path + "Mkn421A+B_CFac.dat";
+TString fileLCurve   = path + "Mkn421A+B_LCurve.dat";
+TString fileAPlots   = path + "Mkn421A+B_APlot.root";
+
+// matrices needed for cut optimization, optimize on sample A
+TString fileOptOn    = path + dataOnA  + "_HScaledC.root";
+TString fileOptOff   = path + dataOffA + "_HScaled.root";
+
+TString fileMatOn    = path + dataOnA  + "_Matrix.root";
+TString fileMatOff   = path + dataOffA + "_Matrix.root";
+
+//--------------------------------------------------------------------------------------------------------------
+// optimized cuts for 1-dim aplot
+
+//Double_t SizeLo   = 1111.; // #ph
+Double_t SizeLo   = 2000.; // #ph
+Double_t DistLo   = 0.55;
+Double_t DistUp   = 1.27;
+//Double_t DistLo   = 1.;
+//Double_t DistUp   = 1.5;
+//Double_t DistLo   = 0.5;
+//Double_t DistUp   = 1.22;
+
+// optimized on half of sample A for scaled Hillas with dist-cut 0.6 - 1.25, size > 1300
+Double_t LengthLo = 0.318;
+Double_t LengthUp = 0.809;
+Double_t WidthLo  = 0.3;
+Double_t WidthUp  = 0.705;
+//*/
Index: trunk/MagicSoft/Mars/mtemp/mberlin/macros/ScaleHillas.C
===================================================================
--- trunk/MagicSoft/Mars/mtemp/mberlin/macros/ScaleHillas.C	(revision 4137)
+++ trunk/MagicSoft/Mars/mtemp/mberlin/macros/ScaleHillas.C	(revision 4137)
@@ -0,0 +1,626 @@
+#include "TH1F.h"
+#include "TH2F.h"
+#include "TH3F.h"
+#include "TLine.h"
+#include "TTree.h"
+
+#include "TCanvas.h"
+#include "TStyle.h"
+#include "TString.h"
+#include "TFile.h"
+#include "TMath.h"
+
+#include "MReadTree.h"
+#include "MSrcPosCam.h"
+#include "MWriteRootFile.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+
+#include "MTaskInteractive.h"
+
+#include "iostream.h"
+#include "stdlib.h"
+#include "stdio.h"
+#include "string.h"
+
+//--------------------------------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//--------------------------------------------------------------------------------------
+
+Double_t estposx =  0.;
+Double_t estposy =  0.;
+
+//--------------------------------------------------------------------------------------
+// setting for hists
+const Int_t nBinSize=200;
+const Int_t nBinDist=1;
+const Int_t nBinLW=1000;
+
+// limits for size and dist for histograms
+Double_t hSizeLo=2.;
+Double_t hSizeUp=6.;
+Double_t hDistLo=0.5;
+Double_t hDistUp=1.15;
+
+// limits for length, width for histograms
+Double_t hLengthLo=0.;
+Double_t hLengthUp=0.8;
+Double_t hWidthLo =0.;
+Double_t hWidthUp =0.6;
+
+// limits for scaled Hillas for histograms
+Double_t hSLenLo =0.;
+Double_t hSLenUp =15.;
+Double_t hSWidLo =0.;
+Double_t hSWidUp =7.;
+
+// special limits for hLength, hWidth (see ReadHillas())
+const Int_t nBinLWFine=1000;
+Double_t hLenFineLo=0.;
+Double_t hLenFineUp=1.;
+Double_t hWidFineLo=0.;
+Double_t hWidFineUp=1.;
+
+// hists for mean of unscaled Hillas
+TH2F hLenMean("hLenMean","",nBinSize,hSizeLo,hSizeUp, nBinDist,hDistLo,hDistUp);
+TH2F hWidMean("hWidMean","",nBinSize,hSizeLo,hSizeUp, nBinDist,hDistLo,hDistUp);
+
+TH1F hLenMeanSize("hLenMeanSize","",nBinSize,hSizeLo,hSizeUp);
+TH1F hLenMeanDist("hLenMeanDist","",nBinDist,hDistLo,hDistUp);
+TH1F hWidMeanSize("hWidMeanSize","",nBinSize,hSizeLo,hSizeUp);
+TH1F hWidMeanDist("hWidMeanDist","",nBinDist,hDistLo,hDistUp);
+
+// hists for unscaled Hillas
+TH2F hLenSize("hLenSize","",nBinSize,hSizeLo,hSizeUp, nBinLW,hLengthLo,hLengthUp);
+TH2F hLenDist("hLenDist","",nBinDist,hDistLo,hDistUp, nBinLW,hLengthLo,hLengthUp);
+
+TH2F hWidSize("hWidSize","",nBinSize,hSizeLo,hSizeUp, nBinLW,hWidthLo,hWidthUp);
+TH2F hWidDist("hWidDist","",nBinDist,hDistLo,hDistUp, nBinLW,hWidthLo,hWidthUp);
+
+// hists for mean-scaled Hillas
+TH2F hSLenSize("hSLenSize","",nBinSize,hSizeLo,hSizeUp,nBinLW,hSLenLo,hSLenUp);
+TH2F hSLenDist("hSLenDist","",nBinDist,hDistLo,hDistUp,nBinLW,hSLenLo,hSLenUp);
+
+TH2F hSWidSize("hSWidSize","",nBinSize,hSizeLo,hSizeUp,nBinLW,hSWidLo,hSWidUp);
+TH2F hSWidDist("hSWidDist","",nBinDist,hDistLo,hDistUp,nBinLW,hSWidLo,hSWidUp);
+
+
+//****************************************************************************************
+// first part: prepare for scaling, read Hillas to calc mean
+//****************************************************************************************
+
+void ReadHillas()
+{
+    // fill hillas into histograms to calc mean
+    TFile *file=new TFile(fileHillas.Data());
+    TTree *fEvents=(TTree*)file->Get("Events");
+
+    // hists for Hillas
+    // in following 2  hists the binning in length/width should be
+    // very fine (like unbinned) and the limits should be generous
+    TH3F hLength("hLength","",nBinSize,hSizeLo,hSizeUp, nBinDist,hDistLo,hDistUp, nBinLWFine,hLenFineLo,hLenFineUp);
+    TH3F hWidth("hWidth",  "",nBinSize,hSizeLo,hSizeUp, nBinDist,hDistLo,hDistUp, nBinLWFine,hWidFineLo,hWidFineUp);
+
+    TString strlen = Form("MHillas.fLength*%f:MHillasSrc.fDist*%f:log10(MHillas.fSize)",mm2deg,mm2deg);
+    TString strwid = Form("MHillas.fWidth*%f :MHillasSrc.fDist*%f:log10(MHillas.fSize)",mm2deg,mm2deg);
+
+    TString strcut="MHillas.fSize>0";
+    fEvents->Project("hLength",strlen.Data(),strcut.Data());
+    fEvents->Project("hWidth", strwid.Data(),strcut.Data());
+
+    file->Close();
+
+    // fill hists hLenMean, hWidMean (2-dim (size,dist)-hists)
+    for(Int_t i=1;i<=nBinSize;i++)
+        for(Int_t j=1;j<=nBinDist;j++)
+        {
+            Double_t lsum=0.; Double_t lsum2=0.; Double_t lcnt=0.;
+            Double_t wsum=0.; Double_t wsum2=0.; Double_t wcnt=0.;
+
+            for(Int_t k=1;k<=nBinLWFine;k++)
+            {
+                Double_t nl = hLength.GetBinContent(i,j,k);
+                Double_t xl = hLength.GetZaxis()->GetBinCenter(k);
+                
+                lsum +=nl*xl;
+                lsum2+=nl*xl*xl;
+                lcnt +=nl;
+
+                Double_t nw = hWidth.GetBinContent(i,j,k);
+                Double_t xw = hWidth.GetZaxis()->GetBinCenter(k);
+
+                wsum +=nw*xw;
+                wsum2+=nw*xw*xw;
+                wcnt +=nw;
+            }
+
+            Double_t lmean=0.;
+            Double_t lmeanerr=0.;
+            if(lcnt>1)lmean=lsum/lcnt;
+            if(lcnt>2)lmeanerr=(lsum2/lcnt-lmean*lmean)/(lcnt-1.);
+            lmeanerr=TMath::Sqrt(lmeanerr);
+
+            hLenMean.SetBinContent(i,j,lmean);
+            hLenMean.SetBinError(i,j,lmeanerr);
+
+            Double_t wmean=0.;
+            Double_t wmeanerr=0.;
+            if(wcnt>1)wmean=wsum/wcnt;
+            if(wcnt>2)wmeanerr=(wsum2/wcnt-wmean*wmean)/(wcnt-1.);
+            wmeanerr=TMath::Sqrt(wmeanerr);
+
+            hWidMean.SetBinContent(i,j,wmean);
+            hWidMean.SetBinError(i,j,wmeanerr);
+        }
+
+    // fill hists hLenMeanSize, hWidMeanSize (1-dim hists, x-axis = size)
+    for(Int_t i=1;i<=nBinSize;i++)
+    {
+        Double_t lsum=0.; Double_t lsum2=0.; Double_t lcnt=0.;
+        Double_t wsum=0.; Double_t wsum2=0.; Double_t wcnt=0.;
+
+        for(Int_t j=1;j<=nBinDist;j++)
+            for(Int_t k=1;k<=nBinLWFine;k++)
+            {
+                Double_t nl = hLength.GetBinContent(i,j,k);
+                Double_t xl = hLength.GetZaxis()->GetBinCenter(k);
+                
+                lsum +=nl*xl;
+                lsum2+=nl*xl*xl;
+                lcnt +=nl;
+
+                Double_t nw = hWidth.GetBinContent(i,j,k);
+                Double_t xw = hWidth.GetZaxis()->GetBinCenter(k);
+
+                wsum +=nw*xw;
+                wsum2+=nw*xw*xw;
+                wcnt +=nw;
+            }
+
+        Double_t lmean=0.;
+        Double_t lmeanerr=0.;
+        if(lcnt>1)lmean=lsum/lcnt;
+        if(lcnt>2)lmeanerr=(lsum2/lcnt-lmean*lmean)/(lcnt-1.);
+        lmeanerr=TMath::Sqrt(lmeanerr);
+
+        hLenMeanSize.SetBinContent(i,lmean);
+        hLenMeanSize.SetBinError(i,lmeanerr);
+
+        Double_t wmean=0.;
+        Double_t wmeanerr=0.;
+        if(wcnt>1)wmean=wsum/wcnt;
+        if(wcnt>2)wmeanerr=(wsum2/wcnt-wmean*wmean)/(wcnt-1.);
+        wmeanerr=TMath::Sqrt(wmeanerr);
+
+        hWidMeanSize.SetBinContent(i,wmean);
+        hWidMeanSize.SetBinError(i,wmeanerr);
+    }
+
+    // fill hists hLenMeanDist, hWidMeanDist (1-dim hists, x-axis = dist)
+    for(Int_t j=1;j<=nBinDist;j++)
+    {
+        Double_t lsum=0.; Double_t lsum2=0.; Double_t lcnt=0.;
+        Double_t wsum=0.; Double_t wsum2=0.; Double_t wcnt=0.;
+
+        for(Int_t i=1;i<=nBinSize;i++)
+            for(Int_t k=1;k<=nBinLWFine;k++)
+            {
+                Double_t nl = hLength.GetBinContent(i,j,k);
+                Double_t xl = hLength.GetZaxis()->GetBinCenter(k);
+                
+                lsum +=nl*xl;
+                lsum2+=nl*xl*xl;
+                lcnt +=nl;
+
+                Double_t nw = hWidth.GetBinContent(i,j,k);
+                Double_t xw = hWidth.GetZaxis()->GetBinCenter(k);
+
+                wsum +=nw*xw;
+                wsum2+=nw*xw*xw;
+                wcnt +=nw;
+            }
+
+        Double_t lmean=0.;
+        Double_t lmeanerr=0.;
+        if(lcnt>1)lmean=lsum/lcnt;
+        if(lcnt>2)lmeanerr=(lsum2/lcnt-lmean*lmean)/(lcnt-1.);
+        lmeanerr=TMath::Sqrt(lmeanerr);
+
+        hLenMeanDist.SetBinContent(j,lmean);
+        hLenMeanDist.SetBinError(j,lmeanerr);
+
+        Double_t wmean=0.;
+        Double_t wmeanerr=0.;
+        if(wcnt>1)wmean=wsum/wcnt;
+        if(wcnt>2)wmeanerr=(wsum2/wcnt-wmean*wmean)/(wcnt-1.);
+        wmeanerr=TMath::Sqrt(wmeanerr);
+
+        hWidMeanDist.SetBinContent(j,wmean);
+        hWidMeanDist.SetBinError(j,wmeanerr);
+    }
+
+    return;
+}
+
+
+//****************************************************************************************
+// second part: do scaling
+//****************************************************************************************
+
+// pointer to Hillas ParContainer
+MHillas *fHillas=NULL;
+MHillasSrc *fHillasSrc=NULL;
+
+
+Int_t PreProcess(MParList *plist)
+{
+    fHillas = (MHillas*) plist->FindObject("MHillas");
+    fHillasSrc = (MHillasSrc*) plist->FindObject("MHillasSrc");
+
+    return (fHillas && fHillasSrc) ? kTRUE : kFALSE;
+}
+
+Int_t Process()
+{
+    // estimated source pos.
+    MSrcPosCam srcpos;
+    srcpos.SetXY(estposx*deg2mm,estposy*deg2mm);
+    fHillasSrc->SetSrcPos(&srcpos);
+    fHillasSrc->Calc(fHillas);
+
+    Float_t width   = fHillas->GetWidth();
+    Float_t length  = fHillas->GetLength();
+    Float_t size    = fHillas->GetSize();
+    Float_t meanx   = fHillas->GetMeanX();
+    Float_t meany   = fHillas->GetMeanY();
+    Float_t logsize = TMath::Log10(fHillas->GetSize());
+    Float_t delta   = fHillas->GetDelta();
+    Float_t dist    = fHillasSrc->GetDist();
+
+    width *=mm2deg;
+    length*=mm2deg;
+    dist  *=mm2deg;
+
+    hLenSize.Fill(logsize,length);
+    hLenDist.Fill(dist,length);
+    hWidSize.Fill(logsize,width);
+    hWidDist.Fill(dist,width);
+
+    // (log(size), dist) - bin
+    Int_t ix=hLenMean.GetXaxis()->FindBin(logsize);
+    Int_t iy=hLenMean.GetYaxis()->FindBin(dist);
+
+    // check for over-/underflow
+    /*if(ix*iy==0 || ix>nBinSize || iy>nBinDist)
+    {
+        cout<<"Warning, over-/underflow: Log(size)-bin="<<ix;
+        cout<<" Dist-bin="<<iy<<endl<<flush;
+    }*/
+    if(ix==0)ix=1;if(ix==nBinSize+1)ix=nBinSize;
+    if(iy==0)iy=1;if(iy==nBinDist+1)iy=nBinDist;
+
+    Float_t lq=hLenMean.GetBinContent(ix,iy);
+    Float_t wq=hWidMean.GetBinContent(ix,iy);
+
+    if(lq>0.)lq=1./lq;
+    if(wq>0.)wq=1./wq;
+
+    width *=wq;
+    length*=lq;
+
+    hSLenSize.Fill(logsize,length);
+    hSLenDist.Fill(dist,length);
+    hSWidSize.Fill(logsize,width);
+    hSWidDist.Fill(dist,width);
+
+    // --------------------------------------------------------------------------
+    //
+    // This function is ment for special usage, please never try to set
+    // values via this function
+    //
+    /* void MHillas::Set(const TArrayF &arr)
+    {
+        if (arr.GetSize() != 6)
+            return;
+    
+        fLength = arr.At(0);  // [mm]        major axis of ellipse
+        fWidth  = arr.At(1);  // [mm]        minor axis of ellipse
+        fDelta  = arr.At(2);  // [rad]       angle of major axis with x-axis
+        fSize   = arr.At(3);  // [#CerPhot]  sum of content of all pixels (number of Cherenkov photons)
+        fMeanX  = arr.At(4);  // [mm]        x-coordinate of center of ellipse
+        fMeanY  = arr.At(5);  // [mm]        y-coordinate of center of ellipse
+    }*/
+
+    TArrayF farr(6);
+    farr[0]=length;
+    farr[1]=width;
+    farr[2]=delta;
+    farr[3]=size;
+    farr[4]=meanx;
+    farr[5]=meany;
+
+    fHillas->Set(farr);
+
+    fHillas->SetReadyToSave();
+    fHillasSrc->SetReadyToSave();
+
+    return kTRUE;
+}
+
+Int_t PostProcess()
+{
+
+    return kTRUE;
+}
+
+void ScaleHillas(Int_t nent)
+{
+    //---------------------------------------------------------------
+    // scale Hillas (length, width) to mean
+
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadTree read("Events", fileHillas);
+    read.DisableAutoScheme();
+
+    MTaskInteractive scale;
+    scale.SetPreProcess(PreProcess);
+    scale.SetProcess(Process);
+    scale.SetPostProcess(PostProcess);
+
+    MWriteRootFile write(fileHScaled.Data());
+    write.AddContainer("MHillas",      "Events");
+    write.AddContainer("MHillasExt",   "Events");
+    write.AddContainer("MHillasSrc",   "Events");
+    write.AddContainer("MNewImagePar", "Events");
+    write.AddContainer("MRawRunHeader","Events");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&scale);
+    tlist.AddToList(&write);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop(nent))
+        return;
+
+    tlist.PrintStatistics();
+
+    return;
+}
+
+
+//****************************************************************************************
+// third part: check scaling
+//****************************************************************************************
+
+void CheckScaling()
+{
+    //---------------------------------------------------------------
+    // check scaling
+    TFile fileHist(fileHScalHist,"recreate");
+
+    gStyle->SetPalette(1);
+
+
+    TCanvas *c1=new TCanvas("c1","",800,400);
+    if(nBinDist>1)
+        c1->Divide(2,2);
+    else
+        c1->Divide(2,1);
+
+    c1->cd(1);
+    gPad->SetGrid();
+    hSLenSize.SetStats(kFALSE);
+    hSLenSize.GetXaxis()->SetTitle("log(size [#phot])");
+    hSLenSize.GetYaxis()->SetTitle("scaled length");
+    hSLenSize.SetLineWidth(2);
+    hSLenSize.DrawCopy("colz");
+    hSLenSize.Write();
+
+    TLine lLen(2.7,1.,hSizeUp,1.);
+    TLine lLenUp(2.7,LengthUp,hSizeUp,LengthUp);
+    TLine lLenLo(2.7,LengthLo,hSizeUp,LengthLo);
+
+    lLen.SetLineColor(2);
+    lLen.SetLineWidth(2);
+    lLenUp.SetLineWidth(2);
+    lLenLo.SetLineWidth(2);
+    lLen.DrawClone();
+    lLenUp.DrawClone();
+    lLenLo.DrawClone();
+
+
+    c1->cd(2);
+    gPad->SetGrid();
+    hLenSize.SetStats(kFALSE);
+    hLenSize.SetTitle("");
+    hLenSize.GetXaxis()->SetTitle("log(size [#phot])");
+    hLenSize.GetYaxis()->SetTitle("length [deg]");
+    hLenSize.SetLineWidth(2);
+    hLenSize.DrawCopy("colz");
+    hLenSize.Write();
+    hLenMeanSize.SetLineColor(2);
+    hLenMeanSize.SetLineWidth(2);
+    hLenMeanSize.DrawCopy("e same");
+    hLenMeanSize.Write();
+
+    TH1F hLenCutLo("hLenCutLo","",nBinSize,hSizeLo,hSizeUp);
+    TH1F hLenCutUp("hLenCutUp","",nBinSize,hSizeLo,hSizeUp);
+    for(Int_t i=1;i<=nBinSize;i++)
+    {
+        Float_t meanval=hLenMeanSize.GetBinContent(i);
+        hLenCutLo.SetBinContent(i,meanval*LengthLo);
+        hLenCutUp.SetBinContent(i,meanval*LengthUp);
+    }
+    hLenCutLo.SetLineWidth(2);
+    hLenCutUp.SetLineWidth(2);
+    hLenCutLo.DrawCopy("][ same");
+    hLenCutUp.DrawCopy("][ same");
+
+
+    if(nBinDist>1)
+    {
+        c1->cd(3);
+        gPad->SetGrid();
+        hSLenDist.SetStats(kFALSE);
+        hSLenDist.GetXaxis()->SetTitle("dist [deg]");
+        hSLenDist.GetYaxis()->SetTitle("scaled length");
+        hSLenDist.SetLineWidth(2);
+        hSLenDist.DrawCopy("colz");
+        hSLenDist.Write();
+    
+        c1->cd(4);
+        gPad->SetGrid();
+        hLenDist.SetStats(kFALSE);
+        hLenDist.SetTitle("");
+        hLenDist.GetXaxis()->SetTitle("dist [deg]");
+        hLenDist.GetYaxis()->SetTitle("length");
+        hLenDist.SetLineWidth(2);
+        hLenDist.DrawCopy("colz");
+        hLenDist.Write();
+        hLenMeanDist.SetLineColor(2);
+        hLenMeanDist.SetLineWidth(2);
+        hLenMeanDist.DrawCopy("e same");
+        hLenMeanDist.Write();
+    }
+
+    TCanvas *c2=new TCanvas("c2","",800,400);
+    if(nBinDist>1)
+        c2->Divide(2,2);
+    else
+        c2->Divide(2,1);
+
+    c2->cd(1);
+    gPad->SetGrid();
+    hSWidSize.SetStats(kFALSE);
+    hSWidSize.GetXaxis()->SetTitle("log(size [#phot])");
+    hSWidSize.GetYaxis()->SetTitle("scaled width");
+    hSWidSize.SetLineWidth(2);
+    hSWidSize.DrawCopy("colz");
+    hSWidSize.Write();
+
+    TLine lWid(2.7,1.,hSizeUp,1.);
+    TLine lWidUp(2.7,WidthUp,hSizeUp,WidthUp);
+    TLine lWidLo(2.7,WidthLo,hSizeUp,WidthLo);
+
+    lWid.SetLineColor(2);
+    lWid.SetLineWidth(2);
+    lWidUp.SetLineWidth(2);
+    lWidLo.SetLineWidth(2);
+    lWid.DrawClone();
+    lWidUp.DrawClone();
+    lWidLo.DrawClone();
+
+    c2->cd(2);
+    gPad->SetGrid();
+    hWidSize.SetStats(kFALSE);
+    hWidSize.SetTitle("");
+    hWidSize.GetXaxis()->SetTitle("log(size [#phot])");
+    hWidSize.GetYaxis()->SetTitle("width [deg]");
+    hWidSize.SetLineWidth(2);
+    hWidSize.DrawCopy("colz");
+    hWidSize.Write();
+    hWidMeanSize.SetLineColor(2);
+    hWidMeanSize.SetLineWidth(2);
+    hWidMeanSize.DrawCopy("e same");
+    hWidMeanSize.Write();
+
+    TH1F hWidCutLo("hWidCutLo","",nBinSize,hSizeLo,hSizeUp);
+    TH1F hWidCutUp("hWidCutUp","",nBinSize,hSizeLo,hSizeUp);
+    for(Int_t i=1;i<=nBinSize;i++)
+    {
+        Float_t meanval=hWidMeanSize.GetBinContent(i);
+        hWidCutLo.SetBinContent(i,meanval*WidthLo);
+        hWidCutUp.SetBinContent(i,meanval*WidthUp);
+    }
+    hWidCutLo.SetLineWidth(2);
+    hWidCutUp.SetLineWidth(2);
+    hWidCutLo.DrawCopy("][ same");
+    hWidCutUp.DrawCopy("][ same");
+
+    if(nBinDist>1)
+    {
+        c2->cd(3);
+        gPad->SetGrid();
+        hSWidDist.SetStats(kFALSE);
+        hSWidDist.GetXaxis()->SetTitle("dist [deg]");
+        hSWidDist.GetYaxis()->SetTitle("scaled width");
+        hSWidDist.SetLineWidth(2);
+        hSWidDist.DrawCopy("colz");
+        hSWidDist.Write();
+    
+        c2->cd(4);
+        gPad->SetGrid();
+        hWidDist.SetStats(kFALSE);
+        hWidDist.SetTitle("");
+        hWidDist.GetXaxis()->SetTitle("dist [deg]");
+        hWidDist.GetYaxis()->SetTitle("width");
+        hWidDist.SetLineWidth(2);
+        hWidDist.DrawCopy("colz");
+        hWidDist.Write();
+        hWidMeanDist.SetLineColor(2);
+        hWidMeanDist.SetLineWidth(2);
+        hWidMeanDist.DrawCopy("e same");
+        hWidMeanDist.Write();
+    }
+
+    // mean values
+    if(nBinDist>1)
+    {
+        TCanvas *c4=new TCanvas("c4","",800,400);
+        c4->Divide(1,2);
+    
+        c4->cd(1);
+        gPad->SetGrid();
+        hLenMean.SetStats(kFALSE);
+        hLenMean.SetTitle("mean_length(log(size),dist)");
+        hLenMean.GetXaxis()->SetTitle("log(size [#phot])");
+        hLenMean.GetYaxis()->SetTitle("dist [deg])");
+        hLenMean.DrawCopy("colz");
+        hLenMean.Write();
+    
+        c4->cd(2);
+        gPad->SetGrid();
+        hWidMean.SetStats(kFALSE);
+        hWidMean.SetTitle("mean_width(log(size),dist)");
+        hWidMean.GetXaxis()->SetTitle("log(size [#phot])"); ;
+        hWidMean.GetYaxis()->SetTitle("dist [deg])");
+        hWidMean.DrawCopy("colz");
+        hWidMean.Write("colz");
+    }
+
+    fileHist.Close();
+
+    return;
+}
+
+//****************************************************************************************
+// main
+//****************************************************************************************
+
+void RunScaling(Int_t nent=-1)
+{
+    printf("Prepare for scaling...");
+    ReadHillas();
+    printf("done.\n");
+
+    ScaleHillas(nent);
+
+    CheckScaling();
+
+    return;
+}
+
Index: trunk/MagicSoft/Mars/mtemp/mberlin/macros/SrcCorrect.C
===================================================================
--- trunk/MagicSoft/Mars/mtemp/mberlin/macros/SrcCorrect.C	(revision 4137)
+++ trunk/MagicSoft/Mars/mtemp/mberlin/macros/SrcCorrect.C	(revision 4137)
@@ -0,0 +1,768 @@
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MReadTree.h"
+
+#include "MHillasSrc.h"
+#include "MSrcPosCam.h"
+
+#include "MHillasCalc.h"
+#include "MHillasSrcCalc.h"
+#include "MTaskInteractive.h"
+#include "MContinue.h"
+#include "MRawRunHeader.h"
+#include "MWriteRootFile.h"
+
+#include "TH2F.h"
+#include "TF2.h"
+#include "TArrayF.h"
+#include "TObjArray.h"
+#include "TStyle.h"
+#include "TFile.h"
+#include "TMath.h"
+#include "TString.h"
+#include "TCanvas.h"
+#include "TGraphErrors.h"
+#include "TMarker.h"
+
+#include "iostream.h"
+
+//----------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//----------------------------------------------------------------
+
+Double_t rmean=0.3;
+Double_t dtlimit=10;  // time slice width [min]
+//Double_t hlimit =0.85;
+Double_t hlimit =0.9;
+
+//----------------------------------------------------------------
+// false source hist ---------------------------------------------
+//----------------------------------------------------------------
+const Int_t nx = 100; // no. of points in x-grid
+const Int_t ny = 100; // no. of points in y-grid
+
+Double_t alimit = 8.; // signal region in alpha-plot [degree]
+
+Double_t xmin = -1.;  // units in degree !!
+Double_t xmax =  1.;
+Double_t ymin = -1.;
+Double_t ymax =  1.;
+
+Double_t dx=(xmax-xmin)/Double_t(nx);
+Double_t dy=(ymax-ymin)/Double_t(ny);
+
+TH2F FSrcHist("FSrcHist","",nx,xmin-dx,xmax+dx,ny,ymin-dy,ymax+dy);
+TObjArray FSrcArray(1);
+
+TH1F APlot("APlot","",36,0,90);
+TObjArray APlotArray(1);
+
+TArrayF xpeak(100);
+TArrayF ypeak(100);
+
+TArrayF xpeakerr(100);
+TArrayF ypeakerr(100);
+
+Int_t runno     = -1;
+Int_t runno_old = -1;
+Int_t runno_lo  = -1;
+Int_t runno_up  = -1;
+
+Double_t mjdend_old  = -1.;
+Double_t mjdstart_lo = -1.;
+Double_t mjdstart_up = -1.;
+
+Double_t mjd_lo  = -1.;
+Double_t mjd_up  = -1.;
+
+Double_t dt  = 0.;
+Int_t islice = 0;
+
+TF2  *fpeak   = NULL;
+FILE *fsrcpos = NULL;
+
+//****************************************************************************************
+// first part: track the source in time-intervalls of duration dtlimit
+//****************************************************************************************
+
+MHillas       *hil=NULL;
+MRawRunHeader *run=NULL;
+
+Double_t gaus2d(Double_t *x,Double_t *par)
+{
+    Double_t N=par[0];  //integral
+    Double_t mx=par[1]; //mean_x
+    Double_t my=par[2]; //mean_y
+    Double_t sx=par[3]; //sigma_x
+    Double_t sy=par[4]; //sigma_y
+    Double_t rho=par[5];//correlation factor
+    Double_t b=par[6];  //constant background
+
+    Double_t z=(x[0]-mx)*(x[0]-mx)/sx/sx;
+    z+=(x[1]-my)*(x[1]-my)/sy/sy;
+    z-=2.*rho*(x[0]-mx)*(x[1]-my)/sx/sy;
+
+    Double_t val=N/(2.*TMath::Pi()*sx*sy*sqrt(1-rho*rho));
+    val*=exp( -z/(2.*(1.-rho*rho)) );
+    val+=b;
+    return val;
+}
+
+Bool_t CalcPeakXY(Double_t *xmean, Double_t *ymean,
+                  Double_t *xmeanerr, Double_t *ymeanerr)
+{
+    Int_t mbin=FSrcHist.GetMaximumBin();
+    Int_t biny = mbin/(nx+2);
+    Int_t binx = mbin%(nx+2);
+  
+    if(mbin!=FSrcHist.GetBin(binx,biny))
+    {
+        cout<<"Error extracting binx, biny from global bin!"<<endl;
+        cout<<" mbin="<<mbin<<" binfound="<<FSrcHist.GetBin(binx,biny)<<endl;
+        cout<<" binx="<<binx<<" biny="<<biny<<endl;
+  
+        return kFALSE;
+    }
+  
+    Double_t ndelta = rmean/FSrcHist.GetBinWidth(mbin);
+
+    Double_t nmax=FSrcHist.GetBinContent(binx,biny);
+
+    Int_t ilo=Int_t(binx-ndelta);
+    Int_t iup=Int_t(binx+ndelta);
+
+    Int_t jlo=Int_t(biny-ndelta);
+    Int_t jup=Int_t(biny+ndelta);
+
+    Double_t xsum  = 0.; Double_t xsum2 = 0.;
+    Double_t ysum  = 0.; Double_t ysum2 = 0.;
+    Double_t cnt   = 0.;
+    //Double_t cov   = 0.;
+
+    for(Int_t i=ilo;i<=iup;i++)
+        for(Int_t j=jlo;j<=jup;j++)
+        {
+            Double_t n=(Double_t)FSrcHist.GetBinContent(i,j);
+            if(n<hlimit*nmax)continue;
+            Double_t x=(Double_t)FSrcHist.GetXaxis()->GetBinCenter(i);
+            Double_t y=(Double_t)FSrcHist.GetYaxis()->GetBinCenter(j);
+
+            cnt+=n;
+
+            xsum +=n*x;
+            xsum2+=n*x*x;
+            ysum +=n*y;
+            ysum2+=n*y*y;
+        }
+
+    Double_t xbar=0.; Double_t xbarerr=0.;
+    Double_t ybar=0.; Double_t ybarerr=0.;
+
+    if(cnt>1)
+    {
+        xbar=xsum/cnt;
+        ybar=ysum/cnt;
+    }
+    if(cnt>2)
+    {
+        xbarerr=cnt*(xsum2/cnt-xbar*xbar)/(cnt-1.);
+        xbarerr=TMath::Sqrt(xbarerr);
+
+        ybarerr=cnt*(ysum2/cnt-ybar*ybar)/(cnt-1.);
+        ybarerr=TMath::Sqrt(ybarerr);
+    }
+
+    /*
+    //fit not yet tested!!
+    Double_t b=FSrcHist.GetEntries()/nx/ny;
+    Double_t nn=b*ndelta*ndelta;
+
+    fpeak->SetParameter(0,nn);     // integral
+    fpeak->SetParameter(1,*xmean); // mean_x
+    fpeak->SetParameter(2,*ymean); // mean_y
+    fpeak->SetParameter(3,0.15);   // sigma_x
+    fpeak->SetParameter(4,0.15);   // sigma_y
+    fpeak->SetParameter(5,0.);     // correlation factor
+    fpeak->SetParameter(6,b);      // constant background
+
+    FSrcHist.Fit("fpeak");
+    xbar=fpeak->GetParameter(1);
+    ybar=fpeak->GetParameter(2);
+    xbarerr=fpeak->GetParameter(3);
+    ybarerr=fpeak->GetParameter(4);
+    */
+
+    *xmean=xbar;
+    *ymean=ybar;
+    *xmeanerr=xbarerr;
+    *ymeanerr=ybarerr;
+
+    return kTRUE;
+}
+
+void AddFSrcHist(Int_t i,Double_t delta)
+{
+    Int_t n=FSrcArray.GetSize();
+    if(i>=n) FSrcArray.Expand(n+1);
+
+    TH2F *htemp=(TH2F*)FSrcHist.Clone();
+    TString name=Form("%d",i);
+    TString title=Form("TimeIntervall = %f min",delta);
+
+    htemp->SetName(name.Data());
+    htemp->SetTitle(title.Data());
+    htemp->SetDrawOption("colz");
+
+    FSrcArray[i] = htemp;
+
+    return;
+}
+
+void AddAPlot(Int_t i,Double_t delta)
+{
+    Int_t n=APlotArray.GetSize();
+    if(i>=n) APlotArray.Expand(n+1);
+
+    TH1F *htemp=(TH1F*)APlot.Clone();
+    TString name=Form("%d",i);
+    TString title=Form("TimeIntervall = %f min",delta);
+
+    htemp->SetName(name.Data());
+    htemp->SetTitle(title.Data());
+    htemp->SetFillColor(16);
+
+    APlotArray[i] = htemp;
+
+    return;
+}
+
+//----------------------------------------------------------------
+// Source Position Grid ------------------------------------------
+//----------------------------------------------------------------
+
+Int_t STrackPreProc(MParList *plist)
+{
+    hil = (MHillas*) plist->FindObject("MHillas");
+    run = (MRawRunHeader*) plist->FindObject("MRawRunHeader");
+
+    return (hil && run) ? kTRUE : kFALSE;
+}
+
+Int_t STrackProc()
+{
+    runno  = run->GetRunNumber();
+    if(runno==0) return kTRUE;
+
+    Double_t mjdstart = (run->GetRunStart()).GetMjd();
+    Double_t mjdend   = (run->GetRunEnd()).GetMjd();
+    Double_t t = (mjdend-mjdstart)*24.*60.;
+
+    Double_t dtrun;
+    if(runno!=runno_old)
+    {
+        if(dt<0.001) {runno_lo=runno;mjd_lo=mjdstart;mjdend_old=mjdstart;} // very first run
+
+        dtrun=(mjdend_old-mjd_lo)*24.*60.;
+        //if(dt>dtlimit)
+        if(dtrun>dtlimit)
+        {
+            runno_up=runno_old;
+            mjd_up=mjdend_old;
+
+            Double_t x; Double_t xerr;
+            Double_t y; Double_t yerr;
+
+            if(!CalcPeakXY(&x,&y,&xerr,&yerr)) return kFALSE;
+            AddFSrcHist(islice,dt);
+
+            xpeak[islice]=x;
+            ypeak[islice]=y;
+            xpeakerr[islice]=xerr;
+            ypeakerr[islice]=yerr;
+
+            printf("\n TimeSlice %d   RunNo %d-%d  Mjd %f-%f  Dt=%f \n",islice,runno_lo,runno_up,mjd_lo,mjd_up,dt);
+            printf(" X=%f+-%f  Y=%f+-%f \n\n",x,xerr,y,yerr);
+            fprintf(fsrcpos,"%d %d %d %f %f %f %f %f %f %f\n",islice,runno_lo,runno_up,x,y,xerr,yerr,mjd_lo,mjd_up,dt);
+
+            FSrcHist.Reset();
+            dt=0.;
+
+            runno_lo=runno;
+            mjd_lo=mjdstart;
+
+            islice++;
+        }
+
+        dt+=t;
+        printf("Runno=%d  MjdStart=%f  MjdEnde=%f dt=%f \n",runno,mjdstart,mjdend,dt);
+        runno_old=runno;
+        mjdend_old=mjdend;
+    }
+
+
+    MHillasSrc hillas_src;
+    MSrcPosCam srcpos;
+
+    Double_t length=hil->GetLength();
+    Double_t width=hil->GetWidth();
+
+    // size cut
+    if(hil->GetSize()<SizeLo) return kTRUE;
+
+    // cuts in scaled length, width
+    if((length>LengthUp) || (length<LengthLo) || (width>WidthUp) || (width<WidthLo))
+        return kTRUE;
+
+    // cut in dist from camera center
+    srcpos.SetXY(0,0);
+    hillas_src.SetSrcPos(&srcpos);
+    hillas_src.Calc(hil);
+
+    Double_t dist=hillas_src.GetDist()*mm2deg;
+    if(dist>DistUp || dist<DistLo) return kTRUE;
+
+    // false source grid
+    for (Int_t i=0;i<nx;i++)
+        for (Int_t j=0;j<ny;j++)
+        {
+            Double_t x=(xmax-xmin)*Double_t(i)/Double_t(nx-1)+xmin;
+            Double_t y=(ymax-ymin)*Double_t(j)/Double_t(ny-1)+ymin;
+
+            srcpos.SetXY(x*deg2mm,y*deg2mm);
+            hillas_src.SetSrcPos(&srcpos);
+            hillas_src.Calc(hil);
+
+            if(TMath::Abs(hillas_src.GetAlpha())<alimit)
+                FSrcHist.Fill(x,y);
+
+        }
+
+    return kTRUE;
+}
+
+Int_t STrackPostProc()
+{
+    if(dt>0.001)
+    {
+        runno_up=runno_old;
+        mjd_up=mjdend_old;
+
+        Double_t x; Double_t xerr;
+        Double_t y; Double_t yerr;
+
+        if(!CalcPeakXY(&x,&y,&xerr,&yerr)) return kFALSE;
+        AddFSrcHist(islice,dt);
+
+        xpeak[islice]=x;
+        ypeak[islice]=y;
+        xpeakerr[islice]=xerr;
+        ypeakerr[islice]=yerr;
+
+        printf("\n TimeSlice %d   RunNo %d-%d  Mjd %f-%f  Dt=%f \n",islice,runno_lo,runno_up,mjd_lo,mjd_up,dt);
+        printf(" X=%f+-%f  Y=%f+-%f \n\n",x,xerr,y,yerr);
+        fprintf(fsrcpos,"%d %d %d %f %f %f %f %f %f %f\n",islice,runno_lo,runno_up,x,y,xerr,yerr,mjd_lo,mjd_up,dt);
+
+        islice++;
+    }
+
+    return kTRUE;
+}
+
+//----------------------------------------------------------------
+//----------------------------------------------------------------
+
+void SourceTrack(Int_t nent)
+{
+
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadTree read("Events",fileHScaled);
+    read.DisableAutoScheme();
+
+    //TString runcuts("(MRawRunHeader.fRunNumber<17427)");
+    //runcuts+="|| (MRawRunHeader.fRunNumber>17428)";
+    //MContinue runsel(runcuts.Data());
+
+    MTaskInteractive strack;
+    strack.SetPreProcess(STrackPreProc);
+    strack.SetProcess(STrackProc);
+    strack.SetPostProcess(STrackPostProc);
+
+    tlist.AddToList(&read);
+    //tlist.AddToList(&runsel);
+    tlist.AddToList(&strack);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //------------------------------------------
+    // initializations
+
+    FSrcHist.SetDrawOption("colz");
+    FSrcHist.SetStats(kFALSE);
+
+    fpeak=new TF2("fpeak",gaus2d,-1,1,-1,1,6);
+    fsrcpos=fopen(fileSrcPos.Data(),"w");
+
+    //------------------------------------------
+    // standard eventloop
+
+    if (!evtloop.Eventloop(nent))
+        return;
+
+    tlist.PrintStatistics();
+
+    fclose(fsrcpos);
+
+    TFile file(fileFSrcPlot.Data(),"recreate");
+    FSrcArray.Write();
+    FSrcHist.Write();
+    file.Close();
+
+    const Int_t dim=islice;
+    TGraphErrors g(dim,xpeak.GetArray(),ypeak.GetArray(),
+                   xpeakerr.GetArray(),ypeakerr.GetArray());
+
+    //------------------------------------------
+    // canvas with complete hist
+    TCanvas *c1=new TCanvas("c1","",400,800);
+    gStyle->SetPalette(1);
+
+    c1->Divide(2,1);
+    c1->cd(1);
+    gPad->Update();
+
+    FSrcHist.Reset();
+    for(Int_t i=0;i<dim;i++)
+    {
+        TH2F *hptr = (TH2F*) (FSrcArray[i]);
+        FSrcHist.Add(hptr);
+    }
+
+    TString label=Form("Size>%f  ",SizeLo);
+    label+=Form("%f<Dist<%f  ",  DistLo,DistUp);
+    label+=Form("%f<Width<%f  " ,WidthLo,WidthUp);
+    label+=Form("%f<Length<%f  ",LengthLo,LengthUp);
+    label+=Form("|Alpha|<%f"  ,alimit);
+
+    FSrcHist.SetTitle(label.Data());
+    FSrcHist.GetXaxis()->SetTitle("X");
+    FSrcHist.GetYaxis()->SetTitle("Y");
+
+    FSrcHist.DrawClone("colz");
+    g.DrawClone("pl");
+
+    c1->cd(2);
+    gPad->Update();
+    g.GetXaxis()->SetRangeUser(-1.,1.);
+    g.GetYaxis()->SetRangeUser(-1.,1.);
+    g.DrawClone("apl");
+
+    //------------------------------------------
+    // canvas with slides
+    TCanvas *c2=new TCanvas("c2","",800,800);
+    gStyle->SetPalette(1);
+
+    Int_t n=Int_t(TMath::Ceil(sqrt(double(dim))));
+
+    c2->Divide(n,n);
+    for(Int_t i=0;i<dim;i++)
+    {
+        Int_t col=i/n;
+        Int_t row=i%n;
+        c2->cd(row*n+col+1);
+
+        gPad->Update();
+        TH2F *hptr = (TH2F*) (FSrcArray[i]);
+
+        TMarker m;
+        m.SetMarkerStyle(2);
+        m.SetMarkerSize(4);
+        m.SetMarkerColor(1);
+        m.SetX(xpeak[i]);
+        m.SetY(ypeak[i]);
+
+        hptr->DrawClone("colz");
+        m.DrawClone();
+    }
+
+    return;
+}
+
+//****************************************************************************************
+// second part: correct for moving source position
+//****************************************************************************************
+
+// initilizations
+
+Double_t dtref=0.;
+Int_t islice_old;
+Double_t dtref_old=0;
+
+Double_t xref = 0.; Double_t xreferr = 0.;
+Double_t yref = 0.; Double_t yreferr = 0.;
+
+MSrcPosCam *src=NULL;
+
+//----------------------------------------------------------------
+// Source Position Grid ------------------------------------------
+//----------------------------------------------------------------
+Int_t SCorrectPreProc(MParList *plist)
+{
+    hil = (MHillas*) plist->FindObject("MHillas");
+    src = (MSrcPosCam*) plist->FindCreateObj("MSrcPosCam");
+    run = (MRawRunHeader*) plist->FindObject("MRawRunHeader");
+
+    return (hil && run && src) ? kTRUE : kFALSE;
+}
+
+Int_t SCorrectProc()
+{
+    if(hil->GetSize()<=0.) return kTRUE;
+
+    Int_t runno    = run->GetRunNumber();
+    if(runno==0) return kTRUE;
+
+    Double_t mjdstart = (run->GetRunStart()).GetMjd();
+    Double_t mjdend   = (run->GetRunEnd()).GetMjd();
+    Double_t t=(mjdend-mjdstart)*24.*60.;
+
+    if(runno!=runno_old)
+    {
+        if((runno<runno_lo)||(runno>runno_up))
+        {
+            dt=t;
+
+            fscanf(fsrcpos,"%d %d %d %lf %lf %lf %lf %lf %lf %lf\n",&islice,&runno_lo,&runno_up,&xref,&yref,&xreferr,&yreferr,&mjd_lo,&mjd_up,&dtref);
+            printf("\nApplying correction for runs %d - %d (MJD %f - %f), DtRef=%f :\n",runno_lo,runno_up,mjd_lo,mjd_up,dtref);
+            printf("Source pos set to X=%f  Y=%f \n\n",xref,yref);
+
+            if(islice>0)
+            {
+                AddAPlot(islice_old,dtref_old);
+                APlot.Reset();
+            }
+            islice_old=islice;
+            dtref_old=dtref;
+        }
+        else
+        {
+            dt+=t;
+        }
+        printf("Runno=%d  MjdStart=%f  MjdEnde=%f Dt=%f \n",runno,mjdstart,mjdend,dt);
+        runno_old=runno;
+
+    }
+
+    src->SetXY(xref*deg2mm,yref*deg2mm);
+    src->SetReadyToSave();
+    // false source grid
+
+    MHillasSrc hillas_src;
+    MSrcPosCam srcpos;
+
+    Double_t length=hil->GetLength();
+    Double_t width =hil->GetWidth();
+
+    // size cut
+    if(hil->GetSize()<SizeLo) return kTRUE;
+
+    // cuts in scaled length, width
+    if((length>LengthUp) || (length<LengthLo) || (width>WidthUp) || (width<WidthLo))
+        return kTRUE;
+
+    // cut in dist from camera center
+    srcpos.SetXY(0,0);
+    hillas_src.SetSrcPos(&srcpos);
+    hillas_src.Calc(hil);
+
+    Double_t dist=hillas_src.GetDist()*mm2deg;
+    if(dist>DistUp || dist<DistLo) return kTRUE;
+
+    // fill 1-dim APlot for extracted source position
+    srcpos.SetXY(xref*deg2mm,yref*deg2mm);
+    hillas_src.SetSrcPos(&srcpos);
+    hillas_src.Calc(hil);
+    APlot.Fill(TMath::Abs(hillas_src.GetAlpha()));
+
+    // false source plot for corrected source movement
+    for (Int_t i=0;i<nx;i++)
+        for (Int_t j=0;j<ny;j++)
+        {
+            Double_t x=(xmax-xmin)*Double_t(i)/Double_t(nx-1)+xmin;
+            Double_t y=(ymax-ymin)*Double_t(j)/Double_t(ny-1)+ymin;
+
+            //printf("xref=%f  yref=%f \n",xref,yref);
+            srcpos.SetXY((x+xref)*deg2mm,(y+yref)*deg2mm);
+            hillas_src.SetSrcPos(&srcpos);
+            hillas_src.Calc(hil);
+
+            if(TMath::Abs(hillas_src.GetAlpha())<alimit)
+                FSrcHist.Fill(x,y);
+        }
+
+    return kTRUE;
+}
+
+Int_t SCorrectPostProc()
+{
+    AddAPlot(islice_old,dtref_old);
+
+    return kTRUE;
+}
+
+//----------------------------------------------------------------
+//----------------------------------------------------------------
+
+void SourceCorrect(Int_t nent)
+{
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadTree read("Events", fileHScaled);
+    read.DisableAutoScheme();
+
+    MTaskInteractive scorrect;
+    scorrect.SetPreProcess(SCorrectPreProc);
+    scorrect.SetProcess(SCorrectProc);
+    scorrect.SetPostProcess(SCorrectPostProc);
+
+    MHillasSrcCalc scalc;
+
+    MWriteRootFile write(fileHScaledC.Data());
+    write.AddContainer("MSrcPosCam",   "Events");
+    write.AddContainer("MHillas",      "Events");
+    write.AddContainer("MHillasExt",   "Events");
+    write.AddContainer("MHillasSrc",   "Events");
+    write.AddContainer("MNewImagePar", "Events");
+    write.AddContainer("MRawRunHeader","Events");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&scorrect);
+    tlist.AddToList(&scalc);
+    tlist.AddToList(&write);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //------------------------------------------
+    // standard eventloop
+
+    fsrcpos=fopen(fileSrcPos.Data(),"r");
+    if(!fsrcpos)
+    {
+        cout<<"fsrcpos does not exist!"<<endl;
+        return;
+    }
+
+    if (!evtloop.Eventloop(nent))
+        return;
+
+    tlist.PrintStatistics();
+
+    fclose(fsrcpos);
+
+
+    gStyle->SetPalette(1);
+    TFile file(fileFSrcPlotC.Data(),"recreate");
+    FSrcHist.Write();
+    APlotArray.Write();
+    file.Close();
+
+    //------------------------------------------
+    // canvas with complete hist
+    TCanvas *c=new TCanvas("c","",800,400);
+    c->cd();
+
+    TString label=Form("Size>%f  ",SizeLo);
+    label+=Form("%f<Dist<%f  ",  DistLo,DistUp);
+    label+=Form("%f<Width<%f  " ,WidthLo,WidthUp);
+    label+=Form("%f<Length<%f  ",LengthLo,LengthUp);
+    label+=Form("|Alpha|<%f"  ,alimit);
+
+    FSrcHist.SetTitle(label.Data());
+    FSrcHist.GetXaxis()->SetTitle("X");
+    FSrcHist.GetYaxis()->SetTitle("Y");
+
+    FSrcHist.DrawCopy("colz");
+
+    //------------------------------------------
+    // canvas with alpha hists
+    TCanvas *c2=new TCanvas("c2","",800,800);
+    gStyle->SetPalette(1);
+
+    const Int_t dim=islice+1;
+    Int_t n=Int_t(TMath::Ceil(sqrt(double(dim))));
+
+    c2->Divide(n,n);
+    for(Int_t i=0;i<dim;i++)
+    {
+        Int_t col=i/n;
+        Int_t row=i%n;
+        c2->cd(row*n+col+1);
+
+        gPad->Update();
+        TH1F *hptr = (TH1F*) (APlotArray[i]);
+
+        hptr->DrawClone();
+    }
+
+    return;
+}
+
+//****************************************************************************************
+// main
+//****************************************************************************************
+
+void SrcCorrect(Int_t icorrect,Int_t nent=-1)
+{
+
+    if(!icorrect)
+    {
+        // (re-) initilizations
+        islice=0;
+        runno_old=-1;
+        runno_lo=-1;
+        runno_up=-1;
+
+        dt=0;
+
+        mjd_lo=-1;
+        mjd_up=-1;
+
+        hil=NULL; run=NULL;
+
+        cout<<"Starting source track reconstruction."<<endl<<flush;
+        FSrcHist.Reset();
+        SourceTrack(nent);
+
+    }else{
+
+        // (re-) initilizations
+        islice=0;
+        runno_old=-1;
+        runno_lo=-1;
+        runno_up=-1;
+
+        dt=0;
+
+        mjd_lo=-1;
+        mjd_up=-1;
+
+        hil=NULL; run=NULL;
+
+        cout<<"Starting source correct."<<endl<<flush;
+        FSrcHist.Reset();
+        SourceCorrect(nent);
+    }
+
+    return;
+}
