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

void HstCrcSignal(const unsigned crate=1, const unsigned slot=12,
		  const unsigned fe=3, const unsigned chip=5,
		  const unsigned chan=4, const unsigned sleepMs=1000) {
  
  gROOT->Reset();
  
  TMapFile *mfile = TMapFile::Create("HstGeneric.map");
  
  // Print status of mapped file
  mfile->Print();
  
  // Create a new canvas
  TCanvas hstHistCanvas("HstCrcSignalCanvas","HstCrcSignal",10,10,710,510);
  
  // Create pointer to the object in shared memory.
  std::string label("HstCrcSignalCrate1Slot12");
  TH2F *hstHist((TH2F*)mfile->Get(label.c_str()));
  
  if(hstHist==0) {
    mfile->ls();    
    std::cout << "Histogram " << label << " not found" << std::endl;
    return;
  }
  
  std::ostringstream sout;
  if(crate==0) sout << "ECAL crate, ";
  if(crate==1) sout << "AHCAL crate, ";
  sout << "Slot " << slot << ", FE" << fe << ", Chip "
       << chip << ", Channel " << chan;
  std::string temp(sout.str());

  TH1D localHist(*(hstHist->ProjectionY(temp.c_str(),
					12*18*fe+12*chip+chan,
					12*18*fe+12*chip+chan)));

  localHist.SetTitle(temp.c_str());
  localHist.Draw();
		 
  // Loop displaying the histograms

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

    hstHist=(TH2F*)mfile->Get(label.c_str(),hstHist);
    if(hstHist!=0) {
      Float_t entries=0.0;
      for(int i(0);i<=1+hstHist->GetNbinsY();i++) {
        Float_t c=hstHist->GetBinContent(12*18*fe+12*chip+chan,i);
        localHist.SetBinContent(i,c);
	entries+=c;
      }
      localHist.SetEntries(entries);
    }
  }
}
