/*
 * MAC  Version 2.0           Author :  Vincent Hayward
 *                                      School of Electrical Engineering
 *                                      Purdue University
 *      Dir     : sys
 *      File    : lsitst.c
 *      Remarks : fifo test program
 *      Usage   : cc vaxtst.c ; use with lsitst
 */

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

#define YES     1
#define NO      0

int     onlsi1(), onlsi2();

struct fifobuf wbuffer, rbuffer;

struct drcROBOT drcROBOT  = {
	(caddr_t) &wbuffer,  /* this write buffer */
	(caddr_t) &rbuffer,  /* this is read buffer */
	onlsi1,
	onlsi2
};

int DONE = 0;
int enough = 0;
int fd, exch1 = 0, exch2 = 0;
int delay1, delay2;

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

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

	for(count = 0; count < FIFOBUFS; ++count)
		wbuffer.data[count] = OD;
	wbuffer.wc = FIFOBUFS;

	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);
	}

	printf("enter delay1 delay2 ");
	scanf("%d%d", &delay1, &delay2);

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

	while (!DONE)
		nap(10);
	close(fd);

	printf("wc %d exch1 %d exch2 %d\n",rbuffer.wc, exch1, exch2);
	for (count = 0; count < FIFOBUFS; ++count) {
		printf("%o ", rbuffer.data[count] & 0xffff);
	}
	printf("\nprogram finished DONE = %d , time spend in f1 %f f2 %f\n",
		DONE, 3.88 * (double)delay1, 3.88 * (double)delay2);
}


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

	if (inserf) {
		DONE = -1;
		return;
	}
	inserf = YES;
	if (DONE) {
		inserf = NO;
		return;
	}
	if (enough) {
		wbuffer.data[0] = 0;
		DONE = 1;
		inserf = NO;
		return;
	}
	for (i = 0; i < FIFOBUFS; ++i) {
		if (rbuffer.data[i] != (short)ID) {
			wbuffer.data[0] = 0;
			DONE = -3;
		}
	}
	spin = delay1;
	while (spin--)
		;
	exch1++;
	inserf = NO;
}


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

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



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



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