#ifndef MpsAnalysisPcbConfigurationScan_HH
#define MpsAnalysisPcbConfigurationScan_HH

#include <cassert>

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

#include "HstCfgScan.hh"
#include "MpsSensor1BunchTrainData.hh"


class MpsAnalysisPcbConfigurationScan : public MpsAnalysisBase {

public:
  MpsAnalysisPcbConfigurationScan() : MpsAnalysisBase("MpsAnalysisPcbConfigurationScan") {
    for(unsigned i(0);i<4;i++) {
      std::ostringstream sLabel[2];
      sLabel[0] << "Region" << i << "Lin";
      sLabel[1] << "Region" << i << "Log";
      
      std::ostringstream sTitle[2];
      sTitle[0] << "Region " << i << ", Number of words";
      sTitle[1] << "Region " << i << ", Log10(number of words)";

      _regionWords[i]=new HstCfgScan(sLabel[0].str().c_str(),
				     sTitle[0].str().c_str(),
				     3200,0.0,3200.0);

      _regionLogWs[i]=new HstCfgScan(sLabel[1].str().c_str(),
				     sTitle[1].str().c_str(),
				     1000,0.0,4.0);
    }
  }

  virtual ~MpsAnalysisPcbConfigurationScan() {
    for(unsigned i(0);i<4;i++) {
      _regionWords[i]->runEnd();
      _regionLogWs[i]->runEnd();
    }      
    endRoot();
  }

  virtual bool mpsAnalysisValidRun(IlcRunType::Type t) const {
    return t==IlcRunType::mpsPcbConfigurationScan;
  }

  bool runStart(const RcdRecord &r) {
    _dac=_runStart.runType().version()&0x1f;
    std::ostringstream sout;
    sout << "DAC" << std::setfill('0') <<std::setw(2) << _dac;

    for(unsigned i(0);i<4;i++) {
      _regionWords[i]->runStart(_runStart.runNumber(),sout.str());
      _regionLogWs[i]->runStart(_runStart.runNumber(),sout.str());
    }
    return true;
  }

  bool runEnd(const RcdRecord &r) {
    for(unsigned i(0);i<4;i++) {
      _regionWords[i]->runEnd();
      _regionLogWs[i]->runEnd();
    }
    return true;
  }

  bool configurationStart(const RcdRecord &r) {
    for(unsigned i(0);i<4;i++) {
      _regionWords[i]->configurationStart(_vPcbConfigurationData[0].dac(_dac));
      _regionLogWs[i]->configurationStart(_vPcbConfigurationData[0].dac(_dac));
    }
    return true;
  }
  
  bool bunchTrain(const RcdRecord &r) {
    SubAccessor accessor(r);

    std::vector<const MpsLocationData<MpsSensor1BunchTrainData>* >
      w(accessor.access< MpsLocationData<MpsSensor1BunchTrainData> >());
    assert(w.size()==1);
    if(doPrint(r.recordType(),1)) w[0]->print(std::cout) << std::endl;

    for(unsigned i(0);i<4;i++) {
      _regionWords[i]->Fill(w[0]->data()->numberOfRegionHits(i));
      if(w[0]->data()->numberOfRegionHits(i)>0) {
	_regionLogWs[i]->Fill(std::log10((double)w[0]->data()->numberOfRegionHits(i)));
      }
    }

    return true;
  }


private:
  unsigned _dac;
  HstCfgScan *_regionWords[4];
  HstCfgScan *_regionLogWs[4];
};

#endif
