#ifndef RunReader_HH
#define RunReader_HH

class RcdReader;


//class RunReader : public RcdReader { ?? Not needed ???
class RunReader {

public:
  RunReader();
  virtual ~RunReader();

  void directory(std::string d);

  bool open(unsigned r, bool a=false);
  bool read(RcdRecord &r);
  bool close();

private:
  bool pOpen();
  bool pClose();

  std::string _directory;
  RcdReader *_reader;
  bool _ascii;
  unsigned _runNumber;
  unsigned _fileNumber;
};


#ifdef CALICE_DAQ_ICC

#include "RcdReaderAsc.hh"
#include "RcdReaderBin.hh"

RunReader::RunReader() : _directory("data/run"), _reader(0) {
}

RunReader::~RunReader() {
}

void RunReader::directory(std::string d) {
  _directory=d;
}

bool RunReader::open(unsigned r, bool a) {
  _ascii=a;
  _runNumber=r;
  _fileNumber=0;
  return pOpen();
}

bool RunReader::read(RcdRecord &r) {
  if(!_reader->read(r)) return false;
  if(r.recordType()!=RcdHeader::fileContinuation) return true;

  // Need next file; close this and open the next  
  assert(pClose());
  _fileNumber++;
  if(!pOpen()) {
    return false;
  }

  // Check the fileContinuation records from both files are the same
  RcdArena a;
  assert(_reader->read(a));
  assert((RcdHeader)a==(RcdHeader)r);
  
  return _reader->read(r);
}

bool RunReader::close() {
  return pClose();
}

bool RunReader::pOpen() {
  assert(_reader==0);
  
  if(_ascii) _reader=new RcdReaderAsc;
  else       _reader=new RcdReaderBin;
  
  std::ostringstream sout;
  sout << _directory << "/Run";
  
  if(_runNumber<100000) sout << "0";
  if(_runNumber<10000)  sout << "0";
  if(_runNumber<1000)   sout << "0";
  if(_runNumber<100)    sout << "0";
  if(_runNumber<10)     sout << "0";
  sout << _runNumber;
  
  // Early runs had no file continuation number
  if(_runNumber>=200000) {
    sout << ".";
    if(_fileNumber<100)   sout << "0";
    if(_fileNumber<10)    sout << "0";
    sout << _fileNumber;
  }
  
  if(!_reader->open(sout.str())) {
    delete _reader;
    _reader=0;
    return false;
  }

  return true;
}

bool RunReader::pClose() {
  assert(_reader!=0);
  delete _reader;
  _reader=0;
  return true;
}

#endif
#endif
