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

void HstTH2F(const char* const label, 
	     const char* const options="box", 
	     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("HstTH2FCanvas","HstTH2F",10,10,700,500);
  
  // Create pointer to the object in shared memory.
  TH2F *hstHist((TH2F*)mfile->Get(label));
  
  if(hstHist==0) {
    mfile->ls();    
    std::cout << "TH2F histogram " << label << " not found" << std::endl;
    return;
  }
  
  TH2F localHist(*hstHist);
  localHist.Draw(options);
  
  // Loop displaying the histograms
  
  while (!gSystem->ProcessEvents()) {
    hstHistCanvas.Modified();
    hstHistCanvas.Update();
    gSystem->Sleep(sleepMs);
    
    // Now update the histogram contents only
    hstHist=(TH2F*)mfile->Get(label,hstHist);
    if(hstHist!=0) {
      localHist.SetTitle(hstHist->GetTitle());
      localHist.SetEntries(hstHist->GetEntries());
      for(int i(0);i<=1+hstHist->GetNbinsX();i++) {
	for(int j(0);j<=1+hstHist->GetNbinsY();j++) {
	  localHist.SetBinContent(i,j,hstHist->GetBinContent(i,j));
	  localHist.SetBinError(i,j,hstHist->GetBinError(i,j));
	}
      }
    }
  }
}
