/*-=-=-=-=-=-=-=-=-=-=-=- RCCL/RCI Notice of Copyright -=-=-=-=-=-=-=-=-=-=-*
 *									    *
 *	Copyright (C) 1987, 1991 by John E. Lloyd.			    *
 *									    *
 *	Information on copyright permissions, as well as a complete	    *
 *	disclaimer of warranty, is given in the file COPYRIGHT.		    *
 *									    *
 *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

#include <signal.h>
#include "../h/cdefs.h"
#include "../h/ctree.h"

#include "robotsim.h"

char key_buf [256];

handler(n)
int n;
{
	printf ("Signal %d caught\n", n);
}

#define BUFSIZE		256
unsigned short buffer[BUFSIZE];

HostIO *hio;

main(argc, argv)
int argc;
char **argv;
{
	int numwords;
	int signum;
	char *keytree;
	int manipRobotId = UNDEF;

	argc--; argv++;
	while (argc)
	 {
	   if (ARGUMENT ("-id"))
	    { argc--; argv++;
	      if (argc < 1)
	       { argc = -1;
		 break;
	       }
	      if (scanInteger (&manipRobotId, *argv) == NULL)
	       { fatalMsg (-1, "Integer expected after '-id' option\n");
	       }
	      if (manipRobotId < 0)
	       { fatalMsg (-1, "robot id must be positive\n");
	       }
	    }
	   argc--; argv++;
	 }
	if (argc < 0)
	 { usageMsg (-1, "drivertest [-id <rbtid>]\n");
	 }
	if (manipRobotId == UNDEF)
	 { manipRobotId = 0;
	 }
	hio = (HostIO*)calloc(1,sizeof(HostIO));
	initHostIO(hio);

	keytree = tree_match_parse("					\
(	quit								\
	listen								\
	attach								\
	detach								\
	read								\
	write								\
	 (%d", &numwords, ",,,		\"number of words\")		\
	onSig								\
	 (%d", &signum, ",,,		\"signal number\")		\
	signal								\
)", 0);

	if (keytree == 0)
	 { printf ("ERROR/Parse error at %.30s\n", tree_match_err_at());
	   exit (-1);
	 }

	hostDevice(hio, manipRobotId, SIGHUP);
	do
 	 { tree_match (keytree, "HOSTIO> ", key_buf);

	   if (COMMAND("attach"))
	    { hostAttach(hio);
	    }
	   else if (COMMAND ("read"))
	    { if ((numwords = hostRead(hio, buffer, BUFSIZE)) < 0)
	       { printf ("Error %d\n", hio->error);
	       }
	      else
	       { int k;
		 printf ("%d words read:\n", numwords);
		 for (k=0; k<numwords; k++)
		  { printf ("%2d: 0x%04hx\n", k, buffer[k]);
		  }
	       }
	    }
	   else if (COMMAND ("write"))
	    { int k;
	      for (k=0; k<numwords; k++)
	       { buffer[k] = k + 256*k;
	       }
	      if (hostWrite(hio, buffer, numwords) < 0)
	       { printf ("Error %d\n", hio->error);
	       }
	    }
	   else if (COMMAND ("onSig"))
	    { hostOnSig (hio, signum, handler, signum);
	    }
	   else if (COMMAND ("detach"))
	    { hostDetach(hio);
	    }
	   else if (COMMAND ("signal"))
	    { hostDetach(hio);
	    }
	 }
	while (!(COMMAND("quit")));
}
	
