/* Copyright (c) 1994 by Olin Shivers.
** Copyright (c) 1994-1995 by Brian D. Carlstrom.
** AIX version by Chipsy Sperber
**
** This file implements the char-ready? procedure for file descriptors
** and Scsh's fdports. It is not Posix, so it must be implemented for
** each OS to which scsh is ported.
**
** This version assumes two things:
** - the existence of select to tell if there is data
**   available for the file descriptor.
** - the existence of the _cnt field in the stdio FILE struct, telling
**   if there is any buffered input in the struct.
**
** Most Unixes have these things, so this file should work for them.
** However, Your Mileage May Vary.
**
** You could also replace the select() with a iotctl(FIONREAD) call, if you
** had one but not the other.
**     -Olin&Brian
*/

#include <sys/types.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include "libcig.h"
#include <errno.h>
#include <sys/select.h>

#include "stdio_dep.h" /* Make sure the .h interface agrees with the code. */

/* These two procs return #t if data ready, #f data not ready, 
** and errno if error.
*/

scheme_value char_ready_fdes(int fd)
{
  fd_set readfds;
  struct timeval timeout;
  int result;

  FD_ZERO(&readfds);
  FD_SET(fd,&readfds);

  timeout.tv_sec=0;
  timeout.tv_usec=0;

  result=select(fd+1, &readfds, NULL, NULL, &timeout);
  
  if(result == -1 ) 
    return(ENTER_FIXNUM(errno));
  if(result) 
    return(SCHTRUE);
  return(SCHFALSE);	
}

scheme_value stream_char_readyp(FILE *f)
{
  int fd = fileno(f);
  return f->_cnt > 0 ? SCHTRUE : char_ready_fdes(fd);
}

void setfileno(FILE *fs, int fd)
{
  fileno(fs) = fd;
}

int fbufcount(FILE* fs)
{ 
  return(fs->_cnt);
}

/* Returns true if there is no buffered data in stream FS
** (or there is no buffering, period.)
*/

int ibuf_empty(FILE *fs) {return fs->_cnt <= 0;}


/* Returns true if the buffer in stream FS is full 
** (or there is no buffering, period).
*/

int obuf_full(FILE *fs) {return fs->_cnt <= 0;}
