#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

/* convert sexagesimal string str AxBxC to double.
 *   x can be anything non-numeric. Any missing A, B or C will be assumed 0.
 *   optional - and + can be anywhere.
 * return 0 if ok, -1 if can't find a thing.
 */
int
f_scansexa (
const char *str0,	/* input string */
double *dp)		/* cracked value, if return 0 */
{
	double a, b, c;
	char str[256];
	char *neg;
	int isneg, r;

	/* copy str0 so we can play with it */
	strncpy (str, str0, sizeof(str)-1);
	str[sizeof(str)-1] = '\0';

	/* note first negative (but not fooled by neg exponent) */
	isneg = 0;
	neg = strchr(str, '-');
	if (neg && (neg == str || (neg[-1] != 'E' && neg[-1] != 'e'))) {
	    *neg = ' ';
	    isneg = 1;
	}

	/* crack up to three components */
	a = b = c = 0.0;
	r = sscanf (str, "%lf%*[^0-9]%lf%*[^0-9]%lf", &a, &b, &c);
	if (r < 1)
	    return (-1);

	/* back to one value, restoring neg */
	*dp = (c/60.0 + b)/60.0 + a;
	if (isneg)
	    *dp *= -1;
	return (0);
}

