/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>

#include <ncurses.h>

#define MIN_WIDTH 10
#define MAX_WIDTH 30

#define MIN_HEIGHT 10
#define MAX_HEIGHT 30

#define RAW(x, y) (state.cells[y][x])
#define CELL(x, y) RAW(x+1, y+1)

#define MASK_MINE 0x80
#define IS_MINE(x) ((x) & MASK_MINE)
#define SET_MINE(x) ((x) |= MASK_MINE)

#define MASK_FLAG 0x40
#define IS_FLAG(x) ((x) & MASK_FLAG)
#define SET_FLAG(x) ((x) |= MASK_FLAG)
#define CLR_FLAG(x) ((x) &=~MASK_FLAG)
#define TGL_FLAG(x) ((x) ^= MASK_FLAG)

#define MASK_OPEN 0x20
#define IS_OPEN(x) ((x) & MASK_OPEN)
#define SET_OPEN(x) ((x) |= MASK_OPEN)

#define MASK_AROUND 0x0f
#define AROUND(x) ((x) & MASK_AROUND)

typedef struct GAME_STATE {
	int width;
	int height;
	int mines;
	int start;
	int alive;
	int x;
	int y;
	char cells[MAX_HEIGHT + 2][MAX_WIDTH + 2];
} GAME_STATE, *PGAME_STATE;

GAME_STATE state = { 9, 9, 10 };

int cheat_seq[] = {
		KEY_UP,
		KEY_UP,
		KEY_DOWN,
		KEY_DOWN,
		KEY_LEFT,
		KEY_RIGHT,
		KEY_LEFT,
		KEY_RIGHT,
		'b',
		'a',
		'\n'
};

#define CHEAT_COUNT (sizeof(cheat_seq)/sizeof(cheat_seq[0]))

int cheat = 0;

void print_usage(char *cmd) {
	fprintf(stderr,
			"Usage: %s [-s SKILL] [-W WIDTH] [-H HEIGHT] [-M MINES] [-h]\n\
\n\
    -s SKILL    Select a preset dimension and mine count. One of:\n\
                    Beginner:     9x9 with 10 mines. (default)\n\
                    Intermediate: 16x16 with 40 mines.\n\
                    Advanced:     30x16 with 99 mines.\n\
    -W WIDTH    Set the width of the game board.\n\
                Must be between 8 and 30\n\
    -H HEIGHT   Set the height of the game board.\n\
                Must be between 8 and 24\n\
    -M MINES    Set the number of mines.\n\
                Must be between 10 and (WIDTH-1)*(HEIGHT-1)\n\
                Set the WIDTH and HEIGHT first\n\
    -h          Print this help\n\
\n\
Gameplay:\n\
\n\
It's a fairly standard game of minesweeper, except the timer is not displayed\n\
until you win. Refer to other resources for the rules. Here's an example board:\n\
\n\
+                           +---+---+\n\
                          1 | : | : |\n\
                            +---+---+\n\
          1   2   2   1   1 | : | : |\n\
            +---+   +---+---+---+---+\n\
          1 | # |[*]| : | : | : | : |\n\
            +---+---+---+---+---+---+\n\
  1   2   2 | : | : | : | : | : | : |\n\
+---+---+---+---+---+---+---+---+---+\n\
| : | : | : | : | : | : | : | : | : |\n\
+---+---+---+---+---+---+---+---+---+\n\
| : | : | : | : | : | : | : | : | : |\n\
+---+---+---+---+---+---+---+---+---+\n\
| : | : | : | : | : | : | : | : | : |\n\
+---+---+---+---+---+---+---+---+---+\n\
| : | : | : | : | : | : | : | : | : |\n\
+---+---+---+---+---+---+---+---+---+\n\
| : | : | : | : | : | : | : | : | : |\n\
+---+---+---+---+---+---+---+---+---+\n\
\n\
Concealed cells are indicated by a colon (:).\n\
Flagged cells are indicated by a hash (#).\n\
Mines are indicated by an asterisk (*).\n\
Empty cells are indicated by empty space. These have no mines around them.\n\
Non-empty open cells are indicated by the number of surrounding mines.\n\
The cursor is indicated by brackets [ ] around the cell's contents.\n\
\n\
ARROW KEYS: Navigate the cursor around the board.\n\
SPACE:      Clear a concealed cell, or\n\
            Clear all cells surrounding an open cell. This is only allowed when\n\
              the number of flagged cells surrounding the cursor matches the\n\
              number of surrounding mines indicated by the cell's contents.\n\
F:          Flag a cell believed to conceal a mine, or\n\
            Unflag a cell no longer believed to conceal a mine. A flagged cell\n\
              cannot be cleared.\n\
SHIFT+R:    Start a new game.\n\
CTRL+C:     Quit.\n\
",
			cmd);
}

