// basic stdlib functions
#include <stdint.h>
#include <stdlib.h>

#define LONG_MIN -2147483648
#define LONG_MAX 2147483647

// THIS IS NO LONGER DEFINED HERE, BUT IN start_serial's init.S, BECAUSE
// the implementation is tightly coupled with `start_serial` anyway...
//   
// void exit(int status)
// {
//   // Jump to EFP_PROG_EXIT when quit
//   __asm__ __volatile__ (
//       "moveal 0x490.l, %a0\n\t"
//       "jmp %a0@\n\t"
//   );
// }

// THIS IS STILL DEFINED HERE, RATHER THAN IN start_serial's init.S, BECAUSE
// it just takes a sledgehammer to the runtime environment, doesn't care about
// any of the C runtime set up in `start_serial` and jumps directly to the 
// hardware vector "owned by" the firmware...
//
void abort(void)
{
  // Jump directly to reset vector when abort
  __asm__ __volatile__ (
      "moveal 0x4.l, %a0\n\t"
      "jmp %a0@\n\t"
  );
}

static unsigned int rand_seed = 42;
void srand(unsigned int seed)
{
  rand_seed = seed;
}

int rand(void)
{
  rand_seed = rand_seed * 1103515245 + 12345;
  return (rand_seed & RAND_MAX);
}

long
strtol (const char *__restrict s,
  char **__restrict ptr,
  int base)
{
  //register const unsigned char *s = (const unsigned char *)nptr;
  register unsigned long acc;
  register int c;
  register unsigned long cutoff;
  register int neg = 0, any, cutlim;

  /* if end ptr non-NULL, store string start by default */
  if (ptr) {
    *ptr = (char *)s;
  }

  if (base < 0 || base == 1 || base > 36) {
    return 0;
  }

  /*
   * Skip white space and pick up leading +/- sign if any.
   * If base is 0, allow 0x for hex and 0 for octal, else
   * assume decimal; if base is already 16, allow 0x.
   */
  do {
    c = *s++;
  } while (c == ' ');
  if (c == '-') {
    neg = 1;
    c = *s++;
  } else if (c == '+')
    c = *s++;
  if ((base == 0 || base == 16) &&
      c == '0' && (*s == 'x' || *s == 'X')) {
    c = s[1];
    s += 2;
    base = 16;
  }
  if (base == 0)
    base = c == '0' ? 8 : 10;

  /*
   * Compute the cutoff value between legal numbers and illegal
   * numbers.  That is the largest legal value, divided by the
   * base.  An input number that is greater than this value, if
   * followed by a legal input character, is too big.  One that
   * is equal to this value may be valid or not; the limit
   * between valid and invalid numbers is then based on the last
   * digit.  For instance, if the range for longs is
   * [-2147483648..2147483647] and the input base is 10,
   * cutoff will be set to 214748364 and cutlim to either
   * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
   * a value > 214748364, or equal but the next digit is > 7 (or 8),
   * the number is too big, and we will return a range error.
   *
   * Set any if any `digits' consumed; make it negative to indicate
   * overflow.
   */
  cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
  cutlim = cutoff % (unsigned long)base;
  cutoff /= (unsigned long)base;
  for (acc = 0, any = 0;; c = *s++) {
    if (c >= '0' && c <= '9')
      c -= '0';
    else if (c >= 'A' && c <= 'Z')
      c -= 'A' - 10;
    else if (c >= 'a' && c <= 'z')
      c -= 'a' - 10;
    else
      break;
    if (c >= base)
      break;
    if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) {
      any = -1;
    } else {
      any = 1;
      acc *= base;
      acc += c;
    }
  }
  if (any < 0) {
    acc = neg ? LONG_MIN : LONG_MAX;
  } else if (neg)
    acc = -acc;

  /* if end ptr non-NULL, store ptr to the character past the last character interpreted */
  if (ptr) {
    *ptr = (char *)s-1;
  }
  return (acc);
}


long
atol (const char *s)
{
  return strtol (s, NULL, 10);
}

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


char *
__utoa (unsigned value,
        char *str,
        int base)
{
  const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
  int i, j;
  unsigned remainder;
  char c;
  
  /* Check base is supported. */
  if ((base < 2) || (base > 36))
    { 
      str[0] = '\0';
      return NULL;
    }  
    
  /* Convert to string. Digits are in reverse order.  */
  i = 0;
  do 
    {
      remainder = value % base;
      str[i++] = digits[remainder];
      value = value / base;
    } while (value != 0);  
  str[i] = '\0'; 
  
  /* Reverse string.  */
  for (j = 0, i--; j < i; j++, i--)
    {
      c = str[j];
      str[j] = str[i];
      str[i] = c; 
    }       
  
  return str;
}

char *  
utoa (unsigned value,
        char *str,
        int base)
{
  return __utoa (value, str, base);
}


char *
__itoa (int value,
        char *str,
        int base)
{
  unsigned uvalue;
  int i = 0;
  
  /* Check base is supported. */
  if ((base < 2) || (base > 36))
    { 
      str[0] = '\0';
      return NULL;
    }  
    
  /* Negative numbers are only supported for decimal.
   * Cast to unsigned to avoid overflow for maximum negative value.  */ 
  if ((base == 10) && (value < 0))
    {              
      str[i++] = '-';
      uvalue = (unsigned)-value;
    }
  else
    uvalue = (unsigned)value;
  
  __utoa (uvalue, &str[i], base);
  return str;
}

char *  
itoa (int value,
        char *str,
        int base)
{
  return __itoa (value, str, base);
}
