#include <intercept.h>
#include <sys/time.h>
#include <sys/select.h>
#include <stdio.h>
#include <unistd.h>

unsigned int newsleep(unsigned int seconds);
unsigned int (*oldsleep)(unsigned int seconds);
int newselect(int  nfds,  fd_set  *readfds,  fd_set  *writefds,
     fd_set *errorfds, struct timeval *timeout);
int (*oldselect)(int  nfds,  fd_set  *readfds,  fd_set  *writefds,
     fd_set *errorfds, struct timeval *timeout);
ssize_t newread(int fd, void *buf, size_t count);
ssize_t (*oldread)(int fd, void *buf, size_t count);

SIntercept tSleepIntercept =
   { "sleep", &newsleep, 0x0, (void **) &oldsleep, 0x0 };
SIntercept tSelectIntercept =
   { "select", &newselect, 0x0, (void **) &oldselect, 0x0 };
SIntercept tReadIntercept = 
   { "read", &newread, 0x0, (void **) &oldread, 0x0 };
SIntercept *pptInterceptFuncs[] = 
   { &tSleepIntercept, &tSelectIntercept, &tReadIntercept, 0x0 };

int _init() {

   printf("Testing library loaded successfully\n");
   iInterceptDebug = 1;

   return(0);
}

unsigned int newsleep(unsigned int seconds) {

   printf("newsleep called for %d seconds\n", seconds);

   intercept_fix_unresolved(&tSleepIntercept);
   oldsleep(2);
   intercept_override(&tSleepIntercept);

   return(0);
}

int newselect(int  nfds,  fd_set  *readfds,  fd_set  *writefds,
     fd_set *errorfds, struct timeval *timeout) {
   int iRc;

   printf("newselect called with %d fds\n", nfds);

   intercept_fix_unresolved(&tSelectIntercept);
   iRc = oldselect(nfds, readfds, writefds, errorfds, timeout);
   intercept_override(&tSelectIntercept);

   return(iRc);
}
   
ssize_t newread(int fd, void *buf, size_t count) {
   ssize_t iRc;

   printf("In read!\n");
   printf("newread called with %d fd\n", fd);

   intercept_fix_unresolved(&tReadIntercept);
   iRc = oldread(fd, buf, count);
   intercept_override(&tReadIntercept);

   return(iRc);

}
   
