#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
#include <stdint.h>

intmax_t strtoirange(const char * __restrict, char ** __restrict, int,
    intmax_t, intmax_t, int *);

intmax_t
strtoirange(const char * __restrict ptr, char ** __restrict eptr, int base,
    intmax_t lo, intmax_t hi, int *rerror)
{
	int serrno;
	intmax_t im;
	char *ep;

	if (*eptr == NULL)
		eptr = &ep;

	serrno = errno;
	errno = 0;
	im = strtoimax(ptr, eptr, base);
	if (ptr == *eptr || *eptr) {
		*rerror = EINVAL;
		errno = serrno;
		return im;
	}

	if ((errno == ERANGE && (im == INTMAX_MAX || im == INTMAX_MIN)) ||
	    (im < lo || im > hi)) {
		*rerror = errno;
		errno = serrno;
		return im;

	}

	*rerror = 0;
	return im;
}