// #include <select.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/time.h>

#include "ardcom.h"

char ardtty[SLEN]=DEFAULTTTY;
char toardfile[SLEN]=DEFAULTTOARD;
char fromardfile[SLEN]=DEFAULTFROMARD;

void syserrorf(char *code, char *reason) {
	fprintf(stderr,"\n?? %s\t%s\t%s (%d)",code,reason,strerror(errno),errno);
	}

void errorf(char *code, char *reason) {
	fprintf(stderr,"\n?? %s\t%s",code,reason);
	}

void sysexitf(char *code,char *reason) {
	syserrorf(code,reason);
	fprintf(stderr,"\n");
	exit(1);
	}
	
//====================================
main(int argc,char **argv) {
	int fd=open(ardtty,O_RDWR|O_NOCTTY);
	if(fd<=0) sysexitf("PBTTY","Can't open TTY");
	//int fromard=open(fromardfile,O_WRONLY|O_APPEND|O_CREAT,S_IRWXU|S_IRGRP|S_IROTH);
	if(mkfifo(fromardfile,FIFOMOD))sysexitf("PBFROMARD","Can't create FROMARD");
	int fromard=open(fromardfile,O_WRONLY|O_NONBLOCK);
	printf("fromad=%s= (%d)",fromardfile,fromard);
	if(fromard<=0) sysexitf("PBFROMARD","Can't open FROMARD");

	fd_set set;
	struct timeval timeout;

      /* Initialize the timeout data structure. */
	char message[MAXMESSAGESIZE+1];
	int cursor=0;

	for(;;) {
//	printf("loop\n");
		int sres=0;

	//initialisatiuon set et timeout 
	FD_ZERO(&set);
	FD_SET(fd,&set);
       timeout.tv_sec = TIMEOUT;
       timeout.tv_usec = 0;


 		sres=select(FD_SETSIZE,&set,NULL,NULL,&timeout);
		if(FD_ISSET(fd,&set)) {
			char rb;
			int rres=0;
			while(read(fd,&rb,1)) {
//				printf(" -%c (%d)- ",rb,(int)rb);
				message[cursor++]=rb;
				if(rb==(char)10) {
					//fin message
					message[cursor]=0;
					errorf("MESSAGE",message);
					write(fromard,message,strlen(message));
					cursor=0;
					}
				if(cursor>=MAXMESSAGESIZE) {
					errorf("BUFOVF","Buffer overflow");
					cursor=0;
					};
				};
			}
		else
			printf("\nTimeout");
	};
}

