/*
 *               Copyright (C) 2007, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */


#include <limits.h>

#include "ioslibc.h"


/* TODO: errno is currently not supported */


unsigned long
strtoul(const char *ptr, char **endptr, int base)
{
    int neg = 0, overflow = 0;
    unsigned long int v = 0;
    const char* orig;
    const char* nptr = ptr;

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

    if (*nptr == '-') {
        neg = 1;
        nptr++;
    } else if (*nptr == '+') {
        ++nptr;
    }

    orig = nptr;
    if (base == 16 && nptr[0] == '0') {
        goto skip0x;
    }
    if (base) {
        unsigned int b = base - 2;

        if (b > 34) {
            //errno = EINVAL;
            return 0;
        }
    } else {
        if (*nptr == '0') {
            base = 8;
skip0x:
            if ((nptr[1] == 'x' || nptr[1] == 'X') && isxdigit(nptr[2])) {
                nptr += 2;
                base = 16;
            }
        } else {
            base = 10;
        }
    }

    while (*nptr) {
        unsigned char c = *nptr;

        c = (c >= 'a' ? c - 'a' + 10 : c >= 'A' ? c - 'A' + 10 : c <= '9' ? c - '0' : 0xff);
        if (c >= base) {
            break; /* out of base */
        }

        {
            unsigned long x = (v & 0xff) * base + c;
            unsigned long w = (v >> 8) * base + (x >> 8);

            if (w > (ULONG_MAX >> 8)) {
                overflow = 1;
            }
            v = (w << 8) + (x & 0xff);
        }
        ++nptr;
    }

    if (nptr == orig) {    /* no conversion done */
        nptr = ptr;
        //errno = EINVAL;
        v = 0;
    }
    if (endptr) {
        *endptr = (char *)nptr;
    }
    if (overflow) {
        //errno = ERANGE;
        return ULONG_MAX;
    }

    return (neg ? -v : v);
}
