#ifndef RcdWriterBin_HH
#define RcdWriterBin_HH

#include <string>

#include "RcdWriter.hh"


class RcdWriterBin : public RcdWriter {

public:
  RcdWriterBin();
  virtual ~RcdWriterBin();

  bool open(const std::string &file);
  bool write(const RcdRecord &r);
  bool close();


private:
  void reset();

  int _fileDescriptor;
};



#ifdef CALICE_DAQ_ICC

#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <iostream>


RcdWriterBin::RcdWriterBin() : _fileDescriptor(-1) {
}

RcdWriterBin::~RcdWriterBin() {
  close();
}

bool RcdWriterBin::open(const std::string &file) {
  if(_fileDescriptor>=0) close();
  reset();

  _fileName=file+".bin";
  _fileDescriptor=::creat(_fileName.c_str(),S_IRUSR|S_IRGRP|S_IROTH);
  
  if(_fileDescriptor<0) {
    std::cerr << "RcdWriterBin::open()   Error opening file "
	      << _fileName << " " << strerror(errno)
	      << std::endl << std::flush;
    reset();
    return false;
  }
  
  if(_printLevel>0) {
    std::cout << "RcdWriterBin::open()   Opened file "
	      << _fileName << std::endl;
  }

  _isOpen=true;

  return true;
}

bool RcdWriterBin::write(const RcdRecord &r) {
  if(_fileDescriptor<0) return false;
  
  int n(r.totalNumberOfBytes()),m(::write(_fileDescriptor,&r,n));
  if(m!=n) {
    std::cerr << "RcdWriterBin::write()  Error writing to file;"
	      << "number of bytes written " << m << " < " << n
	      << " " << strerror(errno) << std::endl << std::flush;
    _numberOfBytes+=m;
    return false;
  }
  
  _numberOfBytes+=r.totalNumberOfBytes();
  
  return true;
}

bool RcdWriterBin::close() {
  if(_fileDescriptor<0) {
    reset();
    return false;
  }
  
  if(::close(_fileDescriptor)<0) {
    std::cerr << "RcdWriterBin::close()  Error closing file "
	      << _fileName << " " << strerror(errno)
	      << std::endl << std::flush;
    reset();
    return false;
  }
  
  if(_printLevel>0) {
    std::cout << "RcdWriterBin::close()  Closed file " << _fileName;
    if(_printLevel>1) std::cout << " after writing "
				<< _numberOfBytes << " bytes";
    std::cout << std::endl;
  }

  reset();
  return true;
}

void RcdWriterBin::reset() {
  RcdIoBase::reset();
  _fileDescriptor=-1;
}

#endif
#endif
