/* Example: struct * dynamic array, function-initialized, custom vector type */
/* Part of genvector examples (http://repo.hu/projects/genvector) */
#include <stdio.h>
#include "val.h"

/* print the array with a prefix */
static void dump(const char *prefix, vtvali_t *v)
{
	if (v->array != NULL) {
		int n;
		printf("%-12s", prefix);
		for(n = 0; n < vtvali_len(v); n++)
			printf(" %s=%.2f", v->array[n].name, v->array[n].val);
		printf("\n");
	}
	else
		printf("%-12s <NULL>\n", prefix);
}

/* Initialize new elements if they are not immediately assigned */
void my_init_elem(vtvali_t *arr, val_t *elem)
{
	strcpy(elem->name, "init_elem");
	elem->val = -1.0;
}

int main()
{
	int n;
	vtvali_t a, a2;
	val_t carr[] = {
		{"two",   2.0},
		{"three", 3.0},
		{"four",  4.0}
	};
	val_t carr2[] = {
		{"seven", 7.0},
		{"six",   6.0},
		{"five",  5.0}
	};

	/* Initialize the vector (to empty, which means the array is not allocated) */
	vtvali_init(&a);
	a.init_elem = my_init_elem;
	dump("empty: ", &a);

	/* append 100..109, int by int */
	for(n = 0; n < 10; n++) {
		val_t v;
		strcpy(v.name, "fill");
		v.val = 100+n;
		/* Use append_len() instead of append() to avoid v copied onto the stack */
		vtvali_append_len(&a, &v, 1);
	}
	dump("append: ", &a);

	/* append a static array */
	vtvali_append_len(&a, carr, sizeof(carr)/sizeof(val_t));
	dump("append_len: ", &a);

	/* truncate after 8 elements */
	vtvali_truncate(&a, 8);
	dump("truncate: ", &a);

	/* Concat two vectors: sort of "s += s2" */
	vtvali_init(&a2);
	vtvali_append_len(&a, carr2, sizeof(carr2)/sizeof(val_t));
	vtvali_concat(&a, &a2);
	dump("concat: ", &a);

	/* Array is still just an int * array */
	printf("[3] is:      %s=%.2f\n", a.array[3].name, a.array[3].val);

	/* It can be read or written as an int * array, within bounds */
	strcpy(a.array[5].name, "manual");
	a.array[5].val = 99;
	dump("array asg: ", &a);

	/* Initializing an element beyond current end will create multiple
	   new elements, all initialized using the initialized function */
	{
		val_t v = {"set", 3.14};

		/* NOTE: use set_ptr() over set() so that v doesn't need to be copied onto the stack */
		vtvali_set_ptr(&a, 15, &v);
		dump("set: ", &a);
	}

	/* Remove a mid-section of the array, 3 elements starting from [2] */
	vtvali_remove(&a, 2, 3);
	dump("remove: ", &a);

	/* Free memory */
	vtvali_uninit(&a);
	vtvali_uninit(&a2);

	return 0;
}
