#include "collect.h"
#include <stdio.h>
#include <malloc.h>
#include <string.h>

/* simplistic collection class... */

Collection *newCollection(int max, int delta)
{
	Collection *c;
	int i;
	c = (Collection *) malloc(sizeof(Collection));
	if (!c) return 0;
	memset(c, 0, sizeof(Collection));
	c->ptr = (void **) malloc(max * sizeof(void *));
	if (c->ptr) memset(c->ptr, 0, max*sizeof(void *));
	c->cnt = 0;
	c->allocated = c->ptr ? max : 0;
	c->delta = delta;
	return c;
}

void deleteCollection(Collection *c)
{
	if (!c) return;
	if (c->ptr) free(c->ptr);
	free(c);
}

void expandCollection(Collection *c, int sz)
{
	int i;
	void **p;
	if (c->allocated>sz) return;
	p = (void **) malloc(sz * sizeof(void *));
	if (p) memset(p, 0, sz*sizeof(void *));
	for (i=0;i<c->cnt;i++) p[i] = c->ptr[i];
	free(c->ptr);
	c->ptr = p;
	c->allocated = sz;
}

int addCollectionItem(Collection *c, void *item )
{
	if (!c) return -1;
	if (!item) return -1;
	if (c->allocated<=c->cnt)
		expandCollection(c, c->cnt+c->delta);
	if (c->cnt<c->allocated) {
		c->ptr[c->cnt] = item;
		c->cnt++;
	}
	return c->cnt-1;
}

void setCollectionItem(Collection *c, int index, void *item)
{
	if (!c) return;
	if (index<0) return;
	if (c->allocated<index) {
		expandCollection(c, index+1);
	}
	if (index<c->allocated) {
		c->ptr[index] = item;
		if (c->cnt<=index)
			c->cnt = index+1;
	}
}

void *getCollectionItem(Collection *c, int index )
{
	if (!c) return 0;
	if (index<0||index>=c->cnt) return 0;
	return c->ptr[index];
}

int getCollectionCount(Collection *c)
{
	if (!c) return 0;
	return c->cnt;
}
