/* Example: struct * dynamic array, zero-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, vtval0_t *v)
{
	if (v->array != NULL) {
		int n;
		printf("%-12s", prefix);
		for(n = 0; n < vtval0_len(v); n++)
			printf(" %s=%.2f", v->array[n].name, v->array[n].val);
		printf("\n");
	}
	else
		printf("%-12s <NULL>\n", prefix);
}

int main()
{
	int n;
	vtval0_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) */
	vtval0_init(&a);
	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 */
		vtval0_append_len(&a, &v, 1);
	}
	dump("append: ", &a);

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

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

	/* Concat two vectors: sort of "s += s2" */
	vtval0_init(&a2);
	vtval0_append_len(&a, carr2, sizeof(carr2)/sizeof(val_t));
	vtval0_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 */
		vtval0_set_ptr(&a, 15, &v);
		dump("set: ", &a);
	}

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

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

	return 0;
}
