/* $Id: bzr.c 1322 2006-11-28 09:44:43Z olau $
 *
 * Copyright (c) 2006 Oliver Lau <ola@ctmagazin.de>
 * Copyright (c) 2006 Heise Zeitschriften Verlag
 * Alle Rechte vorbehalten. All rights reserved.
 *
 */

#include <stdlib.h>
#include "globaldefs.h"
#include "bzr.h"

/** Eine Iteration der BZR durchfuehren. (Vgl. A.K. Dewdney, Wellen
 * aus der Computer-Retorte, Spektrum der Wissenschaft, Sonderheft 8:
 * Computer-Kurzweil III, 1989)
 */
void BZR_iterate(int *cell, int *cell_new,
                 int width, int height,
                 int k1, int k2, int g, int n) {
    int x, y, xx, yy;
    int c, S, excited, active;
    int v;
    int c_new;
    for (y = 0; y < height; ++y) {
        for (x = 0; x < width; ++x) {
            c = cell[x + y * (width+2)];
            S = c;
            excited = 0;
            active = 0;
            for (yy = -1; yy <= 1; ++yy) {
                for (xx = -1; xx <= 1; ++xx) {
                    v = cell[(x + xx) + (y + yy) * (width+2)];
                    S += v;
                    if (v == n)
                        ++active;
                    else if (v != 0)
                        ++excited;
                }
            }

            if (c == 0)
                c_new = excited / k1 + active / k2;
            else if (c == n)
                c_new = 0;
            else 
                c_new = S / (excited + active + 1) + g;

            if (c_new > n)
                c_new = n;

            cell_new[x + y * (width+2)] = c_new;
        }
    }
}
