#ifndef RcdSkt2UserRW_HH
#define RcdSkt2UserRW_HH

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

#include "RcdUserRW.hh"
#include "RcdIoSkt.hh"


class RcdSkt2UserRW : public RcdUserRW {

public:
  RcdSkt2UserRW(std::string host0, unsigned port0,
		std::string host1, unsigned port1, unsigned tries) :
    _serial(false) {
    _socket[0].open(host0,port0,tries);
    _socket[1].open(host1,port1,tries);
  }

  virtual ~RcdSkt2UserRW() {
    _socket[0].close();
    _socket[1].close();
  }

  void serial(bool s) {
    _serial=s;
  }

  virtual bool record(RcdRecord &r) {
    //SubAccessor accessor(r);
    //accessor.print(std::cout,"Orig ");

    assert(_socket[0].write(r));
    assert(_socket[1].write(r));

    if(_serial) {
      assert(_socket[0].read(r));
      assert(_socket[1].read(r));

    } else {
      const unsigned nw(r.numberOfWords());
      const unsigned *newData(r.newData());

      assert(_socket[1].read(r));
      //accessor.print(std::cout,"Skt1 ");
      const unsigned newWords(r.numberOfWords()-nw);

      if(newWords>8*1024) { // 32kBytes
	std::cerr << "RcdSkt2UserRW::record()  ERROR  Socket 1 returns "
		  << newWords << " new words in record" << std::endl;
	r.RcdHeader::print(std::cerr) << std::endl;
      }

      unsigned *p(new unsigned[4*newWords]);
      memcpy(p,newData,4*newWords);

      assert(_socket[0].read(r));
      //accessor.print(std::cout,"Skt0 ");
      r.extend(newWords,p);
      //accessor.print(std::cout,"Total");
      delete [] p;
    }

    if(r.recordType()==RcdHeader::shutDown) {
      assert(_socket[0].close());
      assert(_socket[1].close());
    }

    return true;
  }

private:
  RcdIoSkt _socket[2];
  bool _serial;
};

#endif
