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

#include "HstCrcChannelStore.hh"
#include "ShmObject.hh"


void HstCrcChannel(const unsigned crate=0, 
		   const unsigned slot=0,
		   const unsigned fe=0,
		   const unsigned chip=0,
		   const unsigned chan=0,
		   const unsigned sleepMs=1000) {

  int gran(16);

  gROOT->Reset();
  
  ShmObject<HstCrcChannelStore>
    _shmHstCrcChannelStore(HstCrcChannelStore::shmKey);
  HstCrcChannelStore *_pShm(_shmHstCrcChannelStore.payload());
  assert(_pShm!=0);

  // Catch basic or real crate labelling
  _pShm->_crate=crate;
  if(crate==0xec) _pShm->_crate=0;
  if(crate==0xce) _pShm->_crate=0;
  if(crate==0xac) _pShm->_crate=1;
  if(crate==0xde) _pShm->_crate=2;

  _pShm->_slot =slot;
  _pShm->_fe   =fe;
  _pShm->_chip =chip;
  _pShm->_chan =chan;


  // Create a new canvas
  TCanvas *hstCrcNoiseCanvas;
  unsigned nCanvas(0);

  hstCrcNoiseCanvas=new TCanvas("HstChannelCanvas",
				"HstChannelTitle",
				10+20*nCanvas,10+20*nCanvas,
				610+20*nCanvas,760+20*nCanvas);
  
  // Create pointers to the objects in shared memory.

  TH1F *localHst[2];
  localHst[0]=new TH1F("HstLabelAdc","Initialising...",65536/gran,-32768,32768);
  localHst[1]=new TH1F("HstLabelBad","Initialising...",65536/gran,-32768,32768);

  localHst[0]->Draw();
  localHst[1]->SetFillColor(kRed);
  localHst[1]->Draw("same");

  //const unsigned sMs(5);
  //HstFlags::Level refresh(HstFlags::event);
  //if(acqRefresh) refresh=HstFlags::acquisition;

  //while(!gSystem->ProcessEvents() && _pShm->_inJob) {
  while(!gSystem->ProcessEvents()) {

    /*
    for(unsigned i(0);i<sleepMs && !_pShm->ready(refresh);i+=sMs) {
      std::cout << "NOT FINISHED" << std::endl;
      gSystem->Sleep(sMs);
    }
    
    if(_pShm->ready(refresh)) {
    */
    if(true) {
      localHst[0]->SetTitle((_pShm->title()+"Number;ADC counts;Events").c_str());
      localHst[1]->SetTitle((_pShm->title()+"BAD Number;ADC counts;Events").c_str());
      
      for(int i(0);i<65536/gran;i++) {
	for(int j(gran*i);j<gran*(i+1);j++) {
	  localHst[0]->SetBinContent(i+1,_pShm->_adc[j]);
	  localHst[1]->SetBinContent(i+1,_pShm->_bad[j]);
	}
      }

      hstCrcNoiseCanvas->Modified();
      hstCrcNoiseCanvas->Update();
    }
    gSystem->Sleep(sleepMs);
  }
}
