/* readcat.c -- utility functions for reading astronomical catalog data */
/*
Copyright 2000, Steve VanDevender <stevev@hexadecimal.uoregon.edu>
Permission is granted to redistribute source code for this program if
and only if all of the following conditions are met:

1.  This copyright notice must not be removed or modified.
2.  Any changes you make to this source code must be documented.
3.  Binary versions must be distributed with complete source code.
4.  No money will be charged for distribution of binaries or source code.
*/

#include "readcat.h"
#include <stdlib.h>
#include <string.h>

/* these functions are utilities to extract data from ASCII-format
   astronomical catalog lines.  The standard catalog descriptions use
   1-based indexes for the character positions in lines, so these
   functions do too. */

static int min(int a, int b)
{
	return a < b ? a : b;
}

/* extract the character in s at pos (1-based) and place in d. */
void get_char(char *s, int pos, char *d)
{
	if (pos < strlen(s)) *d = s[pos - 1];
	else *d = '\0';
}

/* extract a string from s between start and end indexes (1-based),
   and place in d.  Leading and trailing spaces are removed. */
void get_string(char *s, int start, int end, char *d)
{
	int l = 0;

	/* change from 1-origin to 0-origin */
	start--; end--;
	end = min(end, strlen(s) - 1);
	if (start <= end) {
		/* skip leading spaces */
		while (s[start] == ' ' && start <= end) start++;
		/* copy to end of string or field */
		while (s[start] && start <= end) d[l++] = s[start++];
		/* back over trailing spaces */
		while (l > 0 && d[l] == ' ') l--;
	}
	/* put terminating nul on destination string */
	d[l] = '\0';
}

/* try to parse a signed integer value in s located between start and
   end (1-based) and place its value in n.  If the field is blank, or
   start is past the end of s, place BAD_INT in n. */
void get_integer(char *s, int start, int end, long *n)
{
	char buf[20];
	int l;
	char *endptr;

	*n = BAD_INT;
	start--; end--;
	end = min(end, strlen(s) - 1);
	if (start > end) return;
	l = min(end - start + 1, sizeof(buf) - 1);
	strncpy(buf, s + start, l);
	buf[l] = '\0';
	*n = strtol(buf, &endptr, 10);
	if (endptr == buf) *n = BAD_INT;
}

/* try to parse a floating-point (C double) value in s located between
   start and end (1-based) and place its value in d.  If the field is
   blank or start is past the end of s, place BAD_DOUBLE in n. */
void get_fp(char *s, int start, int end, double *d)
{
	char buf[20];
	int l;
	char *endptr;

	*d = BAD_DOUBLE;
	start--; end--;
	end = min(end, strlen(s) - 1);
	if (start > end) return;
	l = min(end - start + 1, sizeof(buf) - 1);
	strncpy(buf, s + start, l);
	buf[l] = '\0';
	*d = strtod(buf, &endptr);
	if (endptr == buf) *d = BAD_DOUBLE;
}
