#include <signal.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/drc.h>
#include "../h/u.h"

#define NWRD    16
#define NWWR    20
#define YES     1
#define NO      0

int     onlsi1(), onlsi2();

unsigned short wbuffer[NWWR+1];
unsigned short rbuffer[NWRD];

struct drcROBOT drcROBOT  = {
	(caddr_t) wbuffer,  /* this write buffer, first word is byte cnt */
	(caddr_t) rbuffer,  /* this is read buffer */
	NWRD * 2,           /* # of bytes to read */
	onlsi1,
	onlsi2
};

int DONE = 0;
int enough = 0;
int fd, count, exch1 = 0, exch2 = 0;
int delay;

main()
{
	extern onbreak(), onhung();
	register count;

	signal(SIGINT, onbreak);
	signal(SIGHUP, onhung);

	for(count = 0; count < NWWR; ++count)
		wbuffer[count + 1] = NWWR;
	wbuffer[0] = NWWR * 2;

	if ((fd = open("/dev/drc0", 2)) < 0) {
		printf("Can't open /dev/drc0 for write\n");
		exit(1);
	}
	if ((count=write(fd, &drcROBOT, sizeof (struct drcROBOT)))
	     != sizeof (struct drcROBOT)) {
		printf("write error initing drcROBOT, count:%d\n", count);
		exit(9);
	}
	delay /= 2;             /* one for each */
	printf("enter delay ");
	scanf("%d", &delay);

	printf("end ?");
	QUERY(count);
	enough = 1;

	nap(10);
	close(fd);
	printf("spin %d exch1 %d exch2 %d\n",delay, exch1, exch2);
	for (count = 0; count < NWRD; ++count) {
		printf(" %d", rbuffer[count]);
	}
	printf("\nprogram finished DONE = %d\n",DONE);
}


onlsi1()
{
	register i;
	int spin;
	static int inserf = NO;

	if (inserf) {
		DONE = -1;
		return;
	}
	inserf = YES;

	if (enough) {
		DONE = 1;
		wbuffer[1] = 0;
		return;
	}
	spin = delay;
	while (spin--)
		;
	exch1++;
	for (i = 0; i < NWRD; ++i)
		if (rbuffer[i] != NWRD)
			DONE = -3;
	inserf = NO;
}


onlsi2()
{
	static int inserf = NO;
	int spin;

	if (inserf) {
		DONE = -2;
		return;
	}
	inserf = YES;
	if (DONE) {
		return;
	}
	exch2++;
	spin = delay;
	while (spin--)
		;
	inserf = NO;
}



onbreak()
{
	DONE = 1;
	nap(10);
	close(fd);
	printf("spin %d exch1 %d exch2 %d\n",delay, exch1, exch2);
	exit(3);
}



onhung()
{
	DONE = 1;
	nap(10);
	close(fd);
	printf("spin %d exch1 %d exch2 %d\n",delay, exch1, exch2);
	exit(4);
}
