#include <TFile.h>
#include <TTree.h>
#include <stdio.h>
#include <vector>
#include <TSystemDirectory.h>
#include <TH2D.h>
#include <TH1D.h>
#include <TProfile.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TMath.h>
#include <vector>
#include <utility>
#include <TString.h>
#include <TDirectory.h>
#include <TString.h>
#include <TVectorD.h>
#include <TGraph.h>
#include <TGraphErrors.h>
#include <cmath>
#include <TPaveStats.h>
#include <TText.h>
#include <TROOT.h>
#include <TStyle.h>
#include <TObjArray.h>

using namespace std;

TFile *fileIn;
TFile *fileOut;
TTree *data;
int spill_profile_number = 0;
double readOutFrequency = 3000;
double maxSignal;
double minSignal;
double minPosX;
double maxPosX;
double c3 = 0.8;

void CompareWidth(const char *dirname, const char *filename);
void SavePDF(const char *dirname, const char *filename);
double CalFWHM(TH1D *hist);
Double_t fitfunc(Double_t *x, Double_t *par);

void process()
{
  const char *dirname = "/mnt/g/HIT/time_aligned/20161126/";
  const char *pin_dirname = "/mnt/g/HIT/time_aligned/20161126/pin/";
  const char *ext = ".root";

  TSystemDirectory dir(dirname, dirname);
  TSystemDirectory pin_dir(pin_dirname, pin_dirname);

  TList *files = dir.GetListOfFiles();
  if (files)
  {
    TSystemFile *file;
    TString fname;
    TIter next(files);

    while ((file = (TSystemFile *)next()))
    {
      fname = file->GetName();
      if (!file->IsDirectory() && fname.EndsWith(ext) && (fname.BeginsWith("SAVE_PiN_run")))
      {
        CompareWidth(dirname, fname.Data());
        SavePDF(dirname, fname.Data());
      }
    }
  }
}