void timer_func() {
}

#define ARGS_ERR() do { \
	fprintf(stderr, "Invalid argument: %s\n", argv[i]); \
	print_usage(argv[0]); \
	exit(-1); \
} while (0)

#define REQ_ARG(name) do { \
	i++; \
	if (i >= argc) { \
		fprintf(stderr, "Missing argument: %s\n", name); \
		print_usage(argv[0]); \
		exit(-1); \
	} \
} while (0)

void parse_skill(char *arg) {
	if (strcmp("Beginner", arg) == 0) {
		state.width = 9;
		state.height = 9;
		state.mines = 10;
	}
	else if (strcmp("Intermediate", arg) == 0) {
		state.width = 16;
		state.height = 16;
		state.mines = 40;
	}
	else if (strcmp("Advanced", arg) == 0) {
		state.width = 30;
		state.height = 16;
		state.mines = 99;
	}
	else {
		fprintf(stderr, "Invalid SKILL: %s\n", arg);
		exit(-1);
	}
}

unsigned long parse_int(char *a, char *name,
		unsigned long min, unsigned long max) {
	char *e;
	unsigned long val = strtoul(a, &e, 10);
	if (*e != 0 || val < min || max < val) {
		fprintf(stderr, "Invalid %s: %s. Must be an integer between %ld and %ld.\n",
				name, a, min, max);
		exit(-1);
	}
	return val;
}

void parse_width(char *arg) {
	state.width = parse_int(arg, "WIDTH", 8, 30);
}

void parse_height(char *arg) {
	state.height = parse_int(arg, "HEIGHT", 8, 24);
}

void parse_mines(char *arg) {
	state.mines = parse_int(arg, "MINES", 10, (state.width - 1) * (state.height - 1));
}

void parse_args(int argc, char **argv) {
	if (argc == 0) {
		print_usage("?????");
		exit(-1);
	}
	for (int i = 1; i < argc; i++) {
		if (strnlen(argv[i], 3) != 2 || argv[i][0] != '-') {
			ARGS_ERR();
		}
		switch (argv[i][1]) {
			case 's':
				REQ_ARG("SKILL");
				parse_skill(argv[i]);
				break;
			case 'W':
				REQ_ARG("WIDTH");
				parse_width(argv[i]);
				break;
			case 'H':
				REQ_ARG("HEIGHT");
				parse_height(argv[i]);
				break;
			case 'M':
				REQ_ARG("MINES");
				parse_mines(argv[i]);
				break;
			case 'h':
				print_usage(argv[0]);
				exit(0);
				break;
			default:
				ARGS_ERR();
		}
	}
}

int rand_rng(int n) {
	return rand() % n;
}

int count_around(int X, int Y) {
	int count = 0;
	for (int y = Y - 1; y <= Y + 1; y++) {
		for (int x = X - 1; x <= X + 1; x++) {
			if (IS_MINE(RAW(x,y))) {
				count++;
			}
		}
	}
	return count;
}

int count_flags_around(int X, int Y) {
	int count = 0;
	for (int y = Y - 1; y <= Y + 1; y++) {
		for (int x = X - 1; x <= X + 1; x++) {
			if (IS_FLAG(CELL(x,y))) {
				count++;
			}
		}
	}
	return count;
}

void setup_board() {
	memset(state.cells, 0, sizeof(state.cells));
	for (int mines = 0; mines < state.mines;) {
		int x = rand_rng(state.width);
		int y = rand_rng(state.height);
		if (!IS_MINE(CELL(