#include <stdlib.h>
#include <string>
#include "TVectorT.h"
#include <iostream>
#include <sstream>
#include <TTree.h>
#include <TFile.h>
#include <TH1F.h>
#include <TGraph.h>
#include <TAxis.h>
#include <TCut.h>
#include <stdio.h>
#include <cstdio>
#include "TotemMap.hpp"

using namespace std;

TVectorD EffRadius(long int run_number, double xoffsetmm, double yoffsetmm, long int minrad, Int_t nsteps){
	  TVectorD rad_eff (nsteps+1);
	  string run;                           //Run number to be converted to string
	  char run_n[30];
	  string offsetx;                       //Offsets to be converted to strings
	  string offsety;
	  
	  sprintf(run_n,"%ld",run_number);      //Converting run number to a string
	  run = string(run_n);
	  {                                     //Converting x offset to string
	    ostringstream xx;
	    xx << xoffsetmm;
	    offsetx = xx.str();
	  }
	  {                                     //Converting y offset to string
	    ostringstream yy;
	    yy << yoffsetmm;
	    offsety = yy.str();
	  }
	
	  /*
	  End converting numbers to strings ******************************************
	  */

	  string rootfile_name;
	  string recofile_name;

      if (run_number < 10)
	{
	  rootfile_name = "../RootData/Run000" + run + ".root";
	  recofile_name = "../RootData/Run000" + run + "_reco.root";
	}
      else
	{
	  if (run_number < 100)
	    {
	      rootfile_name = "../RootData/Run00" + run + ".root";
	      recofile_name = "../RootData/Run00" + run + "_reco.root";
	    }
	  else
	    {
	      rootfile_name = "../RootData/Run0" + run + ".root";
	      recofile_name = "../RootData/Run0" + run + "_reco.root";
	    }
	}

	  TFile file0(rootfile_name.c_str());
	  TTree* t = dynamic_cast<TTree*>(file0.Get("rd51tb"));
	  t->AddFriend("recotree",recofile_name.c_str());
	
          //Selecting high quality tracks and events
	  TCut goodtr("goodtr","trackx@.GetEntries()==1 && tracky@.GetEntries()==1 && trackx[0].chi2<10 && tracky[0].chi2<10 && residualx[0]<10 && residualy[0]<10");
	  Int_t count = 0;
	
	  //Scans radius from mirad to maxrad every 5 millimeters
	  for (long int i = minrad; i < 2*nsteps + 1; i = i + 2)
	    {
	      string irad;                      //Converts current radius to string
	      ostringstream rad;
	      rad << i;
	      irad = rad.str();
	    
	      string draw_string = "Sum$((dist(GetX(bgch.ch),GetY(bgch.ch),(trackx[0]->q - trackx[0]->m*400" + offsetx + "),(tracky[0]->q -tracky[0]->m*400 + " + offsety + ")))<" + irad + ") >>h(5,0,5)";
	
	      t->Draw(draw_string.c_str(),goodtr);
	
	      TH1F *h = (TH1F*)gDirectory->Get("h");
	
	      Double_t ieff = 1. - h->GetBinContent(1)/h->GetEntries();
	      
	      rad_eff[count] = ieff;
	      count++;
	    }

	  return rad_eff;

}
