#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/fcntl.h>

// contains the socket code
#include "socket++.h"

// contains sdata class for parsing the input string
#include "datapt.h"

// contains event name to number conversion
#include "CommandList.h"

// create client socket
sockinet my_socket(CLIENT);

int main(int argc, char **argv)
{
  int command_rec=0,command_type=0;
  char buffer[2048];
  char *datafmt_file,*trace_file;
  char *progname=argv[0];

  if(argc <3) {
    fprintf(stderr,"Use the following command line to run this program\n");
    fprintf(stderr,"%s <hostname> <socketnum> \n",progname);
    exit(1);
  }

  if(argc >=5) {
    datafmt_file=argv[3];
    trace_file=argv[4];
    printf("Slave %s: datafmt=%s and trace=%s\n",
	   progname,datafmt_file,trace_file);
    void create_datafmts(char *);
    char *datafmt_file=
      "/home/lampur/griff/escalante/ParaVision/ParaVision_datafmts";
    // read in the datafmts file used to deside event_type by the PICL reader
    create_datafmts(datafmt_file);
  }
  char *hostname=argv[1];
  int sock_num=atoi(argv[2]);
  printf("Slave: Want to connect to # %d\n",sock_num);
  
  // connect to the server
  my_socket.connect_to_server(hostname,sock_num);
  printf("Slave socket %s %d\n",my_socket.get_hostname(),
	 my_socket.get_sin_port());


  int sizein,done;

  // sdata used to parse and store the event string
  sdata the_data;
  while (!done) {

    // read until newline and don't block if nothing present
    sizein=my_socket.readln(buffer,sizeof(buffer));
    if (sizein<0) {
      printf("Error: socket has died!\n");
      done=1;
    }
    else if (sizein>0) {
      printf("$%s$",buffer);
      the_data.parse_event(buffer);
      printf("%d %d \n",the_data.get_rec_type(),the_data.get_type());
      // controller is done when cSockDone is received
      done = (the_data.get_type()==cSockDone);
    }
  }

  // close up the socket
  my_socket.close(); 
  printf("dumpit is done\n");
}
