#ifndef RcdReaderSkt_HH
#define RcdReaderSkt_HH

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

#include <iostream>

#include "RcdReader.hh"
#include "DuplexSocket.hh"

class RcdReaderSkt : public RcdReader {

public:
  RcdReaderSkt() {
  }

  virtual ~RcdReaderSkt() {
    close();
  }

  bool open(std::string file) {
    _socket=new DuplexSocket(file,1124,10);
    _numberOfBytes=0;

    if(_socket==0) {
      std::cerr << "RcdReaderSkt::open()   Error opening socket "
		<< _fileName << std::endl;
      return false;
    }

    std::cout << "RcdReaderSkt::open()   Opened socket "
	      << _fileName << std::endl;
    return true;
  }

  bool read(RcdRecord &r) {
    if(_socket==0) return false;

    int n(0);

    n=_socket->recv((char*)&r,sizeof(RcdRecord));
    if(n<=0) {
      std::cout << "RcdReaderSkt::read()   Expected end-of-file" << std::endl;
      return false;
    }
    _numberOfBytes+=sizeof(RcdRecord);

    if(r.numberOfWords()>0) {
      n=_socket->recv((char*)((&r)+1),4*r.numberOfWords());
      if(n<=0) {
	std::cerr << "RcdReaderSkt::read()   Unexpected end-of-file ";
        perror(0);
        return false;
      }
      _numberOfBytes+=4*r.numberOfWords();
    }

    return true;
  }

  bool close() {
    if(_socket==0) return false;

    delete _socket;
    std::cout << "RcdReaderSkt::close()  Closed socket "
	      << _fileName << " after writing " << _numberOfBytes
	      << " bytes" << std::endl;

    _socket=0;
    _numberOfBytes=0;
    return true;
  }

  unsigned numberOfBytes() const {
    return _numberOfBytes;
  }


private:
  DuplexSocket *_socket;
  std::string _fileName;
  unsigned _numberOfBytes;
};

#endif
