#ifndef HstLalHodoscopeShm_HH
#define HstLalHodoscopeShm_HH

#include <cassert>

#include "TH1F.h"

#include "DaqRunStart.hh"

#include "RcdUserRO.hh"
#include "RcdWriterDmy.hh"
#include "RcdWriterAsc.hh"
#include "RcdWriterBin.hh"

#include "UtlAverage.hh"
#include "SubAccessor.hh"

#include "HstLalHodoscopeStore.hh"
#include "ShmObject.hh"


class HstLalHodoscopeShm : public RcdUserRO {

public:
  HstLalHodoscopeShm() :
    _shmHstLalHodoscopeStore(HstLalHodoscopeStore::shmKey),
    _pShm(_shmHstLalHodoscopeStore.payload()) {
    assert(_pShm!=0);
  }

  virtual ~HstLalHodoscopeShm() {
  }

  bool record(const RcdRecord &r) {

    // Check for user-requested reset
    if(_pShm->_resetNow) {
      _pShm->reset();
      _pShm->_resetNow=false;
    }

    _pShm->fill(r);

    switch (r.recordType()) {
  
    case RcdHeader::runStart: {
      if(_pShm->_resetLevel==HstFlags::run) _pShm->reset();



      _events=0;

      break;
    }
  
    case RcdHeader::configurationStart: {
      if(_pShm->_resetLevel==HstFlags::configuration) _pShm->reset();
      break;
    }
  
    case RcdHeader::acquisitionStart: {
      if(_pShm->_resetLevel==HstFlags::acquisition) _pShm->reset();
      break;
    }
  
    case RcdHeader::event: {
      if(_pShm->_resetLevel==HstFlags::event) _pShm->reset();

      SubAccessor accessor(r);

      std::vector<const BmlLalHodoscopeEventData*>
        v(accessor.access< BmlLalHodoscopeEventData >());

      if(v.size()==1) {
	for(unsigned i(0);i<v[0]->numberOfHits();i++) {
	  unsigned xy(1);
	  if(v[0]->hitX(i)) xy=0;

	  unsigned ch(v[0]->hitChannel(i));
	  if(v[0]->hitValue(i)>50) _pShm->_digitalHits[xy].fill(ch);
	  _pShm->_analogueHits[xy][ch]+=v[0]->hitValue(i);
	}

	/*
	for(unsigned xy(0);xy<2;xy++) {
	  for(unsigned ch(0);ch<128;ch++) {
	    if(v[0]->digitalHit(xy,ch)) _pShm->_digitalHits[xy].fill(ch);
	    //_pShm->_analogueHits[xy][ch]+=v[0]->analogueHit(xy,ch);

	    // FAKE!!!
	    if((ch+10*xy)>90 && (ch+10*xy)<100) {
	      //_pShm->_digitalHits[xy].fill(ch);
	      _pShm->_analogueHits[xy][ch]+=(_events%100);
	    } else {
	      _pShm->_analogueHits[xy][ch]+=(_events%10);
	    }
	  }
	}
	*/
      }

      _pShm->_validEvent=true;


      _events++;


      break;
    }
  
    default: {
      break;
    }
    };
 
    return true;
  }

private:
  ShmObject<HstLalHodoscopeStore> _shmHstLalHodoscopeStore;
  HstLalHodoscopeStore *_pShm;


  unsigned _events;
};

#endif
