#include "TCanvas.h"
#include "TROOT.h"
#include "TH1D.h"
#include "TF1.h"
#include "TFile.h"
#include <iostream>

using namespace std;

void macro() {
  TFile* f = new TFile("data.root");
  TH1D* h;
  f->GetObject("combined", h);
  TF1* background = new TF1("background", "[0] + x*[1] + [2] * exp(-[3] * x)",
      1, 299);
  TF1* gauss = new TF1("gauss", "[0]*exp(-0.5 * (x-[1])^2/[2]^2)",
      140, 210);
  TF1* combined = new TF1("combined", "background+gauss", 0, 300);
  h->Fit(combined, "", "", 0, 300);
  gauss->SetParameters(0.013, 170, 20);
  combined->SetParameter(4, 0.004);
  combined->SetParameter(5, 173);
  combined->SetParameter(6, 10);
  h->Fit(combined, "", "", 0, 300);
  cout << "X^2: " << h->Chisquare(combined) / (h->GetNbinsX() - 7)<< endl;
  //cout << background->GetParameters() << endl;
  background->SetLineColor(kRed);
  h->Draw();
  //gauss->Draw("Same");
  combined->Draw("Same");
}

int main() {
  macro();
}
