#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
#include "libp.h"

long double __xstrtod(const char *s, char **endptr, int count)
{
	int sign = 0;
	long double frac = 0;
	long double val = 0;
	int exp=0;

	while( isspace(*s)) s++;
	if (*s == '-') {
		sign++;
		s++;
	  if (!--count)
	  	return val;
	}
	else if (*s == '+') {
		s++;

		if (!--count)
			return val;
	}

	if (*s == '.') {
		frac = .1;
		s++;                    
		if (!--count)
			return val;
	}
	if (!frac) {
		while(isdigit(*s)) {
			val*= 10;
			val += (*s++-'0');
			if (!--count)
				return val;
		}
		if (*s == '.') {
			frac = .1;
			s++;
			if (!--count)
				return val;
		}
	}
	if (frac)
		while (isdigit(*s)) {
			val += (*s++-'0')*frac;
			frac /=10;
			if (!--count)
				return val;
		}
	if (sign)
		val = - val;
	sign = 0;
	if (*s == 'e' || *s == 'E' || *s == 'd' || *s == 'E') {
		sign = 0;
		s++;
		if (*s == '-') {
			sign++;
			s++;
			if (!--count)
				return val;
		}
		else if (*s == '+') {
			s++;
	  	if (!--count)
	  		return val;
		}
		while(isdigit(*s)) {
			exp*= 10;
			exp += (*s++-'0');
	  	if (!--count)
	  		return val;
		}
		if (exp > 5200)
			exp = 5200;
		if (sign)
			val = val / _fpow(exp);
		else
			val = val * _fpow(exp);
	}
	if (endptr)
		*endptr = s;
	return val;
}
double strtod(const char *string, char **endptr)
{
	return((double)__xstrtod(string,endptr,256));
}
double atof(const char *string)
{
	return((double)__xstrtod(string,0,256));
}
long double _atold(const char *string)
{
	return(__xstrtod(string,0,256));
}