
#include <iostream>
#include <string>
#include <math.h> 
#include <sstream>
#include <TFile.h>
#include <TTree.h>
#include <vector>


//Compile with  g++ -std=c++11 testCpp.cc -o test; ./test
std::string convert_vector_to_string(std::vector<double> myVector){
    std::stringstream ss;
    copy(myVector.begin(), myVector.end(), std::ostream_iterator<double>(ss, " "));
    std::string s = ss.str();
    return s.substr(0, s.length()-1); // get rid of the trailing space
}


int try_getObservable(std::string observable, TFile* file){
    if (!file->GetListOfKeys()->Contains(observable.c_str())){
        //Also check if Fl<->S1s and A_FB<->S6s is available
        if (observable == "Fl")  return 10+try_getObservable("S1s",file);
        if (observable == "S1s") return 20+try_getObservable("Fl",file);
        if (observable == "Afb") return 30+try_getObservable("S6s",file);
        if (observable == "S6s") return 40+try_getObservable("Afb",file);
        return 0;
    }
    else return 1;
}

std::vector<double> load_param_values_into_vector(std::string paramName, std::string fileName){
    //There is a function for this in bu2kstarmumu_parameters.cc, but that is inherited from parameters, therefore a parameter class needs to be created for this
    //That would be tedious, so there is a new class that opens the root file with results and reads it from a tree directly into an array

    //Create the vector that will be returned
    std::vector<double> output;

    //Open file
    std::cout << "Opening " << fileName <<std::endl;
    TFile* file = new TFile(fileName.c_str(), "READ");

    int isFoundFlag = try_getObservable(paramName, file);

    std::cout << isFoundFlag << std::endl;
    
        //Get the tree
    TTree* tree = (TTree*)file->Get(paramName.c_str());
    //Activate only needed branches
    tree->SetBranchStatus("*",0);
    tree->SetBranchStatus("value",1);
    double value    = 0;
    tree->SetBranchAddress("value", &value);

    //Loop over nBins that are saved in the tree

    for (int wait = 0; wait < 10; wait++){ //Make the code stall for a bit
        for (int b = 0; b < tree->GetEntries(); b++){
            tree->GetEntry(b);
            output.push_back(value);
        }
    }
    std::cout << convert_vector_to_string(output) << std::endl;
    return output;
}

using namespace std; //I know it is not safe, but ef it
int main() {
    cout << "Hello World!" << endl;
    load_param_values_into_vector("S3",
"/home/lhcb/kopecna/B2KstarMuMu/code/ewp-Bplus2Kstmumu-AngAna/FCNCfitter/fitResults/GenLvlFit/finalresultgenLvl_MC_SignalFit_ALLBINS_OnlyAngles.root");
}

