#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <limits.h>

#include "consoleio.h"

//------------------------------------------------------------------------------
/* safely read an integer from standard input - loop until input is correct */
int get_integer(int min, int max)
{
	int val;
    do
    {
    	char buff[10];
        char * endptr = NULL;

        printf("(%d-%d)",min,max);
        fgets(buff,sizeof(buff)-1,stdin);

		errno = 0;
        val = strtol(buff, &endptr, 10);
        if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) { perror("strtol") ; continue; }
        if (endptr == buff) { fprintf(stderr, "input is not a digit\n"); continue; }
        if ( (val >= min) && (val <= max) ) { printf ("%d\n",val); return val; };
        fprintf(stderr,"input %d is out of range (%d, %d)\n",val,min,max);
	}
    while(1);
}
//------------------------------------------------------------------------------
/* is an input pending on stdin ? 
 * 
 * 0: no input
 * 1: input pending
 * -1: error 
 */ 
int non_blocking_input(int fd)
{
	fd_set set;
	ADDI_TIMEVAL timeout;
	FD_ZERO (&set);
	FD_SET (fd, &set);
	
	/* Initialize the timeout data structure. */
	timeout.tv_sec = 0;
	timeout.tv_usec = 1;
	
	return select(FD_SETSIZE, &set, NULL, NULL, &timeout);	
}
