#include <TGraph.h>
#include <TGraphErrors.h>
#include <TCanvas.h>
#include <TAxis.h>
#include <stdio.h>
#include <cstdio>
#include "TVectorT.h"
#include <stdlib.h>
#include <iostream>
#include "TMultiGraph.h"
#include "TAxis.h"
#include "TGaxis.h"
#include "TF1.h"
#include "TLegend.h"
#include "TLatex.h"
#include <TFile.h>

TVectorD HVscanAmacro(long int first_run = 337, long int last_run = 554);

void MuPiComp(){

  Int_t MuSize = 8;
  Int_t PaiSize = 5;

  TVectorD MuHV (MuSize);
  MuHV[0] = 5.25;
  MuHV[1] = 5.20;
  MuHV[2] = 5.15;
  MuHV[3] = 5.10;
  MuHV[4] = 5.00;
  MuHV[5] = 4.90;
  MuHV[6] = 4.80;
  MuHV[7] = 4.60;

  TVectorD PaiHV (PaiSize);
  PaiHV[0] = 5.0;
  PaiHV[1] = 4.9;
  PaiHV[2] = 4.8;
  PaiHV[3] = 4.6;
  PaiHV[4] = 4.5;

  TVectorD pions (PaiSize);
  pions[0] = 0.993580;
  pions[1] = 0.990909;
  pions[2] = 0.978039;
  pions[3] = 0.722178;
  pions[4] = 0.475573;

  TVectorD pionsey (PaiSize);
  pionsey[0] = 0.001364;
  pionsey[1] = 0.000910;
  pionsey[2] = 0.001474;
  pionsey[3] = 0.005644;
  pionsey[4] = 0.008672;

  TVectorD muons (MuSize);
  muons = HVscanAmacro(337,554);

  TVectorD muonsey (MuSize);

  for (Int_t i = 0; i < MuSize; i++)
    {
      muonsey[i] = sqrt( muons[i] * (1 - muons[i]) / 5000 );
    }

  TVectorD pionsex (PaiSize);

  TVectorD muonsex (MuSize);

  for (Int_t i = 0; i < PaiSize; i++)
    {
      pionsex[i] = 0;
    }

  for (Int_t i = 0; i < MuSize; i++)
    {
      muonsex[i] = 0;
    }

  TGraphErrors *pai = new TGraphErrors (PaiHV,pions,pionsex,pionsey);
  pai->SetTitle("150GeV/c #pi beam [~38kHz]");
  pai->SetMarkerColor(kRed);
  pai->SetLineColor(kRed);
  pai->SetLineWidth(2);

  TGraphErrors *mu = new TGraphErrors (MuHV,muons,muonsex,muonsey);
  mu->SetTitle("150GeV/c #mu beam [~0.8kHz]");
  mu->SetMarkerColor(kBlue);
  mu->SetLineColor(kBlue);
  mu->SetLineWidth(2);

  TCanvas *c1 = new TCanvas("c1","Hadrons-Leptons comparison");

  TMultiGraph *plot = new TMultiGraph();
  plot->Add(pai);
  plot->Add(mu);
  plot->Draw("ACP");

  plot->GetYaxis()->SetRangeUser(0,1);
  // These commands have to be put after the Draw command,
  // or it will cause segmentation violation
  plot->GetXaxis()->SetRangeUser(4.5,5.25);
  plot->GetYaxis()->SetDecimals();
  plot->GetXaxis()->SetDecimals();
  plot->GetXaxis()->SetTitle("Divider HV [kV]");
  plot->GetYaxis()->SetTitle("LG efficiency");

  c1->Update();
  c1->SetGridx();
  c1->SetGridy();
  c1->SetTickx();
  c1->SetTicky();
  c1->Update();

  TLegend *legend = new TLegend (0.1,0.4,0.4,0.9);
  legend->SetHeader("#pi - #mu beam comparison");
  legend->AddEntry(pai,pai->GetTitle(),"lp");
  legend->AddEntry(mu,mu->GetTitle(),"lp");
  legend->Draw();

  TF1 *f1 = new TF1 ("f1","x",750,875);
  f1->Update();

  TGaxis *current = new TGaxis (4.5, 1, 5.25, 1, "f1", 1020, "-");
  current->SetTitle("Divider current [uA]");
  current->SetTitleOffset(1.1);
  current->Draw();
  c1->Update();

}
