/*
 * array.c - Growable baseless 2D array
 *
 * Written 2010 by Werner Almesberger
 * Copyright 2010 by Werner Almesberger
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */


#include <stdlib.h>

#include "util.h"
#include "array.h"


static void resize(struct array *a,
    int nx0, int nx1, int ny0, int ny1)
{
	int ox, oy, nx, ny;
	int n, x, y;
	int *tmp;

	ox = a->max_x-a->min_x;
	oy = a->max_y-a->min_y;
	nx = nx1-nx0;
	ny = ny1-ny0;
	if (ox == nx && oy == ny)
		return;
	n = (nx+1)*(ny+1);
	tmp = alloc_size(n*sizeof(int));
	for (x = 0; x != n; x++)
		tmp[x] = UNDEF;
	for (x = a->min_x; x <= a->max_x; x++)
		for (y = a->min_y; y <= a->max_y; y++)
			tmp[x-nx0+(nx+1)*(y-ny0)] =
			    a->data[x-a->min_x+(ox+1)*(y-a->min_y)];
	free(a->data);
	a->data = tmp;
	a->min_x = nx0;
	a->max_x = nx1;
	a->min_y = ny0;
	a->max_y = ny1;
}


struct array *new_array(void)
{
	struct array *a;

	a = alloc_type(struct array);
	a->data = NULL;
	return a;
}


void free_array(struct array *a)
{
	free(a->data);
	free(a);
}


void set(struct array *a, int x, int y, int z)
{
	if (!a->data) {
		a->min_x = a->max_x = x;
		a->min_y = a->max_y = y;
		a->min_z = a->max_z = z;
		a->data = alloc_type(int);
		*a->data = z;
	} else {
		resize(a, 
		    x < a->min_x ? x : a->min_x, x > a->max_x ? x : a->max_x,
		    y < a->min_y ? y : a->min_y, y > a->max_y ? y : a->max_y);
		if (z < a->min_z)
			a->min_z = z;
		if (z > a->max_z)
			a->max_z = z;
		a->data[x-a->min_x+(a->max_x-a->min_x+1)*(y-a->min_y)] = z;
	}
}