/* Example: int * dynamic array, function-initialized (vtii_), standard vector type */
/* Part of genvector examples (http://repo.hu/projects/genvector) */
#include <stdio.h>
#include <genvector/vtii.h>

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

/* Initialize new elements if they are not immediately assigned */
void my_init_elem(vtii_t *arr, int *elem)
{
	*elem = -1;
}

int main()
{
	int n;
	vtii_t a, a2;
	int carr[] = {2, 4, 8, 16};
	int carr2[] = {7, 6, 5, 4};

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

	/* append 100..109, int by int */
	for(n = 0; n < 10; n++)
		vtii_append(&a, 100+n);
	dump("append: ", &a);

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

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

	/* Concat two vectors: sort of "s += s2" */
	vtii_init(&a2);
	vtii_append_len(&a, carr2, sizeof(carr2)/sizeof(int));
	vtii_concat(&a, &a2);
	dump("concat: ", &a);

	/* Array is still just an int * array */
	printf("[3] is:      %d\n", a.array[3]);

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

	/* Initializing an element beyond current end will create multiple
	   new elements, all initialized using the initialized function */
	vtii_set(&a, 15, 77);
	dump("set: ", &a);

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

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

	return 0;
}
