#include "ftype.h"
#include "select.h"
#include "termios.h"
#include "event_handler.h"
#include "select_support.h"


int
serl_select_on(struct ser_select_t * selinfo, struct timeval *notimeout) 
{
    struct serial_buffer_t bufs;
    int i = 0;

    for (i = 0 ; i < SERIAL_MAX ; i++) 
	{
		if (NAserialComPortFds[i] &&
			FD_ISSET(NAserialComPortFds[i], selinfo->readset))
		{
			selinfo->trgEvent[i]++;
			FD_CLR(NAserialComPortFds[i], selinfo->readset);

			tcgetbuffers(NAserialComPortFds[i], &bufs);
			if (bufs.rxbuf) 
			{
				/* serial data available */
				selinfo->gotEvent[i]++;
				*selinfo->timeout = notimeout;
			}
			
			selinfo->scb[i] = serl_cb_add(i, RX_DATA, 
						  (cb_func)selinfo->selectEvent, 
						  (void*)i);
			if (selinfo->scb[i] == 0) 
			{
				return -2;
			}
			else
			{
				FD_SET(sockLocalfd[0], selinfo->readset);
			}
		}
    }

    return 0;
}

void
serl_select_off(struct ser_select_t * selinfo)
{
    int i = 0;
    for (i = 0 ; i < SERIAL_MAX ; i++) {
	if (selinfo->scb[i])
	{
	    serl_cb_remove(selinfo->scb[i]);
	}
    }
}

