#include "TMapFile.h"
#include "TSystem.h"
#include "TCanvas.h"
#include "TH1D.h"

void HstTH1D(const char* const label, unsigned sleepMs=1000) {

  gROOT->Reset();
  
  // Open the memory mapped file in "READ" (default) mode.
  TMapFile* mfile = TMapFile::Create("HstGeneric.map");

  // Print status of mapped file
  mfile->Print();
  
  // Create a new canvas
  TCanvas hstHistCanvas("HstHistCanvas","HstHist",10,10,700,500);
   
  // Create pointer to the object in shared memory.
  TH1D *hstHist((TH1D*)mfile->Get(label));

  if(hstHist==0) {
    mfile->ls();    
    std::cout << "Histogram " << label << " not found" << std::endl;
    return;
  }

  TH1D localHist(*hstHist);
  localHist.Draw();

  // Loop displaying the histograms

  while (!gSystem->ProcessEvents()) {
    hstHistCanvas.Modified();
    hstHistCanvas.Update();
    gSystem->Sleep(sleepMs);

    // Now update the histogram contents only
    hstHist=(TH1D*)mfile->Get(label,hstHist);
    if(hstHist!=0) {
      localHist.SetTitle(hstHist->GetTitle());
      localHist.SetEntries(hstHist->GetEntries());
      for(int i(0);i<=1+hstHist->GetNbinsX();i++) {
	localHist.SetBinContent(i,hstHist->GetBinContent(i));
	localHist.SetBinError(i,hstHist->GetBinError(i));
      }
    }
  }
}
