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

void HstLc1176(const unsigned bits=0xff, const 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 and 3 pads
  TCanvas *hstCrcNoiseCanvas[16];
  
  // Create pointers to the objects in shared memory.
  TH1F *hstCrcNoise[16][3];
  std::string hTitle[16][3];
  unsigned nCanvas(0);
  
  // Loop over channels
  for(unsigned c(0);c<16;c++) {
    hstCrcNoiseCanvas[c]=0;
    if((bits&(1<<c))!=0) {
      
      // Make title strings
      std::ostringstream title;
      title << "HstLc1176Ch";
      if(c<10) title << "0";
      title << c;
      
      hTitle[c][0]=title.str()+std::string("Numb");
      hTitle[c][1]=title.str()+std::string("Lead");
      hTitle[c][2]=title.str()+std::string("Fall");
      
      for(unsigned j(0);j<3;j++) {
	hstCrcNoise[c][j]=(TH1F*)mfile->Get(hTitle[c][j].c_str());
      }	

      // Put up canvas
      if(hstCrcNoise[c][0]!=0 &&
	 hstCrcNoise[c][1]!=0 &&
	 hstCrcNoise[c][2]!=0) {
	std::string cTitle(title.str());
	hstCrcNoiseCanvas[c]=new TCanvas((cTitle+"Canvas").c_str(),
					 cTitle.c_str(),
					 10+20*nCanvas,10+20*nCanvas,
					 610+20*nCanvas,760+20*nCanvas);
	hstCrcNoiseCanvas[c]->Divide(1,3);
	nCanvas++;
      }
    }
  }

  if(nCanvas==0) {
    std::cout << "No histograms found" << std::endl;
    return;
  }

  // Create pointers to the objects in shared memory.
  TH1F *localHstCrcNoise[16][3];
  for(unsigned c(0);c<16;c++) {
    if(hstCrcNoiseCanvas[c]!=0) {
       
      for(unsigned j(0);j<3;j++) {
	if(hstCrcNoise[c][j]!=0) localHstCrcNoise[c][j]=new TH1F(*hstCrcNoise[c][j]);
	hstCrcNoiseCanvas[c]->cd(j+1);
	localHstCrcNoise[c][j]->Draw();
      }
    }
  }

  while(!gSystem->ProcessEvents()) {
    for(unsigned c(0);c<16;c++) {
      if(hstCrcNoiseCanvas[c]!=0) {
	hstCrcNoiseCanvas[c]->Modified();
	hstCrcNoiseCanvas[c]->Update();
	
	for(unsigned j(0);j<3;j++) {
	  hstCrcNoise[c][j]=(TH1F*)mfile->Get(hTitle[c][j].c_str(),hstCrcNoise[c][j]);
	  
	  if(hstCrcNoise[c][j]!=0) {
	    localHstCrcNoise[c][j]->SetEntries(hstCrcNoise[c][j]->GetEntries());
	    for(int k(0);k<=1+hstCrcNoise[c][j]->GetNbinsX();k++) {
	      localHstCrcNoise[c][j]->SetBinContent(k,hstCrcNoise[c][j]->GetBinContent(k));
	      //if(j>0) localHstCrcNoise[c][j]->SetBinError(k,hstCrcNoise[c][j]->GetBinError(k));
	    }
	    
	    hstCrcNoiseCanvas[c]->cd(j+1);
	    localHstCrcNoise[c][j]->Draw();
	  }
	}
      }
    }
    
    gSystem->Sleep(sleepMs);
  }
}
