/*
 * Get the next event from the event queue, or block until an event is
 * available.
 *
 * Raises a Fam::Error exception if FAM couldn't check for pending
 * events, or if FAM-Ruby couldn't get the next FAM event.
 * 
 * Aliases:
 *   Fam::Connection#next_ev
 *   Fam::Connection#ev
 *
 * Examples:
 *   ev = fam.next_event
 *
 */
static VALUE fam_conn_next_ev(VALUE self)
{
  FAMConnection *conn;
  FAMEvent *ev = NULL;
  int err;

  Data_Get_Struct(self, FAMConnection, conn);

  if (!(err = FAMPending(conn))) {
    int fd = FAMCONNECTION_GETFD(conn);
    fd_set rfds;

    FD_ZERO(&rfds);
    do {
      if (err == -1)
        rb_raise(eError, "Couldn't check for pending FAM events: %s", fam_error());
      FD_SET(fd, &rfds);
      rb_thread_select(fd + 1, &rfds, NULL, NULL, NULL);
    } while (!FD_ISSET(fd, &rfds) || !(err = FAMPending(conn)));
  }

  ev = ALLOC(FAMEvent);
  err = FAMNextEvent(conn, ev);

  if (err == -1) {
    xfree(ev);
    rb_raise(eError, "Couldn't get next FAM event: %s", fam_error());
  }

  return wrap_ev(ev);
}