#include <stdlib.h>
#include <sys/select.h>
#include "debug.h"
#include "selecthelper.h"
#include <errno.h>

fd_set *init_fdset(int *fd_array, int n) {
	int i;
	fd_set *r = (fd_set *)malloc(sizeof(fd_set));
	FD_ZERO(r);
	for(i=0; i<n; i++)
		FD_SET(fd_array[i],r);
	return r;
}

int *wait_fd(int *fd_array, int len, int time)
{
   fd_set *rfds = init_fdset(fd_array,len);
   struct timeval tv;
   int retval;
	 int i,j;
	 int highest = -1;
	 int *out;
	 
	 for(i=0; i<len; i++) {
	 	if (fd_array[i]>highest) highest=fd_array[i];
	 }

   /* Wait up to #time seconds. */
   tv.tv_sec = time;
   tv.tv_usec = 0;

   retval = select(highest+1, rfds, NULL, NULL, &tv);
   /* Don't rely on the value of tv now! */

   errlog(retval);
	 if (!retval) {
	   free(rfds);
		 errno=ETIME;
	   return NULL;
	 }
   /* One or more FD_ISSET(0, &rfds) will be true. 
	  * Return the all available fd.
		*/
	 out = malloc(sizeof(int)*(retval+1));
   for(i=0,j=0; i<len; i++) {
	 	if (FD_ISSET(fd_array[i],rfds)) {
			out[j]=fd_array[i];
			j++;
		}
	 }
	 out[retval]=0;
	 free(rfds);
	 return out;
}

int in(int *list, int fd){
	int i=0;
	while(list[i]!=0 && list[i]!=fd) i++;
	fprintf(stderr,"i=%d\n",i);
	if (list[i]==fd) return 1;
	else return 0;
}

