#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include <vector>

using namespace std;

vector<vector<bool> > current_grid, next_grid;
int total_steps = 100;
int rows, columns;

int count_neighbours(int i_global, int j_global)
{
    int i, j;
    int count = 0;
    for (int i_local = -1; i_local <= 1; i_local++)
        for (int j_local = -1; j_local <= 1; j_local++)
            if (i_local != 0 || j_local != 0)
            {
                i = (i_local + i_global + rows) % rows;
                j = (j_local + j_global + columns) % columns;
                if (current_grid[i][j]) count++;
            }
    return count;
}

void write_grid_to_file(int step)
{
    stringstream file_name;
    fstream file;
    file_name << "output" << "_" << step << ".dat";
    file.open(file_name.str().c_str(), ios_base::out);
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
            file << current_grid[i][j] << "\t";
        file << endl;
    }
    file.close();
}

void perform_iteration()
{
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++)
        {
            next_grid[i][j] = current_grid[i][j];
            int neighbour_count = count_neighbours(i, j);
            if (current_grid[i][j])
            {
                if (neighbour_count != 2 && neighbour_count != 3)
                    next_grid[i][j] = false;
            }
            else if (neighbour_count == 3) next_grid[i][j] = true;
        }
    current_grid.swap(next_grid);
}

int main(int argc, char *argv[])
{
    srand(time(NULL));
    rows = 100;
    columns = 100;
    current_grid.resize(rows, vector<bool>(columns));
    next_grid.resize(rows, vector<bool>(columns));

    // Grid initialization
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++) current_grid[i][j] = (rand() % 2);

    for (int n = 0; n < total_steps; n++)
    {
        cout << "Step: " << n << endl;
        perform_iteration();
        write_grid_to_file(n);
    }

    return 0;
}
