#ifndef __NLLIBC_SYS_SELECT_H_INCLUDED__
#define __NLLIBC_SYS_SELECT_H_INCLUDED__

#define FD_SETSIZE 1024

typedef unsigned long __fd_mask;
#define __NFDBITS (sizeof(__fd_mask) * 8)
#define __fd_set_num(x, y) (((x) + ((y) - 1)) / (y))
#define __NFDSBITS __fd_set_num(FD_SETSIZE, __NFDBITS)

typedef struct fd_set {
  __fd_mask __fds_bits[__NFDSBITS];
} fd_set;

#define __fd_set_bits(fdset, fd) ((fdset)->__fds_bits[(fd) / __NFDBITS])
#define __fd_set_mask(fd) ((__fd_mask)1 << ((fd) % __NFDBITS))

#define FD_CLR(fd, fdset)    (__fd_set_bits(fdset, fd) &= ~__fd_set_mask(fd))
#define FD_SET(fd, fdset)    (__fd_set_bits(fdset, fd) |=  __fd_set_mask(fd))
#define FD_ISSET(fd, fdset) ((__fd_set_bits(fdset, fd) &   __fd_set_mask(fd)) != 0)

#define FD_COPY(sfdset, dfdset) \
	do { \
		int i, n; \
		n = __NFDSBITS; \
		for (i = 0; i < n; i++) \
			(dfdset)->__fds_bits[i] = (sfdset)->__fds_bits[i]; \
	} while (0)

#define FD_ZERO(fdset) \
	do { \
		int i, n; \
		n = __NFDSBITS; \
		for (i = 0; i < n; i++) \
			(fdset)->__fds_bits[i] = 0; \
	} while (0)

struct timeval;
struct timespec;
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
int pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *timeout, const sigset_t *newsigmask);

#endif
