#ifndef HstMpsBunchTrainShm_HH
#define HstMpsBunchTrainShm_HH

#include <cassert>

#include "RcdUserRO.hh"
#include "SubAccessor.hh"

#include "HstMpsBunchTrainStore.hh"
#include "ShmObject.hh"


class HstMpsBunchTrainShm : public RcdUserRO {

public:
  HstMpsBunchTrainShm() :
    _shmHstMpsBunchTrainStore(HstMpsBunchTrainStore::shmKey),
    _pShm(_shmHstMpsBunchTrainStore.payload()) {
    assert(_pShm!=0);
  }

  virtual ~HstMpsBunchTrainShm() {
  }

  bool record(const RcdRecord &r) {
    if(doPrint(r.recordType())) {
      std::cout << "HstMpsBunchTrain::record()" << std::endl;
      r.RcdHeader::print(std::cout," ") << std::endl;
    }

    DaqTwoTimer tt;

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

    _pShm->fill(r);

    switch (r.recordType()) {
  
    case RcdHeader::runStart: {
      _pShm->reset(1);

      SubAccessor accessor(r);

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

      for(unsigned i(0);i<v.size() && i<4;i++) {
	_pShm->_sensorId[i]=v[i]->sensorId();
      }

      break;
    }
  
    case RcdHeader::configurationStart: {
      _pShm->reset(2);
      break;
    }
  
    case RcdHeader::bunchTrain: {
      _pShm->reset(3);

      SubAccessor accessor(r);

      std::vector<const MpsLocationData<MpsSensor1BunchTrainData>* >
	v(accessor.access< MpsLocationData<MpsSensor1BunchTrainData> >());
      
      //assert(v.size()<=1);

      unsigned nMpsBunchTrain(0);

      for(unsigned i(0);i<v.size() && i<4;i++) {

      // TEMP!!! ONLY DO SENSOR #8
      //for(unsigned i(0);i<v.size();i++) {
	//if(v[i]->sensorId()==8) {

	nMpsBunchTrain++;
	
	std::vector<MpsSensor1Hit> vh(v[i]->data()->hitVector());
	for(unsigned j(0);j<vh.size();j++) {
	  for(unsigned k(0);k<4;k++) {
	    _pShm->_sensor[i][k].fill(vh[j].pixelX(),vh[j].pixelY());
	  }
	}
      }

      // Store number of histories found
      _pShm->_size.fill(nMpsBunchTrain);

      break;
    }
  
    default: {
      break;
    }
    };

    // Finish up
    _pShm->_validBunchTrain=true;


    tt.setEndTime();
    UtlTimeDifference dt(tt.timeDifference());
    if(dt.seconds()==0) {
      _pShm->_timers[r.recordType()].fill(dt.microseconds()/10);
    } else {
      _pShm->_timers[r.recordType()].fill(10000);
    }

    return true;
  }

private:
  ShmObject<HstMpsBunchTrainStore> _shmHstMpsBunchTrainStore;
  HstMpsBunchTrainStore *_pShm;
};

#endif
