#define analyse2_cxx
#include "analyse2.h"
#include <TH2.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <utility>
#include <TFile.h>
#include <TTree.h>
#include <TSystemDirectory.h>
#include <gsl/gsl_statistics.h>
using namespace std;

void analyse2::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L analyse2.C
//      Root > analyse2 t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();

   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;
      time_1 = time;
      ic1_1 = ic1;
      ic2_1 = ic2;
      mw1_focusx_1 = mw1_focusx;
      mw1_focusy_1 =  mw1_focusy;
      mw2_focusx_1 = mw2_focusx;
      mw2_focusy_1 = mw2_focusy;
      mw1_posx_1 = mw1_posx;
      mw1_posy_1 = mw1_posy;
      mw2_posx_1 = mw2_posx;
      mw2_posy_1=   mw2_posy;
     
      
      //      calculate mean and integral
      beamSignal_1 = 0.;
      /*
      for (int ch = 0; ch < 64; ch++){
	beamSignal_1 +=  channels[ch] - baseline[ch];
	beamPosX_1 +=  (channels[ch] - baseline[ch]) * double(ch);
	
      }
      beamPosX_1/= beamSignal_1;

      //      calculate FWHM from RMS
      beamFocusX_1 = 0.;
      for (int ch = 0; ch < 64; ch++){
	beamFocusX_1 +=  (channels[ch] - baseline[ch]) * (ch-beamPosX_1)* (ch-beamPosX_1);
      }
      beamFocusX_1 /= beamSignal_1;
      beamFocusX_1 = sqrt(beamFocusX_1); //correct this Variance = sigma*sigma / b
      */
      for (int ch = 0; ch < 64; ch++){
	channels[ch]-=baseline[ch]; //subtract the baseline
	beamSignal_1 +=  channels[ch]; //integrate the signal
      }
      beamPosX_1 = gsl_stats_wmean(channels,1,channellist,1,64); //calculate the weighted mean
      beamFocusX_1 = 2.355* gsl_stats_wsd(channels,1,channellist,1,64); //FWHM
      beamSkewX_1 = gsl_stats_wskew(channels,1,channellist,1,64); //skewness (symmetry)
      beamKurtX_1 = gsl_stats_wkurtosis(channels,1,channellist,1,64); //excess kurtosis (well behaved tails)
      th2f_mw1_beamPosX->Fill(mw1_posx_1,beamPosX_1);

      newdata->Fill();

   }
   th2f_mw1_beamPosX->Write();
   newdata->Write();
}


int main(int argc, char **argv)
{
  // Working directories
  const char *dirname = "/work/leverington/beamprofilemonitor/hitdata/HIT_26-11-2016/with_timestamp/";
  const char *pin_dirname = "/work/leverington/beamprofilemonitor/hitdata/HIT_26-11-2016/with_timestamp/pin/";
  const char *ext = ".root";
  TSystemDirectory pin_dir(pin_dirname, pin_dirname);

  if (true)
  {
    TSystemFile* file;
    TString fname = argv[1];
    

    
    // fname = file->GetName();

      // execute single PiN_run***.root
      if ( fname.EndsWith(ext) && !fname.BeginsWith("SAVE") && fname.BeginsWith("PiN_run"))
      {
        analyse2 *mon = new analyse2();
        printf("File name: %s \n", fname.Data());

        // Main part
        // Initialize(DIRName, FileName, baselineEvents, prelimEvents, beamLevel, firstFibermat, readOutFrequency in Hz, integrationTime in us)
        mon->Initialize(dirname, fname.Data(), 5000, 10000, 1., true, 3000., 312.);
	mon->Baseline(false,1000);
	mon->Loop(); //analysis loop

	//	cout << th2f_mw1_beamPosX->GetCorrelationFactor() << endl;
	mon->Save();//save output tree file
	//	mon->Close();//close output tree file

        delete mon;
      
      }
  
  }
  return 0;
}
