#include <string.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <utility>

#include <TFile.h>
#include <TTree.h>
#include <TSystemDirectory.h>
#include <string.h>
#include <TFile.h>
#include <TTree.h>
#include <TH1.h>
#include <TH2.h>
#include <TNtuple.h>
#include <iostream>
#include <fstream>
#include <TRandom.h>
#include <TROOT.h>
#include <algorithm> 
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TProfile.h>
#include <TVectorD.h>


#include <cstdlib>
#include <cmath>
#include <vector>

#include <TApplication.h>



using namespace std;


int main(int argc, char **argv)
{

  // Working directories
  const char *dirname = "/work/leverington/beamprofilemonitor/hitdata/HIT_26-11-2016/with_timestamp/";
  const char *listfile = "intensitylist_carbon.prn";
   ifstream in;
   ofstream ic1energyfile,ic2energyfile, beamenergyfile,beamenergyfile_iccorr, noisefile, focusfile,focusHITfile,  skewfile, kurtfile,focusFitfile,chi2Fitfile;

   TFile *f;
   TTree *tree;
   Int_t nfiles = 0;
   Int_t EList = 0;
   Double_t Energy = 0.;
   Double_t F1 = 0.;
   Double_t Intensity = 0.;
   Double_t SP = 0.;
   char Filename[50];
   Int_t id = 0;
   Double_t signalmean = 0.;
   Double_t signalmeanerror = 0.;
   Double_t signalmean_corr = 0.;
   Double_t signalmeanerror_corr = 0.;
   Double_t signalmean_offsetcorr = 0.;
   Double_t signalmeanerror_offsetcorr = 0.;
   
   Double_t ic1mean = 0.;
   Double_t ic1meanerror = 0.;
   Double_t ic2mean = 0.;
   Double_t ic2meanerror = 0.;

   Double_t sp_air = 0.;
   Double_t sp_ps = 0.;
   Double_t sp2_air = 0.;
   Double_t sp2_ps = 0.;

   Double_t ic_beam_ratio = 0.;
   Double_t ic_beam_ratioerror = 0.;

   Double_t totalcurrent = 0.;
   Double_t totaltime = 0.;
   Double_t intcorr = 0.;
   Double_t icbpmcorrelation = 0.;

   Double_t noisemean = 0.;
   Double_t noiseRMS = 0.;
   Double_t focusmean = 0.;
   Double_t focusRMS = 0.;
   Double_t skewmean = 0.;
   Double_t skewRMS = 0.;
   Double_t kurtmean = 0.;
   Double_t kurtRMS = 0.;
   Double_t focusFitmean = 0.;
   Double_t focusFitRMS = 0.;
   Double_t chi2Fitmean = 0.;
   Double_t chi2FitRMS = 0.;

   cout << "Trying to open"<< Form(": %s%s",dirname, listfile)<<"... " << endl;

   in.open(Form("%s%s",dirname, listfile));
   ic1energyfile.open("ic1energyfile_int_c.txt");
   ic2energyfile.open("ic2energyfile_int_c.txt");

   beamenergyfile.open("beamenergyfile_int_c.txt");
   beamenergyfile_iccorr.open("beamenergyfile_iccorr_int_c.txt");

   noisefile.open("noisefile_int_c.txt");
   focusfile.open("focusfile_int_c.txt");
   focusHITfile.open("focusHITfile_int_c.txt");
   skewfile.open("skewfile_int_c.txt");
   kurtfile.open("kurtfile_int_c.txt");
   focusFitfile.open("focusFitfile_int_c.txt");
   chi2Fitfile.open("chi2Fitfile_int_c.txt");


   TF1 * f_sp_air = new TF1("f_sp_air","[0]*pow(x,[1])+[2]", 50, 250); //stopping power of protons in Air [MeV cm2 /g]
   f_sp_air->SetParameters(303.746, -0.873697,1.01335); //protons between 50 and 300 MeV

   TF1 * f_sp_ps = new TF1("f_sp_ps","[0]*pow(x,[1])+[2]", 50, 250); //stopping power of protons in polystyrene [MeV cm2 /g]
   f_sp_ps->SetParameters(361.936, -0.892255, 1.19133);  //protons between 50 and 220 MeV

   TF1 * f_h2sp_air = new TF1("f_h2sp_air","[0]*pow(x,[1])+[2]", 50, 250); //stopping power of helium in air [MeV cm2 /g]
   f_h2sp_air->SetParameters(1236.51, -0.880225, 4.17041);  //helium between 50 and 300 MeV
   
   TF1 * f_h2sp_ps = new TF1("f_h2sp_ps","[0]*pow(x,[1])+[2]", 50, 250); //stopping power of helium in polystyrene [MeV cm2 /g]
   f_h2sp_ps->SetParameters(1387.08, -0.882686,4.60833);  //heelium between 50 and 300 MeV
   
   TF1 * f_c12sp_air = new TF1("f_c12sp_air","[0]*pow(x,[1])+[2]", 80, 480); //stopping power of carbon in air [MeV cm2 /g]
   f_c12sp_air->SetParameters(13291.2, -0.925464,45.3876);  //carbon between 80 and 480 MeV

   TF1 * f_c12sp_ps = new TF1("f_c12sp_ps","[0]*pow(x,[1])+[2]", 80, 480); //stopping power of carbon in polystyrene [MeV cm2 /g]
   f_c12sp_ps->SetParameters(14538.9, -0.922423,49.2859);  //carbon between 80 and 480 MeV

   TF1 * f_o16sp_air = new TF1("f_o16sp_air","[0]*pow(x,[1])+[2]", 80, 480); //stopping power of oxygen in air [MeV cm2 /g]
   f_o16sp_air->SetParameters(24624.9, -0.925425,80.6828);  //oxygen between 80 and 480 MeV

   TF1 * f_o16sp_ps = new TF1("f_o16sp_ps","[0]*pow(x,[1])+[2]", 80,480); //stopping power of oxygen in polystyrene [MeV cm2 /g]
   f_o16sp_ps->SetParameters(26465.6, -0.928309,88.6728);  //oxygen between 80 and 480 MeV

   /////       ic1/SP intensity correction factor = 19.8E6+/-0.1E6 particles/s per nA/(Mevcm2/g)

   if (!in) {
     cout << Form("%s%s",dirname, listfile) << " not found." << endl;
     return 0;}
   cout << Form("%s%s",dirname, listfile) << " opened." << endl;

   in >> EList >> Energy >> F1 >> Intensity >> SP >> Filename >> id;//prime the while loop
   while (!in.eof()) {
     TFile * file = TFile::Open(Form("%s%s",dirname,Filename));
     TFile * outfile = TFile::Open(Form("plots/%s_plots",Filename),"RECREATE");
     cout << Filename << endl;
     //     TH1D* signalDist = 0;
     //     file->GetObject("signalDist",signalDist);
     //     signalmean = signalDist->GetMean();
     //     signalmeanerror =  signalDist->GetMeanError();
     //  cout << signalmean << " " << signalmeanerror << endl;
     //     delete signalDist;

     //  TCanvas *c1 = new TCanvas("c1");
     TTree *data;
     file->GetObject("newdata", data);
     TH2D *h_beamSignal_channel = (TH2D*)file->Get("th2d_beamSignal_channel");
     TH2D *h_bkg_channel = (TH2D*)file->Get("th2d_bkg_channel");

     noisemean = h_bkg_channel->GetMean(2);
     noiseRMS = h_bkg_channel->GetRMS(2);

    
     TVectorD *v = (TVectorD*)file->Get("icinfo");
     //   v->Print();
     totalcurrent = (*v)[0];
     totaltime = (*v)[1];
     //  data->Print();
     TH1D* h_beamSignal_1 = new TH1D("h_beamSignal_1","h_beamSignal_1",510,-5000,50000);
     TH1D* h_ic1_1 = new TH1D("h_ic1_1","h_ic1_1",510,-5000,50000);
     TH1D* h_ic2_1 = new TH1D("h_ic2_1","h_ic2_1",510,-5000,50000);
     TH1D* h_ic1_corr = new TH1D("h_ic1_corr","h_ic1_corr",210,-0.04,8);
     TH1D* h_ic2_corr = new TH1D("h_ic2_corr","h_ic2_corr",210,-0.04,8);
     TH2D* h_beamSignal_v_ic_pscorr = new TH2D("h_beamSignal_v_ic_pscorr","h_beamSignal_v_ic_pscorr",400,-0.05,8.,400,-.05,3.0);
     TH1D* h_beamSignal_offsetcorr = new TH1D("h_beamSignal_offsetcorr","h_beamSignal_offsetcorr",210,-.05,8.);

     TH1D* h_beamSignal_corr = new TH1D("h_beamSignal_corr","h_beamSignal_corr",210,-.0500,8);
     TH1D* h_ic_beam_diff = new TH1D("h_ic_beam_diff","h_ic_beam_diff",400,-4,4);
     TH2D* h_beamSignal_v_ic_corr = new TH2D("h_beamSignal_v_ic_corr","h_beamSignal_v_ic_corr",210,-.05,8.,410,-3.0,3.0);
     TH2D* h_ic_v_ic_pscorr = new TH2D("h_ic_v_ic_pscorr","h_ic_v_ic_pscorr",400,-.05,8.,400,-0.05,8);
     TH2D* h_ic_v_ic_corr = new TH2D("h_ic_v_ic_corr","h_ic_v_ic_corr",210,-.05,8.,410,-3.0,3.0);
     TH1D* h_ic_beam_ratio = new TH1D("h_ic_beam_ratio","h_ic_beam_ratio",500,0,500.);
     TH2D* h_beamSignal_v_ic = new TH2D("h_beamSignal_v_ic","h_beamSignal_v_ic",510,-5000,50000,510,-5000,50000);

     TH1D* h_beamFocusX_1 = new TH1D("h_beamFocusX_1","h_beamFocusX_1",200,0,50.);
     TH1D* h_beamSkewX_1 = new TH1D("h_beamSkewX_1","h_beamSkewX_1",200,0,50.);
     TH1D* h_beamKurtX_1 = new TH1D("h_beamKurtX_1","h_beamKurtX_1",200,0,50.);
     TH1D* h_beamFocusX_fit = new TH1D("h_beamFocusX_fit","h_beamFocusX_fit",200,0,50.);
     TH1D* h_beamChi2_fit = new TH1D("h_beamChi2_fit","h_beamChi2_fit",200,0,50.);




    
       sp_air = f_c12sp_air->Eval(Energy)*(Intensity/1.0E6);
       sp_ps = f_c12sp_ps->Eval(Energy)*(Intensity/1.0E6);
       sp2_air = f_c12sp_air->Eval(Energy);
       sp2_ps = f_c12sp_ps->Eval(Energy);
    


          cout << sp_air << " " << sp_ps << " " << sp2_air << " " << sp2_ps << endl;
	  // data->Project("h_beamSignal_1","beamPeakX_fit","ic1_1>0.1&&beamChi2_fit<1000");
	  //  data->Project("h_beamSignal_1","beamSignal_1-beamSidebandNoise_1","ic1_1>0.1");
     data->Project("h_beamSignal_1", "beamPeakX_fit*sqrt(2)*beamFocusX_fit/2.3548" ,"beamon==1&&ic1_1>0.001&&beamChi2_fit<200&&beamPeakX_fit>20");

     data->Project("h_beamFocusX_1","beamFocusX_1","ic1_1>0.01");
     data->Project("h_beamSkewX_1","beamSkewX_1","ic1_1>0.01");
     data->Project("h_beamKurtX_1","beamKurtX_1","ic1_1>0.01");
     data->Project("h_beamFocusX_fit","beamFocusX_fit","ic1_1>0.01&&beamChi2_fit<1000");
     data->Project("h_beamChi2_fit","beamChi2_fit","ic1_1>0.01&&beamChi2_fit<1000");

     focusmean = h_beamFocusX_1->GetMean();
     focusRMS = h_beamFocusX_1->GetRMS();
     skewmean = h_beamSkewX_1->GetMean();
     skewRMS = h_beamSkewX_1->GetRMS();
     kurtmean = h_beamKurtX_1->GetMean();
     kurtRMS = h_beamKurtX_1->GetRMS();
     focusFitmean = h_beamFocusX_fit->GetMean();
     focusFitRMS = h_beamFocusX_fit->GetRMS();
     chi2Fitmean = h_beamChi2_fit->GetMean();
     chi2FitRMS = h_beamChi2_fit->GetRMS();


     data->Project("h_ic1_1","ic1_1","ic1_1>0.01");
     data->Project("h_ic2_1","ic2_1","ic2_1>0.01");

     data->Project("h_ic1_corr",Form("ic1_1/%f",sp_air),"ic1_1>0.01");
     data->Project("h_ic2_corr",Form("ic2_1/%f",sp_air),"ic2_1>0.01");

     
     data->Project("h_ic_v_ic_pscorr",Form("ic1_1/%f:ic2_1/%f", sp_air, sp_air),"ic1_1>0.01&&ic2_1>0.01");
     h_ic_v_ic_pscorr->FitSlicesY(0,0,-1,5);
     TF1 * f2 = new TF1("f2","pol1");
     f2->SetParameters(10, 1.0);
     TH1D* h_ic_v_ic_pscorr_1 = (TH1D*)gDirectory->Get("h_ic_v_ic_pscorr_1");
     Int_t fitsuccess2 = h_ic_v_ic_pscorr_1->Fit(f2,"R","",0.2,4.5);
     data->Project("h_ic_v_ic_corr",Form("((ic1_1/%f-%f)/%f - ic2_1/%f)/(ic2_1/%f):ic2_1/%f", sp_air,f2->GetParameter(0), f2->GetParameter(1), sp_air,sp_air,sp_air),"ic1_1>0.01&&ic2_1>0.01");
     h_ic_v_ic_corr->FitSlicesY(0,0,-1,5);

     data->Project("h_beamSignal_v_ic_pscorr",Form("beamSignal_1/%f:ic2_1/%f",sp_ps,sp_air),"ic2_1>0.01");
     data->Project("h_beamSignal_v_ic","beamSignal_1:ic1_1","ic2_1>0.01");
     icbpmcorrelation = h_beamSignal_v_ic->GetCorrelationFactor();
     h_beamSignal_v_ic_pscorr->FitSlicesY(0,0,-1,10);
     TH1D* h_beamSignal_v_ic_pscorr_1 = (TH1D*)gDirectory->Get("h_beamSignal_v_ic_pscorr_1");
     TF1 * f1 = new TF1("f1","pol1");
     f1->SetParameters(10, 1.0);
     Int_t fitsuccess = h_beamSignal_v_ic_pscorr_1->Fit(f1,"R","",0.2,4.5);
     //   cout << fitsuccess << " " << f1->GetParameter(0) << " " << f1->GetParameter(1) << endl;;
     data->Project("h_beamSignal_corr",Form("(beamSignal_1/%f-%f)/%f",sp_ps, f1->GetParameter(0), f1->GetParameter(1)),"ic2_1>0.01");
     data->Project("h_beamSignal_offsetcorr",Form("(beamSignal_1/%f-%f)",sp_ps, f1->GetParameter(0)),"ic2_1>0.01");

     data->Project("h_ic_beam_diff",Form("(beamSignal_1/%f-%f)/%f-(ic2_1/%f)", sp_ps,f1->GetParameter(0), f1->GetParameter(1),sp_air),"ic2_1>0.01"); 
     data->Project("h_beamSignal_v_ic_corr",Form("((beamSignal_1/%f-%f)/%f-(ic2_1)/%f)/(ic2_1/%f):(ic2_1)/%f", sp_ps,f1->GetParameter(0), f1->GetParameter(1),sp_air,sp_air,sp_air),"ic2_1>0.01");
     data->Project("h_ic_beam_ratio","(beamSignal_1/ic1_1)","ic1_1>0.01"); 
     
     
     h_beamSignal_v_ic_corr->FitSlicesY(0,0,-1,5);
     

     signalmean = h_beamSignal_1->GetMean();
     signalmeanerror =  h_beamSignal_1->GetMeanError();

     signalmean_corr = h_beamSignal_corr->GetMean();
     signalmeanerror_corr =  h_beamSignal_corr->GetMeanError();
     signalmean_offsetcorr = h_beamSignal_offsetcorr->GetMean();
     signalmeanerror_offsetcorr =  h_beamSignal_offsetcorr->GetMeanError();
     
     
     ic1mean = h_ic1_1->GetMean();
     ic1meanerror =  h_ic1_1->GetMeanError();
     ic2mean = h_ic2_1->GetMean();
     ic2meanerror =  h_ic2_1->GetMeanError();

     ic_beam_ratio=h_ic_beam_ratio->GetMean();
     ic_beam_ratioerror=h_ic_beam_ratio->GetRMS();
     intcorr = (Intensity /19.8E6) / (totalcurrent/sp2_air/totaltime);

     //cout << id << " " <<sp_air << " " << ic1mean/sp_air << " " << ic1meanerror/sp2_air << endl;
     // cout << id <<" " << Intensity/1.0E6*intcorr << " " <<signalmean/(Intensity/1.0E6)/(ic1mean/sp_air) << " " << signalmeanerror/(Intensity/1.0E6)/(ic1mean/sp_air) << endl;

     ic1energyfile << Intensity/1.0E6*intcorr << " " << ic1mean *intcorr << " " << ic1meanerror*intcorr<<  " " << Filename << endl;
     //  ic2energyfile << sp2_air << " " << ic2mean / (Intensity/1.0E6) / (0.659869 + 1.50842 * sp2_air) << " " << ic2meanerror/sp_air <<  " " << Filename << endl;

     beamenergyfile << Intensity/1.E6*intcorr << " " <<  signalmean*intcorr << " " << signalmeanerror*intcorr <<   endl;

     beamenergyfile_iccorr << Intensity/1.0E6*intcorr << " " <<ic_beam_ratio*sp2_air/sp2_ps/84.5 << " " << ic_beam_ratioerror*sp2_air/sp2_ps/84.5  <<   endl;


     cout << Intensity/1.0E6*intcorr << " " << totalcurrent << " " << totaltime/1000. << " " << totalcurrent / sp2_air << " " << totalcurrent/sp2_air/totaltime<<  " " << Intensity <<  " " << (ic1mean/0.312) / (totalcurrent/totaltime) << " " << intcorr << endl;
     ic2energyfile << Intensity/1.0E6*intcorr << " " << icbpmcorrelation << endl;
     noisefile << Intensity/1.0E6*intcorr << " " << noisemean << " " << noiseRMS << endl;
     focusfile << Intensity/1.0E6*intcorr << " " << focusmean*0.8 << " " << focusRMS*0.8 << endl;
     focusHITfile << Intensity/1.0E6*intcorr << " " << F1 <<  endl;
     skewfile << Intensity/1.0E6*intcorr << " " << skewmean << " " << skewRMS << endl;
     kurtfile << Intensity/1.0E6*intcorr << " " << kurtmean << " " << kurtRMS << endl;
     focusFitfile << Intensity/1.0E6*intcorr << " " << focusFitmean*0.8 << " " << focusFitRMS*0.8 << endl;
     chi2Fitfile << Intensity/1.0E6*intcorr << " " << chi2Fitmean << " " << chi2FitRMS << endl;




     //  h_beamSignal_1->Draw("");
     // c1->SaveAs(Form("figs/h_beamsignal_%i.pdf",nfiles));
     // c1->Destructor();
     file->Close();
     outfile->Write();
     outfile->Close();
     in >>  EList >> Energy >> F1 >> Intensity >> SP >> Filename >> id;
     //  cout <<  EList << Energy << F1 << Intensity << SP << Filename << id << endl;
    
     nfiles++;
     
   }
   ic1energyfile.close();
   ic2energyfile.close();

   beamenergyfile.close();
   beamenergyfile_iccorr.close();

   noisefile.close();
   focusfile.close();
   focusHITfile.close();
   skewfile.close();
   kurtfile.close();
   in.close();
   focusFitfile.close();
   chi2Fitfile.close();
  return 0;
}
