#include <stdlib.h>
#include "image.h"

#define MAX 255   // steps before a point counts as inside the set
#define W 2400    // the picture's width
#define H 1800    // and height

// returns how many steps z = z * z + c takes to leave the circle of radius 2, or MAX
int steps(double cr, double ci) {
    double zr = 0;
    double zi = 0;
    for (int n = 0; n < MAX; n++) {
        if (zr * zr + zi * zi > 4) {
            return n;
        }
        double t = zr * zr - zi * zi + cr;
        zi = 2 * zr * zi + ci;
        zr = t;
    }
    return MAX;
}

// paints the w by h picture px with the set: black inside, gray by speed outside
void mandelbrot(unsigned char * px, int w, int h) {
    for (int y = 0; y < h; y++) {
        unsigned char * p = px + 3 * y * w;
        for (int x = 0; x < w; x++) {
            int n = steps(-2.0 + 3.0 * x / w, -1.2 + 2.4 * y / h);
            int g = n == MAX ? 0 : 255 * n / MAX;
            put_pixel(&p, g, g, g);
        }
    }
}

int main() {
    unsigned char * px = new_image(W, H);
    mandelbrot(px, W, H);
    write_ppm(px, W, H);
    free(px);
}
