/*
 *  This file is part of ixemul.library for the Amiga.
 *  Copyright (C) 1991, 1992  Markus M. Wild
 *  Portions Copyright (C) 1994 Rafael W. Luebbert
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

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

double
strtod (const char *s, char **ptr)
{
	double ret = 0.0;
	const char *start = s;
	const char *begin = NULL;
	int success = 0;

	/* optional white space */
	while (isspace(*s))
		s++;

	/* optional sign */
	if (*s == '+' || *s == '-') {
		s++;
		if (*(s-1) == '-')
			begin = s - 1;
		else
			begin = s;
	}

	/* string of digits with optional decimal point */
	if (isdigit(*s) && ! begin)
		begin = s;

	while (isdigit(*s)) {
		s++;
		success++;
	}

	if (*s == '.') {
		if (! begin)
			begin = s;
		s++;
		while (isdigit(*s))
			s++;
		success++;
	}

	if (s == start || success == 0)		/* nothing there */
		goto out;

	/*
 	 *	optional 'e' or 'E'
	 *		followed by optional sign or space
	 *		followed by an integer
	 */

	if (*s == 'e' || *s == 'E') {
		s++;

		/* XXX - atof probably doesn't allow spaces here */
		while (isspace(*s))
			s++;

		if (*s == '+' || *s == '-')
			s++;

		while (isdigit(*s))
			s++;
	}

	/* go for it */
	ret = atof(begin);

out:
	if (! success)
		s = start;	/* in case all we did was skip whitespace */

	if (ptr)
		*ptr = (char *)s;

	return ret;
}

