#ifndef RcdWriterAsc_HH
#define RcdWriterAsc_HH

#include <string>
#include <fstream>
#include <iostream>

#include "RcdWriter.hh"


class RcdWriterAsc : public RcdWriter {

public:
  RcdWriterAsc();
  virtual ~RcdWriterAsc();

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


private:
  void reset();

  std::ofstream _fout;
};


#ifdef CALICE_DAQ_ICC

RcdWriterAsc::RcdWriterAsc() {
}

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

bool RcdWriterAsc::open(const std::string &file) {
  if(_fout.is_open()) {
    _fout.close();
    reset();
  }
  
  _fileName=file+".asc";
  _fout.open(_fileName.c_str(),std::ios::out);
  
  if(!_fout) {
    std::cerr << "RcdWriterAsc::open()   Error opening file " 
	      << _fileName << std::endl <<std::flush;
    reset();
    return false;
  }
  
  if(_printLevel>0) {
    std::cout << "RcdWriterAsc::open()   Opened file "
	      << _fileName << std::endl;
  }

  _isOpen=true;
  
  return true;
}

bool RcdWriterAsc::write(const RcdRecord &r) {
  if(!_fout) return false;
  
  const unsigned *p((const unsigned*)&r);
  for(unsigned i(0);i<(sizeof(RcdRecord)+3)/4;i++) {
    if(i>0) _fout << " ";
    _fout << p[i];
  }
  _numberOfBytes+=2*sizeof(RcdRecord); // Approx
  
  p=(const unsigned*)(&r+1);
  for(unsigned i(0);i<r.numberOfWords();i++) {
    if((i%16)==0) _fout << std::endl;
    else          _fout << " ";
    _fout << p[i];
  }
  _fout << std::endl;
  
  _numberOfBytes+=9*r.numberOfWords(); // Approx
  
  return _fout;
}

bool RcdWriterAsc::close() {
  if(!_fout.is_open()) {
    reset();
    return false;
  }
  
  _fout.close();

  if(_printLevel>0) {
    std::cout << "RcdWriterAsc::close()  Closed file " << _fileName;
    if(_printLevel>1) std::cout << " after writing approx "
				<< _numberOfBytes << " bytes" << std::endl;
    std::cout << std::endl;
  }

  reset();
  return true;
}

void RcdWriterAsc::reset() {
  RcdIoBase::reset();
  _fout.clear(); // Clear all errors
}

#endif
#endif
