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

#include <iostream>

#include "RcdWriter.hh"
#include "DuplexSocket.hh"

using namespace std;

int main() {
  DuplexSocket *_socket=new DuplexSocket(1201);

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

    std::cout << "RcdWriterSkt::open()   Opened socket "
	      << std::endl;


    while(true) {
      unsigned _recvLength;
      char _recvData[65];


    _recvLength=64;
    for(unsigned i(0);i<64 && _recvLength==64;i++) {
      int n(-1);
      std::cout << "Waiting for byte " << i << std::endl;
      n=_socket->recv(_recvData+i,1);
      std::cout << "Got byte " << i << " = " << (int)_recvData[i] << std::endl;

      _recvData[i+1]='\0';
        std::cout << "cstring recv ed ==>" << _recvData << "<==" << std::endl;



      if(n!=1) {
	std::cerr << "Error reading from socket; number of bytes written = "
		  << n << " < 1" << std::endl;
	perror(0);
	_recvLength=i+1;
      }
      if(_recvData[i]=='#') _recvLength=i+1;
    }

        std::cout << "cstring recv ed ==>" << _recvData << "<== length = "
	      << _recvLength << std::endl;

  
  
    unsigned r(1);
      cout << "Sleeping for " << r << " secs" << std::endl;
      sleep(r);

      char _sendData[64];
      _sendData[0]='s';
      _sendData[1]='k';
      _sendData[2]='t';
      _sendData[3]='#';
      int n=4;

      if(!_socket->send(_sendData,n)) {
	std::cerr << "RcdWriterSkt::write()  Error writing to file; number of bytes written < "
		  << n << std::endl;
	perror(0);
      //_numberOfBytes+=n;
      }
    }

    delete _socket;

}
