#define rpc_offline_cxx
#include "rpc_offline.h"
#include <TH2.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <fstream>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include <string>
#include <cstdio>
#include "TPad.h"
#include "TLegend.h"
#include "TPaveText.h"
#include "TText.h"
#include <math.h>
#include <sys/stat.h>
#include "TGaxis.h"

using namespace std;
using std::cout;
using std::endl;
using std::vector;
using std::stringstream;

#define size 20

int main(int argc, char **argv) {
    
    int feb[13], station;
    char temp1[128], run_config_file[256];
    string rff_conf_line, rff_mat_line, rff_mat_line1, rff_mat_line2, rff_mat_line3, rff_mat_line4;
    string run_str_tmp, run_config;
    string variablestring1, variablestring2, variablestring3, variablestring4, chamber_tn, chamber_tw, chamber_b;
    
    bool verbose_openfile = 0;
    
    stringstream stst;
    ifstream in(argv[1]);
    strcpy(temp1,argv[1]);
    
    if (verbose_openfile) cout << " " << endl << " " << endl << "-----------------------------------------------------" << endl;
    if (verbose_openfile) cout << "Opening file: " << temp1 << endl;
    rpc_offline pa(temp1);
    stst << temp1;
    stst >> run_str_tmp;
    
    pa.StripProfile();
}