void CompareWidth(const char *dirname, const char *filename)
{

  TString fn = TString(filename);
  TString dn = TString(dirname);
  TString inName = dn + fn;
  TString outName = dn + "Output/New_" + fn;
  fileIn = new TFile(inName, "read");
  fileOut = new TFile(outName, "recreate");
  fileIn->GetObject("newdata", data);

  TH2D *sigIcScatterPlot14, *mwPosScatterPlot13;
  TH1D *signalDist, *icSignal, *icSignal2;
  TH2D *deltaPos_time[10];
  fileIn->GetObject("sigIcScatterPlot11", sigIcScatterPlot14);
  fileIn->GetObject("mwPosScatterPlot11", mwPosScatterPlot13);
  fileIn->GetObject("signalDist", signalDist);
  fileIn->GetObject("icSignal", icSignal);
  //fileIn->GetObject("icSignal2", icSignal2);
  TH1D *icFitSlicesX = (TH1D *)sigIcScatterPlot14->ProfileX();
  TH1D *pos_mw = mwPosScatterPlot13->ProfileY();
  TH1D *pos_mw_x = mwPosScatterPlot13->ProfileX();
  TH1D *beamPosX = (TH1D *)fileIn->Get("beamPosX");
  TH1D *mwPosX = (TH1D *)fileIn->Get("mwPosX");
  TH1D *beamFocusX = (TH1D *)fileIn->Get("beamFocusX");
  TH1D *sigHist = (TH1D *)fileIn->Get("sigHist");
  TH1D *ic1Hist = (TH1D *)fileIn->Get("ic1Hist");
  TH1D *ic2Hist = (TH1D *)fileIn->Get("ic2Hist");
  TCanvas *SignalComp;
  Double_t norm_sig = sigHist->Integral();
  Double_t norm_ic1 = ic1Hist->Integral();
  Double_t norm_ic2 = ic2Hist->Integral();

  double mean = beamPosX->GetMean();
  double mean_mw = mwPosX->GetMean();
  double sigma = beamPosX->GetStdDev();
  double sigma_min = beamFocusX->GetMinimum();
  double sigma_max = beamFocusX->GetMaximum();
  minPosX = mean - 3 * sigma;
  maxPosX = mean + 3 * sigma;
  icFitSlicesX->Fit("pol1");

  pos_mw->Fit("pol1", "", "", mean - 3 * sigma, mean + 3 * sigma);
  maxSignal = icFitSlicesX->GetMaximum();
  minSignal = icFitSlicesX->GetMinimum();
  double posX, FocusX, beamSignal, ic1, ic2, mw1_posx, mw1_focusx, beamOn, mw2_posx, mw2_focusx;

  TBranch *b_ic1 = data->GetBranch("ic1_1");
  b_ic1->SetAddress(&ic1);
  TBranch *b_ic2 = data->GetBranch("ic2_1");
  b_ic2->SetAddress(&ic2);
  TBranch *b_mw1_focusx = data->GetBranch("mw1_focusx_1");
  b_mw1_focusx->SetAddress(&mw1_focusx);
  TBranch *b_mw1_posx = data->GetBranch("mw1_posx_1");
  b_mw1_posx->SetAddress(&mw1_posx);
  TBranch *b_mw2_focusx = data->GetBranch("mw2_focusx_1");
  b_mw2_focusx->SetAddress(&mw2_focusx);
  TBranch *b_mw2_posx = data->GetBranch("mw2_posx_1");
  b_mw2_posx->SetAddress(&mw2_posx);
  TBranch *b_beamPosX = data->GetBranch("beamPosX_1");
  b_beamPosX->SetAddress(&posX);
  TBranch *b_beamFocusX = data->GetBranch("beamFocusX_1");
  b_beamFocusX->SetAddress(&FocusX);
  TBranch *b_beamSignal = data->GetBranch("beamSignal_1");
  b_beamSignal->SetAddress(&beamSignal);
  TBranch *b_beamOn = data->GetBranch("beamOn");
  b_beamOn->SetAddress(&beamOn);

  data->Draw("mw1_posx_1>>his");
  data->Draw("mw2_posx_1>>his2");
  TH1F *his = (TH1F *)gDirectory->Get("his");
  TH1F *his2 = (TH1F *)gDirectory->Get("his2");
  double shift_MWPC = his->GetMean() - his2->GetMean();

  vector<int> spillTimes;

  int nevents = data->GetEntries();
  int countspillsize = 1;
  spillTimes.push_back(0);
  for (int i = 0; i < nevents; i++)
  {
    data->GetEntry(i);
    if (beamOn == 0)
    {
      if ((i - spillTimes[countspillsize - 1]) < 10)
      {
        continue;
      }
      spillTimes.push_back(i);
      countspillsize++;
    }
  }

  int nspills = spillTimes.size() - 1;
  printf("N_Spills: %d\n", nspills);

  TH2D *timeCenters = new TH2D("timeCenters", "", nevents / 100, 0., nevents / readOutFrequency, 100, mean - 6. * sigma, mean + 6 * sigma);
  TH2D *timeWidths = new TH2D("timeWidths", "", nevents / 100, 0., nevents / readOutFrequency, 100, 0., 25);
  TH1D *signalResCompare = new TH1D("signalCompare_new", "", 100, -0.5, 0.5);
  TH1D *ICResCompare = new TH1D("ICCompare_new", "", 100, -0.2, 0.2);
  TH1D *posCompare = new TH1D("posCompare_new", "", 100, -1, 1);
  for (int j = 0; j < nspills; j++)
  {
    TString name;
    name.Form("deltaPos_time%d", j);
    printf("spilltime_start: %d\n", spillTimes[j]);
    printf("spilltime_end: %d\n", spillTimes[j + 1]);
    deltaPos_time[j] = new TH2D(name.Data(), name.Data(), 1000, (double)spillTimes[j] / readOutFrequency, (double)spillTimes[j + 1] / readOutFrequency, 100, -0.4, 0.4);
  }
  TH2D *deltaPos_time_MWPC = new TH2D("deltaPos_time_MWPC", "deltaPos_time_MWPC", 1000, (double)spillTimes[spill_profile_number] / readOutFrequency, (double)spillTimes[spill_profile_number + 1] / readOutFrequency, 100, -0.4, 0.4);
  TH2D *deltaSig_time = new TH2D("deltaSig_time", "", nevents / 100, 0., nevents / readOutFrequency, 100, -0.5, 0.5);
  TH2D *deltaSig2_time = new TH2D("deltaSig2_time", "", nevents / 100, 0., nevents / readOutFrequency, 100, -0.5, 0.5);
  TH2D *ic1_ic2_time = new TH2D("ic1_ic2_time", "", nevents / 100, 0., nevents / readOutFrequency, 100, -0.5, 0.5);
  TH2D *deltaSig_Sig = new TH2D("deltaSig_Sig", "", 100, minSignal - 25, maxSignal + 25, 100, -1, 1);
  TH2D *deltaIC_IC = new TH2D("deltaIC_IC", "", 100, minSignal - 25, maxSignal + 25, 100, -1, 1);
  TH2D *Sig_time = new TH2D("Sig_time", "", nevents / 100, 0., nevents / readOutFrequency, 100, 0, maxSignal);
  TH2D *ic1_time = new TH2D("ic1_time", "", nevents / 100, 0., nevents / readOutFrequency, 100, 0, maxSignal);
  TH2D *ic2_time = new TH2D("ic2_time", "", nevents / 100, 0., nevents / readOutFrequency, 100, 0, maxSignal);
  TH2D *Fibre_posx_Signal = new TH2D("Center_Signal", "", 100, minSignal - 25, maxSignal + 25, 100, (mean - 6. * sigma), (mean + 6. * sigma));
  TH1D *SignalFiberScaled = new TH1D("SignalFiberScaled", "", 100, 0, maxSignal + 25);

  for (int j = 0; j < nspills; j++)
  {
    printf("spilltime_start: %d\n", spillTimes[j]);
    printf("spilltime_end: %d\n", spillTimes[j + 1]);
    for (int i = spillTimes[j]; i < spillTimes[j + 1]; i++)
    {
      data->GetEntry(i);
      /*if (beamOn == 0)
      {
        // deltaPos_time->Write();
        // deltaSig_time->Write();
        //spillTimes.push_back(i);
        continue;
      }*/
      timeCenters->Fill(i / readOutFrequency, posX);
      timeWidths->Fill(i / readOutFrequency, FocusX);
      posCompare->Fill(posX - mean - 1.25 * (mw1_posx - mean_mw));
      deltaPos_time_MWPC->Fill(i / readOutFrequency, mw1_posx - mw2_posx - shift_MWPC);

      signalResCompare->Fill((beamSignal - ic1 * norm_sig / norm_ic1) * 2 / (beamSignal + ic1 * norm_sig / norm_ic1));
      ICResCompare->Fill((ic2 - ic1 * norm_ic2 / norm_ic1) * 2 / (ic2 + ic1));
      deltaSig_time->Fill(i / readOutFrequency, (beamSignal - ic1 * norm_sig / norm_ic1) / beamSignal);
      deltaSig2_time->Fill(i / readOutFrequency, (beamSignal - ic1 * norm_sig / norm_ic1) / beamSignal);
      ic1_ic2_time->Fill(i / readOutFrequency, (ic2 - ic1 * norm_ic2 / norm_ic1) / ic1);
      deltaPos_time[j]->Fill(i / readOutFrequency, posX - mean - 1.25 * (mw1_posx - mean_mw));
      deltaSig_Sig->Fill(beamSignal, (beamSignal - ic1 * norm_sig / norm_ic1) / beamSignal);
      deltaIC_IC->Fill(ic1, (ic2 - ic1 * norm_ic2 / norm_ic1) * 2 / (ic2 + ic1));
      Sig_time->Fill(i / readOutFrequency, beamSignal);
      ic1_time->Fill(i / readOutFrequency, ic1);
      SignalFiberScaled->Fill(beamSignal);
      Fibre_posx_Signal->Fill(beamSignal, posX);
    }
  }

  fileIn->Close();
  fileOut->cd();

  signalResCompare->Fit("gaus");
  TObjArray aSlices, bSlices;

  timeCenters->Write();
  timeWidths->Write();
  icFitSlicesX->Write();
  pos_mw->Write();
  posCompare->Write();
  deltaPos_time_MWPC->Write();
  TH1D *tmp = deltaPos_time_MWPC->ProjectionY();
  tmp->SetStats(1111);
  
  tmp->Fit("gaus");
  tmp->Write();
  signalResCompare->Write();
  ICResCompare->Write();
  for (int j = 0; j < nspills; j++)
  {
    deltaPos_time[j]->Write();
  }
  deltaSig_time->Write();
  deltaSig_time->FitSlicesY(0, 0, -1, 5, "QNR", &aSlices);
  for (int i = 0; i < 4; i++)
  {
    aSlices[i]->Write();
  }
  deltaSig2_time->Write();
  ic1_ic2_time->Write();
  deltaSig_Sig->Write();
  deltaIC_IC->Write();
  deltaSig_Sig->FitSlicesY(0, 0, -1, 5, "QNR", &aSlices);
  for (int i = 0; i < 4; i++)
  {
    aSlices[i]->Write();
  }
  deltaIC_IC->FitSlicesY(0, 0, -1, 5, "QNR", &aSlices);
  for (int i = 0; i < 4; i++)
  {
    aSlices[i]->Write();
  }
  Sig_time->Write();
  ic1_time->Write();
  //Fibre_posx_Signal->Fit("pol1");
  Fibre_posx_Signal->Write();
  SignalFiberScaled->Write();

  //fileOut->Write();
  fileOut->Save();
}

