#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 = {0,0};
    struct serial_buffer_t bufs;

    if (FD_ISSET(NAserialComPortFds[0], selinfo->readset))
    {
	selinfo->trgEvent[0]++;
	FD_CLR(NAserialComPortFds[0], selinfo->readset);

	tcgetbuffers(NAserialComPortFds[0], &bufs);
	if (bufs.rxbuf) 
	{
	    /* serial data available */
	    selinfo->gotEvent[0]++;
	    *selinfo->timeout = &notimeout;
	}

	selinfo->scb[0] = serl_cb_add(0, RX_DATA, 
				      (cb_func)selinfo->selectEvent0, 0);
	if (selinfo->scb[0] == 0) 
	{
	    return -2;
	}
	else
	{
	    FD_SET(sockLocalfd[0], selinfo->readset);
	}
	    
    }

    if (FD_ISSET(NAserialComPortFds[1], selinfo->readset))
    {
	selinfo->trgEvent[1]++;
	FD_CLR(NAserialComPortFds[1], selinfo->readset);

	tcgetbuffers(NAserialComPortFds[1], &bufs);
	if (bufs.rxbuf) 
	{
	    /* serial data available */
	    selinfo->gotEvent[1]++;
	    *selinfo->timeout = &notimeout;
	}

	selinfo->scb[1] = serl_cb_add(1, RX_DATA, 
				      (cb_func)selinfo->selectEvent1, 0);
	if (selinfo->scb[1] == 0) 
	{
	    return -2;
	}
	else
	{
	    FD_SET(sockLocalfd[0], selinfo->readset);
	}
	    
    }

    return 0;
}

void
serl_select_off(struct ser_select_t * selinfo)
{
    if (selinfo->scb[0])
    {
	serl_cb_remove(selinfo->scb[0]);
    }
    if (selinfo->scb[1])
    {
	serl_cb_remove(selinfo->scb[1]);
    }
}

