/* A program to test a simple summer on the TM-2, using the ports package */

#include <stdio.h>
#include <stdlib.h>

main(argc, argv)
	int argc;
	char *argv[];
	{
	int portresult, portdelay, portinput;
	int *numbers;
	int result;
	int i, count, sum, delay;

	tm_init("");

#ifdef notdef
	if((portdelay = tm_open("delay", "w")) < 0) {
		printf("Can't open port delay\n");
		exit(1);
		}
#endif

	if((portinput = tm_open("input_data", "w")) < 0) {
		printf("Can't open port input\n");
		exit(1);
		}

	if((portresult = tm_open("result", "r")) < 0) {
		printf("Can't open port result\n");
		exit(1);
		}

	count = 10;
	if(argc>1)
		count = atoi(argv[1]);

	numbers = (int *) malloc(count * sizeof(int));
	if(numbers == NULL) {
		printf("Can't allocate memory\n");
		exit(1);
		}

	delay = 0;
	if(argc > 2)
		delay = atoi(argv[2]);

	sum = 0;
	for(i=0; i<count; i++) {
		sum += i;
		numbers[i] = i;
		}

#ifdef notdef
	if(tm_write(portdelay, &delay, sizeof(delay)) != sizeof(delay)) {
		fprintf(stderr, "error in writing to delay port\n");
		exit(1);
		}
#endif

	if(tm_write(portinput, numbers, count * sizeof(int))
				!= (count * sizeof(int))) {
		fprintf(stderr, "error in writing to input port\n");
		exit(1);
		}
	if(tm_read(portresult, &result, sizeof(result)) != sizeof(result)) {
		fprintf(stderr, "error in reading from result port\n");
		exit(1);
		}

	printf("numbers from 0 to %d; got %d; should be %d\n", count-1, result, sum);
	exit(0);
	}
