#ifndef MpsAnalysisTrimScan_HH
#define MpsAnalysisTrimScan_HH

#include <cassert>

#include "TFile.h"
#include "TF1.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TProfile.h"

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

#include "MpsAnalysisBase.hh"


class MpsAnalysisTrimScan : public MpsAnalysisBase {

public:
  MpsAnalysisTrimScan() : MpsAnalysisBase("MpsAnalysisTrimScan") {
  }

  virtual ~MpsAnalysisTrimScan() {
    //  endRoot();
  }

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

  bool configurationStart(const RcdRecord &r) {
    if(_configurationStart.configurationNumberInRun()==0) {
      
      for(unsigned region(0);region<4;region++) {
	std::ostringstream slab;
	slab << "Region" << region;
	
	std::ostringstream stit;
	stit << _runTitle << ", Region " << region << " Number of hits/BX";
	
	int step(10);
	int dacLo(_pcbConfigurationData.region01ThresholdValue()-8*step-step/2);
	if(region>1) dacLo=_pcbConfigurationData.region23ThresholdValue()-8*step-step/2;
	int dacHi(dacLo+16*step);
	
	_hRegion[region]=new TH2F((slab.str()+"Th").c_str(),(stit.str()+", Thresholds").c_str(),
				  16,dacLo,dacHi,16,0.0,16.0);
      }
    }
    return true;
  }
  
  bool bunchTrain(const RcdRecord &r) {
    SubAccessor accessor(r);

    std::vector<const MpsLocationData<MpsSensor1BunchTrainData>* >
      v(accessor.access< MpsLocationData<MpsSensor1BunchTrainData> >());
    assert(v.size()==1);
    if(doPrint(r.recordType(),1)) v[0]->print(std::cout) << std::endl;
    
    if(_configurationStart.configurationNumberInRun()==0 || _configurationStart.configurationNumberInRun()==257) {
      std::cout << " Cfg " << _configurationStart.configurationNumberInRun() << " Region hits = "
		<< " " << v[0]->data()->numberOfRegionHits(0) 
		<< " " << v[0]->data()->numberOfRegionHits(1) 
		<< " " << v[0]->data()->numberOfRegionHits(2) 
		<< " " << v[0]->data()->numberOfRegionHits(3) << std::endl;
      
    } else {
      for(unsigned region(0);region<4;region++) {
	if(region<2) _hRegion[region]->Fill(_pcbConfigurationData.region01ThresholdValue(),
					    _sensorConfigurationData.trim(42*region,0),
					    v[0]->data()->numberOfRegionHits(region));
	else         _hRegion[region]->Fill(_pcbConfigurationData.region23ThresholdValue(),
					    _sensorConfigurationData.trim(42*region,0),
					    v[0]->data()->numberOfRegionHits(region));
      }
    }
    return true;
  }


private:
  TH2F *_hRegion[4];
};

#endif
