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

void HstCheck(const unsigned bits=0xffffff, const unsigned sleepMs=1000) {

   // Histogram consumer script. Create a canvas and 3 pads. Connect
   // to memory mapped file "hsimple.map", that was created by hprod.C.
   // It reads the histograms from shared memory and displays them
   // in the pads (sleeping for 0.1 seconds before starting a new read-out
   // cycle). This script runs in an infinite loop, so use ctrl-c to stop it.

   gROOT->Reset();

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

   // Print status of mapped file and list its contents
   mfile->Print();
   //mfile->ls();

   // Create a new canvas and 3 pads
   TCanvas *HstCheckCanvas[2][22];

   // Create pointers to the objects in shared memory.
   TH1F *_hstConfiguration[2][22][2];
   std::ostringstream sout[2][22];

   for(unsigned c(0);c<2;c++) {
     for(unsigned i(0);i<22;i++) HstCheckCanvas[c][i]=0;
     if((bits&(1<<(22+c)))!=0) {

       for(unsigned i(0);i<22;i++) {
	 if((bits&(1<<i))!=0) {

	   sout[c][i] << "HstCheckConfigurationCrate" << c << "Slot";
	   if(i<10) sout[c][i] << "0";
	   sout[c][i] << i;

	   //_hstCrcNoiseNumber[c][i]=(TH1F*)mfile->Get((sout[c][i].str()+"Number").c_str());
	   std::string temp=sout[c][i].str();
	   _hstConfiguration[c][i][0]=(TH1F*)mfile->Get((temp+"Total").c_str());
	   _hstConfiguration[c][i][1]=(TH1F*)mfile->Get((temp+"Error").c_str());

	   if(_hstConfiguration[c][i][0]!=0 && _hstConfiguration[c][i][1]!=0) {
	     HstCheckCanvas[c][i]=new 
	       TCanvas(temp.c_str(),temp.c_str(),
		   200+10*i,10+10*i,700,780);
	     HstCheckCanvas[c][i]->Divide(1,2);
	   }
	 }
       }
     }
   }

   // Loop displaying the histograms. Once the producer stops this
   // script will break out of the loop.
   while (true) {
     for(unsigned c(0);c<2;c++) {
       if((bits&(1<<(22+c)))!=0) {
	 for(unsigned i(0);i<22;i++) {
	   if((bits&(1<<i))!=0 && HstCheckCanvas[c][i]!=0) {

	     std::string temp=sout[c][i].str();
	     _hstConfiguration[c][i][0]=(TH1F*)mfile->Get((temp+"Total").c_str());
	     _hstConfiguration[c][i][1]=(TH1F*)mfile->Get((temp+"Error").c_str());
	     
	     HstCheckCanvas[c][i]->cd(1);
	     if(_hstConfiguration[c][i][0]!=0) _hstConfiguration[c][i][0]->Draw();
	     //HstCheckCanvas[c][i]->cd(2);
	     if(_hstConfiguration[c][i][1]!=0) {
	       _hstConfiguration[c][i][1]->SetFillColor(2);
	       _hstConfiguration[c][i][1]->Draw("same");
	     }

	     HstCheckCanvas[c][i]->Modified();
	     HstCheckCanvas[c][i]->Update();
	   }
	 }
       }
     }

     gSystem->Sleep(sleepMs);
     if (gSystem->ProcessEvents()) break;
   }
}
