/**
 * \file    stdlib.c
 * \brief   
 * 
 * \par     Copyright (c) 2018 UWE Technologies Corp., Ltd. All Rights Reserved.
 * \author  James
 * \date    2018-04-11
 * \version 
 * 
 * \history 
 *  Date        Note
 *  2018-04-11  Original Creation
 * 
 */

#include "libc.h"

int abs(int i)
{
    return (i < 0) ? -i : i;
}

int strtoi(const char *p)
{
    int n, c, neg;

    neg = 0;
    if (!isdigit((c = *p))) {
        while (isspace(c))
            c = *++p;
        switch (c) {
        case '-':
            neg++;
            c = *++p;
            break;
        case '+':
            c = *++p;
            break;
        }
        if (!isdigit(c))
            return (0);
    }
    for (n = '0' - c; isdigit((c = *++p)); ) {
        n *= 10;        /* two steps to avoid unnecessary overflow */
        n += '0' - c;   /* accum neg to avoid surprises at MAX */
    }
    return (neg ? n : -n);
}

/*
 * Convert a string to an unsigned long integer.
 *
 * Ignores `locale' stuff.  Assumes that the upper and lower case
 * alphabets and digits are each contiguous.
 */
unsigned long strtoul(const char *s, char **end, int base)
{
    unsigned int n, neg;
    
    if (base == 0)
        base = 10;

    if (s == 0) {
        if (end != 0) {
            end = 0;
        }
        return 0;
    }

    s += (neg = (*s == '-'));

    if (*s == '0') {
        s++;
        if (*s == 'x' || *s == 'X') {
            base = 16;
            s++;
        } else if (*s == 'b' || *s == 'B') {
            base = 2;
            s++;
        } else {
            base = 8;
        }
    }

    for (n = 0; ((*s >= 'a' && *s < (char)('a' + base - 10)) ||
        (*s >= 'A' && *s < (char)('A' + base - 10)) ||
        (*s >= '0' && *s <= '9')); s++) {
        n = n * base + ((*s <= '9' ? *s : *s + 9) & 15);
    }

    if (end != 0) {
        *end = (char *) s;
    }

    return (neg ? -n : n);
}

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

static unsigned long int next = 1;

void srand(unsigned int seed)
{
    next = seed;
}

#define RAND_MAX 32767

int rand(void)    /* RAND_MAX assumed to be 32767*/
{
    next = next * 1103515245 + 12345;
    return (unsigned int) (next >> 16) & RAND_MAX;  /* equal to (next / 65536) % 32768*/
}

unsigned int round_u32(double x)
{
    return (((unsigned int)((x)+0.5) > (unsigned int)(x)) ? ((x)+1) : (x));
}

double ln(double a)
{
	int N = 15; //我们取了前15+1项来估算
	int k,nk;
	double x,xx,y;
	x = (a-1)/(a+1);
	xx = x*x;
	nk = 2*N+1;
	y = 1.0/nk;
	for ( k = N; k > 0; k-- )
	{
		nk = nk - 2;
		y = 1.0/nk+xx*y;
	}
	return 2.0*x*y;
}