void rpc_offline::StripProfile() {
    
    
    // Defining variables
    char htitle[256];
    string conf_line, mat_line, titlestring, info, strip_prof_string = "", strip_prof_noise_string = "", clustersizedistr = "", timestamp;
    int max_station = 8, map_module, map_station, map_start, map_finish, trigger_bit = -99, trigger_biteta = 0, trg_module = 0, aModule, i_station, maxprocessable = 0;
    float timing;
    char stringaexec[ 100 ], temp[20];
    struct stat st1;
    struct stat st2;
    FILE *stream;
    int strip_start = 0, strip_finish = 128*max_station, maxbins = strip_finish, maxstationreal;
    int timemin = -70, timemax = 180; //19500 and 21000
    char *tdcmodules[12] = {"1","2","3","4","5","6","7","8","9","10","11","12"};
    maxstationreal=(strip_finish-64)/96;
    

    
    // Cosmetics settings
    int timebin = abs(timemax) + abs(timemin);
    int strip_bin = strip_finish - strip_start;
    int text_xmin = 55, text_xmax = 104, text_ymin = (maxbins - maxbins/3.8), text_ymax = maxbins;
    
    // Defining verboses
    bool verbose_trg = 1, verbose_map = 1, verbose_filling = 1, verbose_filling2 = 1, verbose_filling_detailed = 1, verbose_filling_eff_counts = 1;
    bool verbose_dump = 1, verbose_filling_eff_noise = 1;
    
    
    TH2F* h_Strip2d = new TH2F("2D hit distribution","DAQ SUMMARY", strip_bin, strip_start, strip_finish, timebin, timemin, timemax);
    if (fChain == 0) return;
    if( c1 ) delete c1;
    c1 = new TCanvas(3);
    Long64_t nentries = fChain->GetEntriesFast();
    if (maxprocessable > 0) nentries = maxprocessable;
    Long64_t nbytes = 0, nb = 0;
        
    // Reading the trigger bit
    ifstream conf_file("/home/user/workspace/rpcupgrade/Offline/offline.cfg");
    if (conf_file.is_open()){
        while(conf_file.good()){
            getline(conf_file, conf_line);
            mat_line = "trigger : ";
            if ( ((int)conf_line.find(mat_line))!=-1){
                conf_line.erase(0,mat_line.length());
                trigger_bit = atoi(conf_line.c_str());
            }
            conf_file.close();
        }
    }
    conf_file.close();
    
    if (verbose_trg) cout << " " << endl << " " << endl << "-----------------------------------------------------" << endl;
    if (verbose_trg) cout << "Master trigger bit :  " << trigger_bit << endl;
    if (verbose_trg) cout << "Trigger bit (eta partition):  " << trigger_biteta << endl;
    if (verbose_trg) cout << "-----------------------------------------------------" << endl << " " << endl << " " << endl;
    
    
    for ( unsigned aModule = 0; aModule < max_station; aModule++ ) {
        cout << " module = " << aModule << endl;
        
        for ( Long64_t jentry = 0; jentry < nentries; jentry++ ) {
            
            if ( jentry%50 == 0 ) {
                //if (verbose_filling) cout << " " << jentry << "/" << nentries << "\r" << flush;
            }
            
            Long64_t ientry = LoadTree(jentry);
            if (ientry < 0) break;
            nb = fChain->GetEntry(jentry);
            nbytes += nb;

            vector<unsigned int> * TRIG = _Data[ trg_module ][ trigger_bit ];
            vector<unsigned int> * HITS_PER_CHANNEL = HitsPerChannel[ trg_module ];

            if ( HITS_PER_CHANNEL->at( trigger_bit ) < 1) continue;            
           
            //if (verbose_filling) cout << " " << endl << "Event: " << jentry << "  " << endl << "TRG -> at(0) = " << TRIG->at( 0 ) << endl;
            //if (verbose_filling) cout << "HITS_PER_CHANNEL -> at(" << trigger_bit << ") = " << HITS_PER_CHANNEL->at( trigger_bit ) << endl << " " << endl;

            for ( unsigned aChannel = 1; aChannel < 128; aChannel++ ) {
                
                vector<unsigned int> * HITS_PER_CHANNELC = HitsPerChannel[ aModule ];
                vector<unsigned int> * CH = _Data[ aModule ][ aChannel ];
                
                // Printing informations
                //if (verbose_filling) cout << " " << endl << "***Event: " << jentry << "  " << "Module: " << Module << "   " << "Station: " << i_station << "   " << "Channel: " << aChannel << endl;
                //if (verbose_filling2) cout << "***Trigger: " << TRIG->at( 0 ) << endl;
                //if (verbose_filling2) cout << "***Hits per channel: " << HITS_PER_CHANNELC->at( aChannel ) << endl << " " << endl;
                
                if( HITS_PER_CHANNELC->at( aChannel ) > 0 ) {
                    long ch = CH->at( 0 );
                    long trig = TRIG->at( 0 );
                    //cout << "TDC0: "<< ch <<" TDC1: "<< trig << endl;            
                    aChannel = aChannel + aModule*128;
                    timing = (trig - ch)/10;
                    //if (aModule>0) h_Strip2d->Fill(aChannel,timing);
                    if ( (aModule==0) && (aChannel==31) ) h_Strip2d->Fill(aChannel,timing);
                    if ( aChannel>31 ) h_Strip2d->Fill(aChannel,timing);
                    //if (verbose_filling2) cout << "***Filling : " << aChannel << " timing: " << timing << " " << endl;
                }
            }
        }
    }
    
    cout << " process ended without problems! " << endl;

    // Drawing Canvase and frames
    //gStyle->SetOptStat(kFALSE);
    TCanvas *c2 = new TCanvas("c2","c2",1000,600);
    //TH2F *frame = new  TH2F("frame", "", strip_bin, strip_start, strip_finish, timebin, timemin, timemax);

    /*
    // Drawing frame
    frame->GetXaxis()->SetTitleOffset(1.1);
    frame->GetXaxis()->SetLabelSize(0.025);
    frame->GetXaxis()->SetTitle("TDC channels");
    
    TAxis *axis = frame->GetXaxis();
    axis->SetNdivisions(maxstationreal,16,1,kFALSE);
    axis->SetDecimals(kFALSE);
    
    frame->GetYaxis()->SetTitleOffset(1.1);
    frame->GetYaxis()->SetLabelSize(0.025);
    frame->GetYaxis()->SetTitle("TIME");
    frame->Draw();
*/
    
    // Drawing strip profiles
    h_Strip2d->GetXaxis()->SetTitle("TDC channels");
    h_Strip2d->GetYaxis()->SetTitle("TIMING (ns)");
    TAxis *axis = h_Strip2d->GetXaxis();
    axis->SetNdivisions(max_station,128,1,kFALSE);
    axis->SetDecimals(kFALSE);

    h_Strip2d->SetFillColor(2);
    h_Strip2d->SetMarkerStyle(6);
    h_Strip2d->Draw();

   //draw an axis on the right side
   TGaxis *axis2 = new TGaxis(32, timemin, strip_finish-32, timemin, 1, maxstationreal+1, maxstationreal+1,"-SM");
   axis2->SetLineColor(kRed);
   axis2->SetLabelColor(kRed);
   axis2->SetLabelOffset(-0.6);
   axis2->SetTickSize(-1);
   axis2->SetDecimals(kFALSE);
   axis2->Draw("same");

    // Saving plots on files
    c2->SaveAs("/srv/www/htdocs/dqm/plot/stripprofile2d.png");
}
