#include <stdlib.h>
#include <ctype.h>
#include <errno.h>

#include <nllibc.h>

int atoi(const char *nptr)
{
  return (int)strtol(nptr, NULL, 10);
}

long strtol(const char *nptr, char **endptr, int base)
{ 
  long val, value = 0;
  int sign = 1;
  const char *top;

  if (endptr)
    *endptr = (char *)nptr;

  while (isspace(*nptr))
    nptr++;

  switch (nptr[0]) {
  case '+': sign =  1; nptr++; break;
  case '-': sign = -1; nptr++; break;
  default: break;
  }

  top = nptr;

  if (nptr[0] == '0') {
    if ((nptr[1] == 'x') || (nptr[1] == 'X')) {
      if (base == 0)
	base = 16;
      if (base == 16)
	nptr += 2;
    } else {
      if (base == 0)
	base = 8;
    }
  } else {
    if (base == 0)
      base = 10;
  }

  for (; *nptr; nptr++) {
    if (isdigit(*nptr))
      val = *nptr - '0';
    else if (islower(*nptr))
      val = *nptr - 'a' + 10;
    else if (isupper(*nptr))
      val = *nptr - 'A' + 10;
    else
      break;

    if (val >= base)
      break;

    value = value * base + val;
  }

  if (sign < 0)
    value = -value;

  if (nptr > top) {
    if (endptr)
      *endptr = (char *)nptr;
  }

  return value;
}

unsigned long strtoul(const char *nptr, char **endptr, int base)
{
  return (unsigned long)strtol(nptr, endptr, base);
}
