#include "TFile.h"
#include "TH1.h"
#include "TH2.h"
#include "TProfile.h"
#include "TRandom.h"
#include "TString.h"
#include "TTree.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <math.h>
#include <string>
#include <iostream>
#include <algorithm>
#include "TLegend.h"
#include "TPaveText.h"
#include "TText.h"
#include "TPad.h"
#include "TLegend.h

gStyle->SetOptStat(111111); 
gStyle->SetOptFit(1); 

using namespace std;

int efficiencies_plot(int stationiwant, TString filenameshort)
{
    // Number of lines per detector
    int nlines = 18;
    filename = "/home/user/re4data/TDC/HVSCAN/" + filenameshort + ".csv";
    cout << filename << endl;    
    // Setting plots range and style
    gStyle->SetOptStat(0.1);
    gStyle->SetMarkerSize(1);
    gStyle->SetMarkerStyle(20);
    gStyle->SetMarkerColor(1);
    int volt_bin = 200, volt_min = 8000, volt_max = 10000;
    int current_bin = 2000, current_min = 0, current_max = 5;
    int effi_bin = 500, effi_min = 0, effi_max = 100, maxbins = 100;
    float temperature, humidity, pressure;
    
    // Text positioning
    float label_font=0.025;
    float axis_offset=0.9;
    float label_size=0.03;
    
    
    // Defining variable already present in the dst file
    Float_t     Volt;
    Float_t     efficiency;
    Float_t     env_t;
    Float_t     env_rh;
    Float_t     env_p;
    Float_t     station;
    Float_t     curr1;
    Float_t     curr2;
    Float_t     curr3;
    Float_t     efficiency_err;
    Float_t     noise;
    Float_t     csize;
    Char_t      trigger_mode[20], eta[10], stat[10], vfat1[8], vfat2[8], vfat3[8], vfat4[8], vfat5[8], vfat6[8], vfat7[8], vfat8[8], vfat9[8], vfat10[8], vfat11[8], vfat12[8];
    
    float i = -1;
    int j = 0;
    char  str2[80], buffer[4], datetowrite[80], titletowrite[80], titletowrite2[80], infovalue1[256], infovalue2[256], infovalue3[256], infovalue4[256], infovalue5[256], infovalue6[256], infovalue31[256], infovalue32[256], infovalue33[256], infovalue34[256], infovalue35[256], infovalue36[256], infovalue37[256], infovalue38[256], infovalue39[256];
    string line, run, date, site, trigger, name, hv1, hv2, hv3, , effi;
    
    TFile *hfile = 0;
    hfile = TFile::Open("hvscan.root","RECREATE");
    
    TTree *rpclab = new TTree("rpclab","904 RPC Lab - PLOTS");
    rpclab->Branch("Volt",&Volt,"Volt/F");
    rpclab->Branch("efficiency",&efficiency,"efficiency/F");
    rpclab->Branch("env_t",&env_t,"env_t/F");
    rpclab->Branch("env_rh",&env_rh,"env_rh/F");
    rpclab->Branch("env_p",&env_p,"env_p/F");
    rpclab->Branch("station",&station,"station/F");
    rpclab->Branch("curr1",&curr1,"curr1/F");
    rpclab->Branch("curr2",&curr2,"curr2/F");
    rpclab->Branch("curr3",&curr3,"curr3/F");
    rpclab->Branch("trigger_mode",trigger_mode,"trigger_mode/C");
    
    ifstream myfile (filename);
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {            
            // Starting Counters
            i = i + 1;
            //cout << "reading line" << i << endl;
            //if ( fmod(i,nlines) == 0) {
            //    j = j + 1;
            //    //cout << "Chamber :" << j << endl;
            //}
            
            // Reading file content
            getline (myfile,line,',');
            run = line;
            
            getline (myfile,line,',');
            if (i==1) date = line;
            if (i==1) replace(date.begin(), date.end(), '/', '-');
            if (i==1) strcpy(datetowrite,date.c_str());
            
            getline (myfile,line,',');
            site = line;
            
            getline (myfile,line,',');
            if (i==1) env_t = ::atof(line.c_str());
            
            getline (myfile,line,',');
            if (i==1) env_p = ::atof(line.c_str());
            
            getline (myfile,line,',');
            if (i==1) env_rh = ::atof(line.c_str());
            
            getline (myfile,line,',');
            if (i==1) name = ::atof(line.c_str());
            if (i==1) strcpy(titletowrite2,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(eta,line.c_str());
            
            getline (myfile,line,',');
            strcpy(trigger_mode,line.c_str());
            
            getline (myfile,line,',');
            station = ::atof(line.c_str());
            
            getline (myfile,line,',');
            Volt = ::atof(line.c_str());
            
            getline (myfile,line,',');
            hv1 = line;
            
            getline (myfile,line,',');
            hv2 = line;
            
            getline (myfile,line,',');
            hv3 = line;
            
            getline (myfile,line,',');
            curr1 = ::atof(line.c_str());;
            
            getline (myfile,line,',');
            curr2 = ::atof(line.c_str());;
            
            getline (myfile,line,',');
            curr3 = ::atof(line.c_str());;
            
            getline (myfile,line,',');
            if (i==1) strcpy(stat,line.c_str());
            
            getline (myfile,line,',');
            efficiency = ::atof(line.c_str());
            
            getline (myfile,line,',');
            efficiency_err = ::atof(line.c_str());
            
            getline (myfile,line,',');
            csize = ::atof(line.c_str());
            
            getline (myfile,line,',');
            noise = ::atof(line.c_str());
            
            getline (myfile,line,',');
            getline (myfile,line,',');
            getline (myfile,line,',');
            getline (myfile,line,',');
            getline (myfile,line,',');
            getline (myfile,line,',');
            getline (myfile,line,',');
            getline (myfile,line,',');
            getline (myfile,line,',');
            getline (myfile,line,',');
            getline (myfile,line,',');
            
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat1,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat2,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat3,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat4,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat5,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat6,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat7,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat8,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat9,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat10,line.c_str());
            
            getline (myfile,line,',');
            if (i==1) strcpy(vfat11,line.c_str());
            
            getline (myfile,line,',');            
            if (i==1) strcpy(vfat12,line.c_str());

            // Taking the rest of the file
            getline (myfile,line,'\n');
            
            
            // Filling root file
            //if ( j == stationiwant) {
            rpclab->Fill();
            //cout << "station " << j << " filled(" << i << ")" << endl;
            //strcpy(titletowrite2,titletowrite);
            //}
            
            
        }
        rpclab->Write();
        myfile.close();
    }
    
    
    // Creating Canvas
    TCanvas *Frameperf = new TCanvas("Frameperf","Chamber performance",0,0,1500,900);
        TPad *pad1 = new TPad("pad1","",0,0,1,1); //1st pad for T
    TPad *pad2 = new TPad("pad2","",0,0,1,1); //2nd pad for P
    pad2->SetFillStyle(4000); //will be transparent
    pad1->Draw();
    pad1->cd();

    // Pre-drawing currents
    TH2F *environ3 = new TH2F("environ3","environ3",volt_bin,volt_min,volt_max,current_bin,current_min,current_max);
    environ3->SetMarkerColor(4);
    environ3->SetMarkerStyle(28);
    environ3->SetMarkerSize(0.8);
    rpclab->Draw("curr1:Volt>>environ3","trigger_mode==\"DOUBLE\"","");
    
    TH2F *environ4 = new TH2F("environ4","environ4",volt_bin,volt_min,volt_max,effi_bin,effi_min,effi_max);
    environ4->SetMarkerColor(4);
    environ4->SetMarkerStyle(29);
    environ4->SetMarkerSize(0.8);
    rpclab->Draw("curr2:Volt>>environ4","trigger_mode==\"DOUBLE\"","");
    
    TH2F *environ5 = new TH2F("environ5","environ5",volt_bin,volt_min,volt_max,effi_bin,effi_min,effi_max);
    environ5->SetMarkerColor(4);
    environ5->SetMarkerStyle(31);
    environ5->SetMarkerSize(0.8);
    rpclab->Draw("curr3:Volt>>environ5","trigger_mode==\"DOUBLE\"","");
    
    // PERFORMANCES
    //TPad *pad1 = new TPad("pad1","",0,0,1,1); //1st pad for T
    //TPad *pad2 = new TPad("pad2","",0,0,1,1); //2nd pad for P
    //pad2->SetFillStyle(4000); //will be transparent
    //pad1->Draw();
    //pad1->cd();
    
    TH2F *sens1 = new  TH2F("sens1","sens1",volt_bin,volt_min,volt_max,effi_bin,effi_min,effi_max);
    TH2F *sens2 = new  TH2F("sens2","sens2",volt_bin,volt_min,volt_max,effi_bin,effi_min,effi_max);
    TH2F *sens3 = new  TH2F("sens3","sens3",volt_bin,volt_min,volt_max,effi_bin,effi_min,effi_max);
    
    sens1->SetMarkerColor(1);
    sens1->SetMarkerStyle(20);
    sens1->SetMarkerSize(0.9);
    
    sens2->SetMarkerColor(2);
    sens2->SetMarkerStyle(21);
    sens2->SetMarkerSize(0.9);
    
    sens3->SetMarkerColor(3);
    sens3->SetMarkerStyle(22);
    sens3->SetMarkerSize(0.9);
    
    strcpy(titletowrite,"Chamber ");
    strcat(titletowrite,titletowrite2);
    sens1->SetTitle(titletowrite);
    sens1->GetXaxis()->SetTitleOffset(axis_offset);
    sens1->GetXaxis()->SetLabelSize(label_size);
    sens1->GetYaxis()->SetTitleSize(0.04);
    sens1->GetXaxis()->SetTitle("HV_{effective}");
    
    sens1->GetYaxis()->SetTitleOffset(axis_offset);
    sens1->GetYaxis()->SetLabelSize(label_size);
    sens1->GetYaxis()->SetTitleSize(0.04);
    sens1->GetYaxis()->SetTitle("Efficiency");
    gPad->SetGrid();
    
    rpclab->Draw("efficiency:Volt>>sens1","trigger_mode==\"TOP\"");
    rpclab->Draw("efficiency:Volt>>sens2","trigger_mode==\"BOTTOM\"");
    rpclab->Draw("efficiency:Volt>>sens3","trigger_mode==\"DOUBLE\"");
    
    TF1 *sigmoid = new TF1("sigmoid"," [0]/(1 + exp( [1] * ([2] - x) ) )");
    sigmoid->SetParNames("Efficiency","Slope","HV @ 50 efficiency");
    sigmoid->SetParameters(80.0, 0.01, 9200.0);
    sigmoid->SetLineColor(1);
    
    
    // Fitting efficiency1
    sens1->Fit("sigmoid","EM");
    TF1 *fit = sens1->GetFunction("sigmoid");
    Double_t chi21 = fit->GetChisquare();
    if (chi21>999) chi21=999;
    Double_t fit_efficiency1 = fit->GetParameter(0);
    Double_t fit_efficiency_err1 = fit->GetParError(0);
    
    Double_t slope1 = fit->GetParameter(1);
    Double_t slope_err1 = fit->GetParError(1);
    
    Double_t hvat501 = fit->GetParameter(2);
    Double_t hvat50_err1 = fit->GetParError(2);
    
    
    // Fitting efficiency2
    sigmoid->SetLineColor(2);
    sens2->Fit("sigmoid","EM");
    TF1 *fit = sens2->GetFunction("sigmoid");
    Double_t chi22 = fit->GetChisquare();
    if (chi22>999) chi22=999;
    Double_t fit_efficiency2 = fit->GetParameter(0);
    Double_t fit_efficiency_err2 = fit->GetParError(0);
    
    Double_t slope2 = fit->GetParameter(1);
    Double_t slope_err2 = fit->GetParError(1);
    
    Double_t hvat502 = fit->GetParameter(2);
    Double_t hvat50_err2 = fit->GetParError(2);
    
    
    
    // Fitting efficiency2
    sigmoid->SetLineColor(3);
    sens3->Fit("sigmoid","EM");
    TF1 *fit = sens3->GetFunction("sigmoid");
    Double_t chi23 = fit->GetChisquare();
    if (chi23>999) chi23=999;
    Double_t fit_efficiency3 = fit->GetParameter(0);
    Double_t fit_efficiency_err3 = fit->GetParError(0);
    
    Double_t slope3 = fit->GetParameter(1);
    Double_t slope_err3 = fit->GetParError(1);
    
    Double_t hvat503 = fit->GetParameter(2);
    Double_t hvat50_err3 = fit->GetParError(2);
    
    
    
    
    
    sens1->Draw("");    
    sens2->Draw("same");
    sens3->Draw("same");
    
    pad1->Update();
    pad1->Modified();
    Frameperf->cd();
    
    
    
    //compute the pad range with suitable margins
    Double_t ymin = current_min;
    Double_t ymax = current_max;
    Double_t dy = (ymax-ymin)/0.8; //% margins top and bottom
    Double_t xmin = volt_min;
    Double_t xmax = volt_max;
    Double_t dx = (xmax-xmin)/0.8; //% margins left and right
    pad2->Range(xmin-0.1*dx,ymin-0.1*dy,xmax+0.1*dx,ymax+0.1*dy);
    pad2->Draw();
    pad2->cd();
    
    environ3->Draw("][sames");
    environ4->Draw("][sames");
    environ5->Draw("][sames");
    pad2->Update();
    
    
    // draw axis on the right side of the pad
    TGaxis *axis = new TGaxis(xmax,ymin,xmax,ymax,ymin,ymax,50510,"+L");
    axis->SetLabelColor(4);
    axis->SetLineColor(4);
    axis->SetTitleOffset(axis_offset);
    axis->SetLabelSize(label_size);
    axis->SetLabelColor(4);
    axis->SetTitle("Current [uA]");
    axis->SetTitleSize(0.03);
    axis->SetTitleColor(4);
    axis->Draw();
    
    
    
    // Adding text to the plot
    
    TPaveText *pt2 = new TPaveText(0.11,0.45,0.35,0.9,"NDC");
    pt2->AddText("Runs info:");
    snprintf(infovalue1, sizeof(infovalue1), "Temp: %3.1f, RH: %2.0f %, P: %3.0f", env_t, env_rh, env_p );
    pt2->AddText(infovalue1);
    
    snprintf(infovalue2, sizeof(infovalue2), "Eta partition: %s", eta );
    pt2->AddText(infovalue2);
    
    snprintf(infovalue3, sizeof(infovalue3), "Stat.: %s,  #chi^{2}_{DOUBLE}=%6.1f,  #chi^{2}_{TOP}=%6.1f,  #chi^{2}_{BOTTOM}=%6.1f", stat,chi21,chi22,chi23 );
    pt2->AddText(infovalue3);
    
    snprintf(infovalue31, sizeof(infovalue31), "Efficiency_{DOUBLE}= %5.2f #pm %4.2f %%", fit_efficiency1,fit_efficiency_err1);
    snprintf(infovalue32, sizeof(infovalue32), "Slope_{DOUBLE}= %6.4f #pm %8.6f", slope1,slope_err1);
    snprintf(infovalue33, sizeof(infovalue33), "HV @ 50 Eff._{DOUBLE}= %4.0f #pm %4.1f V", hvat501,hvat50_err1);
    pt2->AddText(infovalue31);
    pt2->AddText(infovalue32);
    pt2->AddText(infovalue33);
    
    snprintf(infovalue34, sizeof(infovalue34), "Efficiency_{TOP}= %5.2f #pm %4.2f %%", fit_efficiency2,fit_efficiency_err2);
    snprintf(infovalue35, sizeof(infovalue35), "Slope_{TOP}= %6.4f #pm %8.6f", slope2,slope_err2);
    snprintf(infovalue36, sizeof(infovalue36), "HV @ 50 Eff._{TOP}= %4.0f #pm %4.1f V", hvat502,hvat50_err2);
    pt2->AddText(infovalue34);
    pt2->AddText(infovalue35);
    pt2->AddText(infovalue36);
    
    snprintf(infovalue37, sizeof(infovalue37), "Efficiency_{BOTTOM}= %5.2f #pm %4.2f %%", fit_efficiency3,fit_efficiency_err3);
    snprintf(infovalue38, sizeof(infovalue38), "Slope_{BOTTOM}= %6.4f #pm %8.6f", slope3,slope_err3);
    snprintf(infovalue39, sizeof(infovalue39), "HV @ 50 Eff._{BOTTOM}= %4.0f #pm %4.1f V", hvat503,hvat50_err3);
    pt2->AddText(infovalue37);
    pt2->AddText(infovalue38);
    pt2->AddText(infovalue39);
    
    
    snprintf(infovalue4, sizeof(infovalue4), "Thresholds A: %s %s %s %s",vfat1,vfat2,vfat3,vfat4);
    pt2->AddText(infovalue4);
    
    snprintf(infovalue5, sizeof(infovalue5), "Thresholds B: %s %s %s %s",vfat5,vfat6,vfat7,vfat8);
    pt2->AddText(infovalue5);
    
    snprintf(infovalue6, sizeof(infovalue6), "Thresholds C: %s %s %s %s",vfat9,vfat10,vfat11,vfat12);
    pt2->AddText(infovalue6);
    
    pt2->Draw("");
    
    
    
    // Adding the legend    
    leg = new TLegend(0.69,0.50,0.86,0.34);
    //leg->SetHeader("Legend");
    leg->AddEntry(sens1,"Efficiency (TOP)","lep");
    leg->AddEntry(sens2,"Efficiency (BOTTOM)","lep");
    leg->AddEntry(sens3,"Efficiency (DOUBLE)","lep");
    leg->AddEntry(environ3,"Current TN","lep");
    leg->AddEntry(environ4,"Current TW","lep");
    leg->AddEntry(environ5,"Current B","lep");
    leg->Draw();
    
    
    // Saving the image file
    TImage *img = TImage::Create();
    img->FromPad(Frameperf);

    //filename.Remove(filename.Index(".csv"));
    //filename=Remove(filename.Index("/home/user/re4data/TDC/HVSCAN/"));
    //replace(filename.begin(), date.end(), '.csv', '.png');
    //strcpy (str2,"/Users/tetto/Desktop/hvscan_");
    //strcat (str2,datetowrite);
    //strcat (str2,"_station");
    //sprintf(buffer, "%i", stationiwant);
    //strcat (str2,buffer);
    //strcpy (str2,filename.c_str());

    filenameshort = "/srv/www/htdocs/dqm2/plot/" + filenameshort + ".gif";
    //cout << filenameshort << endl;    
    img->WriteImage(filenameshort);    
}
