#include <kalmia.h>
#include <stdint.h>
#include <stdio.h>


void *kai_expand_array(void **array, size_t *count, size_t element_size)
{
	size_t new_count = *count + 1;
	size_t new_size = element_size * new_count;
	/* cast to unsigned char so we can do pointer arithmetic */
	unsigned char *new_array = realloc(*array, new_size);
	if (new_array == NULL) {
		fprintf(stderr, "[kalmia] ERROR: failed to add %ul bytes to %ul-byte array!\n", 
			element_size, element_size * *count);
		return NULL;
	}

	size_t offset = (*count * element_size) / sizeof(unsigned char);
	void *new_element = new_array + offset;

	*array = new_array;
	*count = new_count;
	return new_element;
}


size_t kai_text_to_reals(ka_real_t *dest, const char *str, size_t count)
{
	char *nptr = (char*) str;
	char *end;

	size_t result = count;

	int i;
	for (i=0; i<count; i++) {
		dest[i] = KA_STR_TO_REAL(nptr, &end);
		if (nptr == end) {
			result -= 1;
		}
		nptr = end;
	}

	return result;
}


size_t kai_text_to_longs(long *dest, const char *str, size_t count)
{
	char *nptr = (char*) str;
	char *end;

	size_t result = count;

	int i;
	for (i=0; i<count; i++) {
		dest[i] = strtol(nptr, &end, 10);
		if (nptr == end) {
			result -= 1;
		}
		nptr = end;
	}

	return result;
}


size_t kai_text_to_uints(unsigned int *dest, const char *str, size_t count)
{
	char *nptr = (char*) str;
	char *end;

	size_t result = count;

	int i;
	for (i=0; i<count; i++) {
		dest[i] = strtol(nptr, &end, 10);
		if (nptr == end) {
			result -= 1;
		}
		nptr = end;
	}

	return result;
}


void *kai_alloc(size_t size, const char *purpose)
{
	void *buf = malloc(size);
	if (buf == NULL) {
		fprintf(stderr, "[kalmia] ERROR: failed to allocated %ul-byte buffer for %s\n", size, purpose);
		return NULL;
	}
	return buf;
}