void SavePDF(const char *dirname, const char *filename)
{
  //Set PDF line width = minimum
  gStyle->SetLineScalePS(1);
  gStyle->SetOptFit(kTRUE);

  TString fn = TString(filename);
  TString dn = TString(dirname);
  TString inName = dn + fn;
  TString outName = dn + "Output/New_" + fn;
  TString outPDF = outName;
  outPDF.Replace(outPDF.Length() - 4, 4, TString("pdf"));
  fileIn = new TFile(inName, "read");
  fileOut = new TFile(outName, "read");
  TString str;
  TF1 *func = new TF1("doublegaus", fitfunc, 0, 64, 6);
  double mean;
  double sigma;
  double constant;

  //Define Canvas:
  TCanvas *canvas1_1 = new TCanvas("canvas1", "", 1024, 768);
  TCanvas *canvas2_1 = new TCanvas("canvas2", "", 1280, 500);
  canvas2_1->Divide(2, 1);
  TCanvas *canvas3_1 = new TCanvas("canvas3", "", 1366, 500);
  canvas3_1->Divide(3, 1);
  TCanvas *canvas2_2 = new TCanvas("canvas4", "", 1366, 1024);
  canvas2_2->Divide(2, 2);

  //Get Histos
  TH2D *timeCenters = (TH2D *)fileIn->Get("timeCenters");
  TH2D *timeCenters_MWPC = (TH2D *)fileIn->Get("timeCenters_MWPC");
  TH2D *timeWidths = (TH2D *)fileIn->Get("timeWidths");
  TH2D *timeWidths_MWPC = (TH2D *)fileIn->Get("timeWidths_MWPC");

  TH2D *Center_Signal = (TH2D *)fileOut->Get("Center_Signal");
  TH1D *Center_Signal_pfc = Center_Signal->ProfileX();

  TString name;
  name.Form("deltaPos_time%d", spill_profile_number);
  TH2D *Diff_time = (TH2D *)fileOut->Get(name.Data()); //(TH2D *)fileIn->Get("Diff_time");
  TH1D *posCompare = Diff_time->ProjectionY();         //(TH1D *)fileOut->Get("posCompare_new");
  TH2D *Diff_time_MWPC = (TH2D *)fileOut->Get("deltaPos_time_MWPC");
  TH1D *posCompare_MWPC = Diff_time_MWPC->ProjectionY();

  TH1D *comppos_weighted = (TH1D *)fileIn->Get("comppos_weighted");
  TH1D *compsig_weighted = (TH1D *)fileIn->Get("compsig_weighted");

  TH1D *signalResCompare = (TH1D *)fileOut->Get("signalCompare_new");
  TH2D *signalRes_Sig = (TH2D *)fileOut->Get("deltaSig_Sig");
  TH1D *signalRes_Sig_1 = (TH1D *)fileOut->Get("deltaSig_Sig_1");
  TH1D *signalRes_Sig_2 = (TH1D *)fileOut->Get("deltaSig_Sig_2");

  TH1D *ICResCompare = (TH1D *)fileOut->Get("ICCompare_new");
  TH2D *deltaIC_IC = (TH2D *)fileOut->Get("deltaIC_IC");
  TH1D *deltaIC_IC_1 = (TH1D *)fileOut->Get("deltaIC_IC_1");
  TH1D *deltaIC_IC_2 = (TH1D *)fileOut->Get("deltaIC_IC_2");
  //TH2D *

  TH2D *deltaSig_time = (TH2D *)fileOut->Get("deltaSig_time");
  TH1D *deltaSig_time_fs2 = (TH1D *)fileOut->Get("deltaSig_time_2");
  TH2D *deltaPos_time = (TH2D *)fileOut->Get(name.Data());
  TH2D *deltaSig2_time = (TH2D *)fileOut->Get("deltaSig2_time");
  TH2D *ic1_ic2_time = (TH2D *)fileOut->Get("ic1_ic2_time");
  TH2D *Sig_time = (TH2D *)fileOut->Get("Sig_time");
  TH2D *ic1_time = (TH2D *)fileOut->Get("ic1_time");

  TH2D *mwPosScatterPlot = (TH2D *)fileIn->Get("mwPosScatterPlot11");
  TH2D *sigIcScatterPlot = (TH2D *)fileIn->Get("sigIcScatterPlot11");
  TH1D *mwPosScatterPlot_pfx = mwPosScatterPlot->ProfileX();
  TH1D *sigIcScatterPlot_pfx = sigIcScatterPlot->ProfileX();

  //Draw in canvas
  //page1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
  canvas2_2->cd(1);
  timeCenters->Draw("colz");
  timeCenters->GetXaxis()->SetTitle("time [s]");
  timeCenters->GetYaxis()->SetTitle("Beam Position [mm]");
  timeCenters->SetTitle("Fiber position vs time");
  canvas2_2->cd(2);
  timeCenters_MWPC->Draw("colz");
  timeCenters_MWPC->GetXaxis()->SetTitle("time [s]");
  timeCenters_MWPC->GetYaxis()->SetTitle("Beam Position [mm]");
  timeCenters_MWPC->SetTitle("MWPC position vs time");
  canvas2_2->cd(3);
  timeWidths->Draw("colz");
  timeWidths->GetXaxis()->SetTitle("time [s]");
  timeWidths->GetYaxis()->SetTitle("Beam widths [mm]");
  timeWidths->SetTitle("Fiber widths vs time");
  canvas2_2->cd(4);
  timeWidths_MWPC->Draw("colz");
  timeWidths_MWPC->GetXaxis()->SetTitle("time [s]");
  timeWidths_MWPC->GetYaxis()->SetTitle("Beam widths [mm]");
  timeWidths_MWPC->SetTitle("MWPC Beam widths vs time");
  canvas2_2->Print(outPDF + "(", "Title: position vs Time");

  //page222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222
  canvas2_1->cd(1);
  Center_Signal->Draw("colz");
  Center_Signal->GetXaxis()->SetTitle("Signal [particles]");
  Center_Signal->GetYaxis()->SetTitle("Beam Position [mm]");
  Center_Signal->SetTitle("Fiber position vs signal");
  canvas2_1->cd(2);
  Center_Signal_pfc->Draw("E1");
  canvas2_1->Update();
  Center_Signal_pfc->SetTitle("Average Fiber position vs signal");
  Center_Signal_pfc->Fit("pol1");
  double slope_c = Center_Signal_pfc->GetFunction("pol1")->GetParameter(1);
  str.Form("Slope = %.9f", slope_c);
  TPaveStats *st0 = (TPaveStats *)Center_Signal_pfc->FindObject("stats");
  st0->SetName("mystats");
  st0->AddText(str.Data());
  Center_Signal_pfc->SetStats(0);
  canvas2_1->Modified();
  Center_Signal_pfc->GetXaxis()->SetTitle("Signal [particles]");
  Center_Signal_pfc->GetYaxis()->SetTitle("Average Beam Position [mm]");
  Center_Signal_pfc->SetAxisRange(minPosX + 0.05, maxPosX - 0.05, "Y");
  Center_Signal_pfc->SetAxisRange(0, 0.8 * maxSignal, "X");
  canvas2_1->Print(outPDF, "Title: Position vs Signal");

  //page333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
  canvas2_2->cd(1);
  Diff_time->SetTitle("X(fibre)-X(MWPC) vs time");
  Diff_time->Draw("colz");
  Diff_time->GetXaxis()->SetTitle("time [s]");
  Diff_time->GetYaxis()->SetTitle("posX(fiber)-posX(MWPC) / [mm]");
  canvas2_2->cd(2);
  posCompare->SetTitle("X(fibre)-X(MWPC) distribution");
  //fit gaus
  posCompare->Fit("gaus");
  mean = posCompare->GetFunction("gaus")->GetParameter(1);
  sigma = posCompare->GetFunction("gaus")->GetParameter(2);
  constant = posCompare->GetFunction("gaus")->GetParameter(0);
  //fit doublegaus
  func->SetNpx(1000);
  func->SetParameter(0, constant);
  func->SetParameter(1, mean);
  func->SetParameter(2, sigma);
  func->SetParameter(3, constant);
  func->SetParameter(4, sigma);
  func->SetParameter(5, 0.);
  posCompare->Fit("doublegaus");
  double val, x1, x2, pos = -1, fwhm;
  int bin1, bin2;
  bin1 = posCompare->FindFirstBinAbove(posCompare->GetMaximum() / 2);
  bin2 = posCompare->FindLastBinAbove(posCompare->GetMaximum() / 2);
  fwhm = (posCompare->GetBinCenter(bin2) + posCompare->GetBinCenter(bin2 + 1) - posCompare->GetBinCenter(bin1) - posCompare->GetBinCenter(bin1 - 1)) * 0.5;
  str.Form("fwhm = %.3f mm", fwhm);
  TText *t = new TText(300.5, 300.5, str.Data());
  //t->Draw("SAME");
  posCompare->Draw("E1");
  printf("FWHM: %f\n", fwhm);
  canvas2_2->Update();
  TPaveStats *st = (TPaveStats *)posCompare->FindObject("stats");
  st->SetName("mystats");
  TList *listOfLines = st->GetListOfLines();
  TLatex *myt = new TLatex(0, 0, str.Data());
  listOfLines->Add(myt);
  str.Form("c3 = %.3f ", c3);
  TLatex *latex_page3_2 = new TLatex();
  latex_page3_2->DrawLatex(-0.2, 40., str.Data());
  posCompare->SetStats(0);
  canvas2_2->Modified();
  posCompare->GetXaxis()->SetTitle("X(fiber)-X(MWPC)");
  posCompare->GetYaxis()->SetTitle("counts");
  canvas2_2->cd(3);
  Diff_time_MWPC->SetTitle("MWPC PosX1-PosX2");
  Diff_time_MWPC->Draw("colz");
  Diff_time_MWPC->GetXaxis()->SetTitle("time [s]");
  Diff_time_MWPC->GetYaxis()->SetTitle("X(MWPC1)-X(MWPC2) / [mm]");
  canvas2_2->cd(4);
  posCompare_MWPC->SetTitle("MWPC PosX1-PosX2");
  posCompare_MWPC->Draw("colz");
  posCompare_MWPC->GetXaxis()->SetTitle("X(MWPC1)-X(MWPC2) / [mm]");
  posCompare_MWPC->GetYaxis()->SetTitle("");

  posCompare_MWPC->Fit("gaus");
  mean = posCompare_MWPC->GetFunction("gaus")->GetParameter(1);
  sigma = posCompare_MWPC->GetFunction("gaus")->GetParameter(2);
  constant = posCompare_MWPC->GetFunction("gaus")->GetParameter(0);
  func->SetNpx(1000);
  func->SetParameter(0, constant);
  func->SetParameter(1, mean);
  func->SetParameter(2, sigma);
  func->SetParameter(3, constant / 10.);
  func->SetParameter(4, sigma * 4.);
  func->SetParameter(5, 0.);
  posCompare_MWPC->Fit("doublegaus");
  posCompare_MWPC->Draw("E1");
  bin1 = posCompare_MWPC->FindFirstBinAbove(posCompare_MWPC->GetMaximum() / 2);
  bin2 = posCompare_MWPC->FindLastBinAbove(posCompare_MWPC->GetMaximum() / 2);
  fwhm = (posCompare_MWPC->GetBinCenter(bin2) + posCompare_MWPC->GetBinCenter(bin2 + 1) - posCompare_MWPC->GetBinCenter(bin1) - posCompare_MWPC->GetBinCenter(bin1 - 1)) * 0.5;
  str.Form("fwhm = %.3f", fwhm);
  //t->Draw("SAME");
  posCompare_MWPC->Draw("E1");
  printf("FWHM: %f\n", fwhm);
  canvas2_2->Update();
  st = (TPaveStats *)posCompare_MWPC->FindObject("stats");
  st->SetName("mystats");
  listOfLines = st->GetListOfLines();
  myt = new TLatex(0, 0, str.Data());
  listOfLines->Add(myt);
  posCompare_MWPC->SetStats(0);
  canvas2_2->Modified();
  canvas2_2->Print(outPDF, "Title: Position compare");

  //page444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444
  canvas2_2->cd(1);
  signalRes_Sig->SetTitle("S(Fibre)-S(IC) vs S(Fibre)");
  signalRes_Sig->Draw("colz");
  canvas2_2->cd(2);
  signalResCompare->SetTitle("S(Fibre)-S(IC) distribution");
  signalResCompare->Fit("gaus");
  mean = signalResCompare->GetFunction("gaus")->GetParameter(1);
  sigma = signalResCompare->GetFunction("gaus")->GetParameter(2);
  constant = signalResCompare->GetFunction("gaus")->GetParameter(0);
  func->SetNpx(1000);
  func->SetParameter(0, constant);
  func->SetParameter(1, mean);
  func->SetParameter(2, sigma);
  func->SetParameter(3, constant / 10.);
  func->SetParameter(4, sigma * 4.);
  func->SetParameter(5, 0.);
  signalResCompare->Fit("doublegaus");
  signalResCompare->Draw("E1");
  bin1 = signalResCompare->FindFirstBinAbove(signalResCompare->GetMaximum() / 2);
  bin2 = signalResCompare->FindLastBinAbove(signalResCompare->GetMaximum() / 2);
  fwhm = (signalResCompare->GetBinCenter(bin2) + signalResCompare->GetBinCenter(bin2 + 1) - signalResCompare->GetBinCenter(bin1) - signalResCompare->GetBinCenter(bin1 - 1)) * 0.5;
  str.Form("fwhm = %.3f", fwhm);
  //t->Draw("SAME");
  signalResCompare->Draw("E1");
  printf("FWHM: %f\n", fwhm);
  canvas2_2->Update();
  st = (TPaveStats *)signalResCompare->FindObject("stats");
  st->SetName("mystats");
  listOfLines = st->GetListOfLines();
  TLatex *myt2 = new TLatex(0, 0, str.Data());
  listOfLines->Add(myt2);
  signalResCompare->SetStats(0);
  canvas2_2->Modified();
  signalResCompare->GetXaxis()->SetTitle("S(Fibre)-S(IC)/S");
  signalResCompare->GetYaxis()->SetTitle("counts");
  canvas2_2->cd(3);
  signalRes_Sig_1->SetTitle("S(Fibre)-S(IC) vs S(Fibre)");
  signalRes_Sig_1->Draw("E1");
  signalRes_Sig_1->GetXaxis()->SetTitle("E(fiber)");
  signalRes_Sig_1->GetYaxis()->SetTitle("(E(fiber)-E(MWPC))//E");
  signalRes_Sig_1->SetAxisRange(0, maxSignal * 0.7, "X");
  signalRes_Sig_1->SetAxisRange(-0.4, 0.4, "Y");
  canvas2_2->cd(4);
  signalRes_Sig_2->SetTitle("sigma(S(Fibre)-S(IC)) vs S(Fibre)");
  signalRes_Sig_2->Draw("E1");
  signalRes_Sig_2->GetXaxis()->SetTitle("E(fiber)");
  signalRes_Sig_2->GetYaxis()->SetTitle("sigma(E(fiber)-E(MWPC))//E");
  signalRes_Sig_2->SetAxisRange(0, maxSignal, "X");
  signalRes_Sig_2->SetAxisRange(0.01, 0.25, "Y");
  canvas2_2->Print(outPDF, "Title: IC Signal Resolution vs Signal");

  //page44545454545454545455454545454545454545454545445454545454545454545454545454555454545454545454545454545454
  canvas2_2->cd(1);
  deltaIC_IC->SetTitle("S(IC2)-S(IC2)/S vs S(IC1)");
  deltaIC_IC->Draw("colz");
  canvas2_2->cd(2);
  ICResCompare->SetTitle("S(IC2)-S(IC2)/S distribution");
  ICResCompare->Fit("gaus");
  mean = ICResCompare->GetFunction("gaus")->GetParameter(1);
  sigma = ICResCompare->GetFunction("gaus")->GetParameter(2);
  constant = ICResCompare->GetFunction("gaus")->GetParameter(0);
  func->SetNpx(1000);
  func->SetParameter(0, constant);
  func->SetParameter(1, mean);
  func->SetParameter(2, sigma);
  func->SetParameter(3, constant / 10.);
  func->SetParameter(4, sigma * 4.);
  func->SetParameter(5, 0.);
  ICResCompare->Fit("doublegaus");
  ICResCompare->Draw("E1");
  bin1 = ICResCompare->FindFirstBinAbove(ICResCompare->GetMaximum() / 2);
  bin2 = ICResCompare->FindLastBinAbove(ICResCompare->GetMaximum() / 2);
  fwhm = (ICResCompare->GetBinCenter(bin2) + ICResCompare->GetBinCenter(bin2 + 1) - ICResCompare->GetBinCenter(bin1) - ICResCompare->GetBinCenter(bin1 - 1)) * 0.5;
  str.Form("fwhm = %.3f", fwhm);
  //t->Draw("SAME");
  ICResCompare->Draw("E1");
  printf("FWHM: %f\n", fwhm);
  canvas2_2->Update();
  st = (TPaveStats *)ICResCompare->FindObject("stats");
  st->SetName("mystats");
  listOfLines = st->GetListOfLines();
  TLatex *myt3 = new TLatex(0, 0, str.Data());
  listOfLines->Add(myt3);
  ICResCompare->SetStats(0);
  canvas2_2->Modified();
  ICResCompare->GetXaxis()->SetTitle("S(IC2)-S(IC2)/S");
  ICResCompare->GetYaxis()->SetTitle("counts");
  canvas2_2->cd(3);
  deltaIC_IC_1->SetTitle("S(IC2)-S(IC2)/S vs S(IC1)");
  deltaIC_IC_1->Draw("E1");
  deltaIC_IC_1->GetXaxis()->SetTitle("S(IC)");
  deltaIC_IC_1->GetYaxis()->SetTitle("S(IC2)-S(IC2)/S");
  deltaIC_IC_1->SetAxisRange(0, maxSignal * 0.7, "X");
  deltaIC_IC_1->SetAxisRange(-0.4, 0.4, "Y");
  canvas2_2->cd(4);
  deltaIC_IC_2->SetTitle("sigma(S(IC2)-S(IC2)/S) vs S(IC)");
  deltaIC_IC_2->Draw("E1");
  deltaIC_IC_2->GetXaxis()->SetTitle("E(fiber)");
  deltaIC_IC_2->GetYaxis()->SetTitle("sigma(S(IC2)-S(IC2)/S)");
  deltaIC_IC_2->SetAxisRange(0, maxSignal, "X");
  deltaIC_IC_2->SetAxisRange(0.01, 0.25, "Y");
  canvas2_2->Print(outPDF, "Title: IC Signal Resolution vs Signal");

  //page555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555
  canvas2_2->cd(1);
  deltaSig_time->SetTitle("S(Fibre)-S(IC1) vs time");
  deltaSig_time->Draw("colz");
  deltaSig_time->GetXaxis()->SetTitle("time [s]");
  deltaSig_time->GetYaxis()->SetTitle("signal difference/signal %");
  canvas2_2->cd(2);
  deltaSig_time_fs2->SetTitle("Signal difference vs time_fitSlicesY_(sigma)");
  deltaSig_time_fs2->Draw("colz");
  deltaSig_time_fs2->GetXaxis()->SetTitle("time [s]");
  deltaSig_time_fs2->GetYaxis()->SetTitle("sigma(signal difference) [particles]");
  canvas2_2->cd(3);
  deltaSig2_time->SetTitle("S(Fibre)-S(IC2) vs time");
  deltaSig2_time->Draw("colz");
  deltaSig2_time->GetXaxis()->SetTitle("time [s]");
  deltaSig2_time->GetYaxis()->SetTitle("signal [particles]");
  canvas2_2->cd(4);
  ic1_ic2_time->SetTitle("S(ic1)-S(ic2) vs time");
  ic1_ic2_time->Draw("colz");
  ic1_ic2_time->GetXaxis()->SetTitle("time [s]");
  ic1_ic2_time->GetYaxis()->SetTitle("signal [particles]");
  canvas2_2->Print(outPDF, "Title: Beam position vs Time");

  //page 6666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666

  canvas2_1->cd(1);
  comppos_weighted->Draw();
  str.Form("fwhm = %.3f", CalFWHM(comppos_weighted));
  TLatex *latex = new TLatex();
  latex->DrawLatex(-0.2, 40., str.Data());
  canvas2_1->cd(2);
  compsig_weighted->Draw();
  str.Form("fwhm = %.3f", CalFWHM(compsig_weighted));
  TLatex *latex2 = new TLatex();
  latex2->DrawLatex(-0.2, 45., str.Data());
  canvas2_1->Print(outPDF, "Title: weighted resoultion");

  //page 777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777
  canvas2_2->cd(1);
  mwPosScatterPlot->SetTitle("Fibre position vs MWPC position");
  mwPosScatterPlot->Draw("colz");
  mwPosScatterPlot->GetXaxis()->SetTitle("MWPC position [mm]");
  mwPosScatterPlot->GetYaxis()->SetTitle("Fibre position [mm]");
  canvas2_2->cd(2);
  mwPosScatterPlot_pfx->SetTitle("mean MWPC position vs Fibre position");
  mwPosScatterPlot_pfx->Fit("pol1");
  mwPosScatterPlot_pfx->Draw("colz");
  mwPosScatterPlot_pfx->SetAxisRange(minPosX, maxPosX, "Y");
  mwPosScatterPlot_pfx->GetXaxis()->SetTitle("MWPC position [mm]");
  mwPosScatterPlot_pfx->GetYaxis()->SetTitle("Fibre position [mm]");
  canvas2_2->cd(3);
  sigIcScatterPlot->SetTitle("Fibre signal vs ic signal");
  sigIcScatterPlot->Draw("colz");
  sigIcScatterPlot->GetXaxis()->SetTitle("ic signal [n]");
  sigIcScatterPlot->GetYaxis()->SetTitle("Fibre signal [n]");
  canvas2_2->cd(4);
  sigIcScatterPlot_pfx->SetTitle("mean IC signal vs Fibre signal");
  sigIcScatterPlot_pfx->Fit("pol1");
  sigIcScatterPlot_pfx->Draw("colz");
  canvas2_2->Update();
  st = (TPaveStats *)sigIcScatterPlot_pfx->FindObject("stats");
  st->SetName("mystats");
  listOfLines = st->GetListOfLines();
  TText *tconst = st->GetLineWith("Mean x");
  TText *tconst1 = st->GetLineWith("Entries");
  TText *tconst2 = st->GetLineWith("Mean y");
  listOfLines->Remove(tconst);
  listOfLines->Remove(tconst1);
  listOfLines->Remove(tconst2);

  sigIcScatterPlot_pfx->GetXaxis()->SetTitle("ic signal [n]");
  sigIcScatterPlot_pfx->GetYaxis()->SetTitle("Fibre signal [n]");
  canvas2_2->Print(outPDF + ")", "Title: Alignment");
}

Double_t fitfunc(Double_t *x, Double_t *par)
{
  Double_t arg1 = 0;
  if (par[2] != 0)
    arg1 = (x[0] - par[1]) / par[2];
  Double_t fitval1 = par[0] * TMath::Exp(-0.5 * arg1 * arg1);
  Double_t arg2 = 0;
  if (par[4] != 0)
    arg2 = (x[0] - par[1]) / par[4];
  Double_t fitval2 = par[3] * TMath::Exp(-0.5 * arg2 * arg2);
  Double_t fitsum = par[5] + fitval1 + fitval2;
  return fitsum;
}

double CalFWHM(TH1D *hist)
{
  double val, x1, x2, pos = -1, fwhm;
  int bin1, bin2;
  bin1 = hist->FindFirstBinAbove(hist->GetMaximum() / 2);
  bin2 = hist->FindLastBinAbove(hist->GetMaximum() / 2);
  fwhm = (hist->GetBinCenter(bin2) + hist->GetBinCenter(bin2 + 1) - hist->GetBinCenter(bin1) - hist->GetBinCenter(bin1 - 1)) * 0.5;
  return fwhm;
}