#include <SDL.h>
#include <SDL_gfxPrimitives.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>

typedef struct {
    short x, y;
} Point;

void Point_draw(SDL_Surface *screen, Point p, int index) {
    filledCircleRGBA(screen, p.x, p.y, 3, 100+155/9*index, 100-index*10, 100-index*10, 255);
}

Point random_point(void) {
    Point p;
    p.x = rand()%401;
    p.y = rand()%401;
    return p;
}

Point blank_point(void) {
    Point p = {-20, -20};
    return p;
}

void shift(Point *points) {
    int i;
    for(i = 0; i < 9; i++) {
        points[i] = points[i+1];
    }
}

int inside_circle(Point p) {
    return (p.x-200)*(p.x-200)+(p.y-200)*(p.y-200) <= 40000;
}

Uint32 timer(Uint32 ms, void *param) {
    SDL_Event ev;
    ev.type = SDL_USEREVENT;
    SDL_PushEvent(&ev);
    return ms;
}

int main(int argc, char *argv[]) {
    SDL_Event ev;
    SDL_Surface *screen;

    srand(time(0));

    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
    screen=SDL_SetVideoMode(400, 420, 0, SDL_ANYFORMAT);
    if (!screen) {
        fprintf(stderr, "OMG no window\n");
        exit(1);
    }
    SDL_WM_SetCaption("Pi approximator", "Pi approximator");

    unsigned int total = 0;
    unsigned int inside = 0;

    SDL_TimerID id = SDL_AddTimer(1, timer, NULL);

    boxRGBA(screen, 0, 0, 400, 420, 0, 0, 0, 255);

    int i;
    for(i = 0; i < 5; i++) {
        rectangleRGBA(screen, i, i, 400-i, 400-i, 255, 255, 255, 255);
    }
    for(i = 0; i < 3; i++) {
        circleRGBA(screen, 200, 200, 195-i, 255, 255, 255, 255);
    }

    Point points[10];
    for(i = 0; i < 10; i++) {
        points[i] = blank_point();
    }

    double pi;
    char pitext[20];
    char stuff[100];

    while (SDL_WaitEvent(&ev) && ev.type!=SDL_QUIT) {
        shift(points);
        points[9] = random_point();

        if(inside_circle(points[9]))
            inside++;
        total++;

        for(i = 0; i < 5; i++)
            rectangleRGBA(screen, i, i, 400-i, 400-i, 255, 255, 255, 255);
        for(i = 0; i < 3; i++)
            circleRGBA(screen, 200, 200, 195-i, 255, 255, 255, 255);
        for(i = 0; i < 10; i++)
            Point_draw(screen, points[i], i);

        pi = (double)inside/(double)total*4;

        boxRGBA(screen, 0, 401, 400, 420, 0, 0, 0, 255);


        sprintf(pitext, "%.8f", pi);
        stringRGBA(screen, 390-9*8, 407, pitext, 255, 0, 0, 255);

        sprintf(stuff, "%d/%d", inside, total);
        stringRGBA(screen, 4, 407, stuff, 255, 0, 0, 255);

        SDL_Flip(screen);
    }

    SDL_RemoveTimer(id);
    SDL_Quit();

    return 0;
}
