/* $Id:$ */

/*  noddy test program to test whether vmin and select are properly obeyed */

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>

#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/select.h>

#ifndef __QNX__
#define max(a,b) ((a) > (b) ? (a) : (b))
#endif

int main( void )
{
  int fd, fifo = -1;
  struct timeval tv;
  fd_set rfd;
  int n, i;
  int endFile = 0;
  char buf[80];
  struct termios ti;
  int vmin = 4;
  int vtime = 0;
#ifndef __QNX__
  char *device = "/dev/ttyR14";
#else
  char *device = "/dev/ser1";
#endif

  printf ("Running\n");

#if 0
  if ( mkfifo ( "F", 0666 ) < 0 ) {
    printf ( "mkfifo returned -- (%d)%s\n",  errno, strerror( errno ) );
    unlink("F");
    return 1;
  }
#endif

  if( ( fd = open( device, O_RDONLY | O_NONBLOCK ) ) == -1
//      || ( fifo  = open( "./F", O_RDONLY | O_NONBLOCK ) ) == -1
	)
  {
    perror( "open" );
//    unlink("F");
    return EXIT_FAILURE;
  }

  tcgetattr( fd, &ti );
  cfmakeraw(&ti);
  tcgetattr( fd, &ti );
  ti.c_iflag = IGNBRK;
  ti.c_oflag = 0;
  ti.c_cflag = CS8 | CREAD | CLOCAL;
  ti.c_lflag = 0;
  for ( i = 0; i < NCCS; ++i ) {
    ti.c_cc[ i ] = '\0';
  }
  ti.c_cc[VMIN] = vmin;
  ti.c_cc[VTIME]  = vtime ;
  cfsetospeed( &ti, B19200 );
  cfsetispeed( &ti, B19200 );
  tcsetattr( fd, TCSANOW, &ti );
  tcflush(fd, TCIOFLUSH);
  /*
   * Clear the set of read file descriptors, and
   * add the two we just got from the open calls.
   */

  printf ("Starting the select()\n");
  FD_ZERO( &rfd );
  FD_SET( fd, &rfd );
#if 0
  FD_SET( fifo,  &rfd );
#endif
  /*
   *    Set a 5 second timeout.
   */
  tv.tv_sec = 5;
  tv.tv_usec = 0;

  errno = 0;
  switch ( n = select( 1 + max( fd, fifo ),
                        &rfd, 0, 0, &tv ) ) {
    case -1:
      perror( "select" );
      unlink("F");
      return EXIT_FAILURE;
    case  0:
      puts( "select timed out" );
      break;
    default:
      printf( "%d descriptors ready ... (errno %d)\n", n, errno );
      if( FD_ISSET( fd, &rfd ) ) {
	n = 0;
	i = 0;
#ifdef __QNX__
        endFile = tcischars ( fd );
#endif
        i = read(fd, buf, endFile);
#ifdef __QNX__
        n = tcischars ( fd );
#endif
        printf( "serial read %d was %d, left %d |%s| (%d)%s\n",
               i, endFile, n, buf, errno, strerror ( errno ) );
      }
#if 0
      if( FD_ISSET( fifo, &rfd ) ) {
        printf( " -- fifo descriptor has data pending - eof %d -- (%d)%s\n",
               endFile, errno, strerror ( errno ) );
      }
#endif
  }
//  unlink("F");
  return EXIT_SUCCESS;
}

