#ifndef HstCfgCount1D_HH
#define HstCfgCount1D_HH

#include <cassert>

#include "TH1F.h"


class HstCfgCount1D {

public:
  HstCfgCount1D(const char *l, const char *t) :
    _label(l), _title(t), _hCount(0) {
    _xLo=0x7fffffff;
    _xHi=0x80000000;
  }

  virtual ~HstCfgCount1D() {
    //delete _hCount;
  }

  void runStart(unsigned r, std::string v="Value") {
    _run=r;
    _variable=v;
    _entries=false;

    _vCount.clear();
    _vValue.clear();

    //delete _hCount;
    //_hCount=0;
  }

  void configurationStart() {
    configurationStart(_vValue.size());
  }

  void configurationStart(int x) {
    for(unsigned i(0);i<_vValue.size();i++) {
      if(x==_vValue[i]) {
	_vFill=i;
	return;
      }
    }

    if(x<_xLo) _xLo=x;
    if(x>_xHi) _xHi=x;

    _vFill=_vValue.size();
    _vValue.push_back(x);
    _vCount.push_back(0.0);
    assert(_vValue.size()==_vCount.size());

  }

  void runEnd() {
    if(_vValue.size()==0) return;
    if(!_entries) return;

    std::ostringstream sTitle;
    sTitle << "Run " << _run << ", " << _title;

    int nBins(_vValue.size());
    int binSize(1);
    if(nBins>1) binSize=(_xHi-_xLo)/(nBins-1);

    if((_xHi-_xLo)<nBins) {
      nBins=_xHi-_xLo+1;
      binSize=1;
    }

    /*
    std::cout << "sTitle = " << sTitle.str() << std::endl;
    std::cout << "vValue.size() = " << _vValue.size() << std::endl;
    std::cout << "xLo,Hi = " << _xLo << " " << _xHi<< std::endl;
    std::cout << "nBins = " << nBins << std::endl;
    std::cout << "binSize = " << binSize << std::endl << std::endl;
    */

    _hCount=new TH1F((_label+"Profile").c_str(),
		     (sTitle.str()+" vs "+_variable+";"+_variable).c_str(),
		     nBins,_xLo,_xLo+nBins*binSize);
    
    for(unsigned x(0);x<_vCount.size();x++) {
      //std::cout << " Bin " << x << ", x = " << _vValue[x] << ", contents = "
      //	<< _vCount[x] << std::endl;

      _hCount->Fill(_vValue[x]+0.01,_vCount[x]);
    }
    _hCount->Draw();
  }

  void Fill(double w=1.0) {
    if(_vCount.size()==0) return;
    assert(_vFill<_vCount.size());
    _entries=true;
    _vCount[_vFill]+=w;
  }


private:
  std::string _label;
  std::string _title;

  unsigned _run;
  std::string _variable;

  bool _entries;
  int _xLo;
  int _xHi;
  unsigned _vFill;
  std::vector<int>    _vValue;
  std::vector<double> _vCount;

  TH1F *_hCount;
};

#endif
