#include <stdio.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <rtl_fifo.h>
#include <math.h>


void outf(int fd,double d)
{
	char x[100];
	int n = sprintf(x,"%f\n",d);
	write(fd,x,n);
}



int main(void)
{
	fd_set rfds;
        struct timeval tv;
	int fifofd[2], datafd[2];
	int findex;
	double d;
	
	if ((fifofd[0] = open("/dev/rtf1", O_RDONLY)) < 0) {
		fprintf(stderr, "Error opening /dev/rtf1\n");
		exit(1);
	}

	if ((fifofd[1] = open("/dev/rtf2", O_RDONLY)) < 0) {
		fprintf(stderr, "Error opening /dev/rtf2\n");
		exit(1);
	}
	umask(0777);
	if ((datafd[0] = creat("sin.data", 0777)) < 0) {
		fprintf(stderr, "Error opening sin.data\n");
		exit(1);
	}

	if ((datafd[1] = creat("cos.data", 0777)) < 0) {
		fprintf(stderr, "Error opening cos.data\n");
		exit(1);
	}



	/* now start the tasks */
	printf("Starting\n");
		FD_ZERO(&rfds);
		FD_SET(fifofd[0], &rfds);
		FD_SET(fifofd[1], &rfds);
		tv.tv_sec = 1;
		tv.tv_usec = 0;
		

		while(select(FD_SETSIZE, &rfds, NULL, NULL, &tv) >0){
			printf("!");
			if(FD_ISSET(fifofd[0], &rfds)) findex = 0;
			else findex = 1;
			read(fifofd[findex], &d, sizeof(double)); 
			outf(datafd[findex],d);
			}
	printf("Done!");
	return 0;
}

