#ifndef MpsSensor1FullTimeStamps_HH
#define MpsSensor1FullTimeStamps_HH

#include <iostream>
#include <fstream>
#include <cassert>


class MpsSensor1FullTimeStamps {

public:
  MpsSensor1FullTimeStamps(const MpsSensor1BunchTrainData &m) {

    memset(&(_fullTimeStamp[0][0][0]),0,4*168*7*sizeof(unsigned));

    //const unsigned groupOrder[7]={6,3,2,1,4,5,0};//{7,4,3,2,5,6,1};

    const MpsSensor1BunchTrainDatum *p(m.data());
    for(unsigned region(0);region<4;region++) {

      unsigned row(168),nRow(0),fullTimeStamp[7];
      for(unsigned i(0);i<m.numberOfRegionHits(region);i++) {

	// Check for change of row number
	if(p[i].row()!=row) {

	  // Set values for new row
	  row=p[i].row();
	  nRow=1;

	  //if(region==0 && row==0) {
	  //  std::cout << "Region " << region << ", row " << row
	  //	      << ", number of hits initialised to = " << nRow << std::endl;
	  //}

	  for(unsigned group(0);group<7;group++) {
	    fullTimeStamp[group]=p[i].timeStamp();
	    if(p[i].timeStamp()>0 && group>p[i].group()) fullTimeStamp[group]--;
	  }
	  /*
	  // Need to know which groups were excluded for this timestamp
	  bool previous(true);
	  for(unsigned group(0);group<7;group++) {
	    if(!previous) fullTimeStamp[groupOrder[group]]--;
	    if(groupOrder[group]==p[i].group()) previous=false;
	  }
	  */

	// Not a new row so simply increment the entry counter
	} else {
	  nRow++;

	  //if(region==0 && row==0) {
	  //  std::cout << "Region " << region << ", row " << row
	  //	      << ", number of hits so far = " << nRow << std::endl;
	  //}

	  // If previous row had 19 entries, it was full
	  if(nRow>=19) {
	    //if(region==0 && row==0) {
	    //  std::cout << "Region " << region << ", row " << row
	    //	<< ", number of hits = " << nRow << " >=19" << std::endl;
	    //}

	    for(unsigned group(0);group<7;group++) {
	      _fullTimeStamp[region][row][group]=fullTimeStamp[group];

	      //if(region==0 && row==0) {
	      //std::cout << " Timestamp for group " << group << " = "
	      //		  << _fullTimeStamp[region][row][group] << std::endl;
	      //}
	    }
	  }
	}
      }
    }
  }

  virtual ~MpsSensor1FullTimeStamps() {
  }

  unsigned fullTimeStamp(unsigned region, unsigned row, unsigned group) const {
    assert(region<4);
    assert(row<168);
    assert(group<7);

    return _fullTimeStamp[region][row][group];
  }

  unsigned fullTimeStamp(unsigned x, unsigned y) const {
    assert(x<168);
    assert(y<168);

    unsigned region(x/42);
    unsigned group((x%42)/6);
    return _fullTimeStamp[region][y][group];
  }

  void fullTimeStamp(unsigned region, unsigned row, unsigned group, unsigned t) {
    assert(region<4);
    assert(row<168);
    assert(group<7);

    _fullTimeStamp[region][row][group]=t;
  }


private:
  unsigned _fullTimeStamp[4][168][7];
};

#endif
