#include "_.h"

int strslen(char **strs) {
    int len = 0;
    for (int i = 0; strs[i] != NULL; i++)
        len++;

    return len;
}

int search (char **strs, int i, int j, int up_down, int left_right) {
    char to_find[4] = "XMAS";
    for (int incr = 0; incr < 4; incr++)
        if (strs[i + (up_down * incr)][j + (left_right * incr)] != to_find[incr])
            return 0;

    return 1;
}

int main(int argc, char **argv) {
	
	if (argc != 2)
		return 1;

	char *input = argv[1];
	char **inputs = str_split(strdup(input), '\n');
    int inputslen = strslen(inputs);

    int nbr = 0;
	for (int i = 0; inputs[i] != NULL; i++) {
        for (int j = 0; inputs[i][j] != '\0'; j++) {
            if (i > 2) { // Up
                nbr += search(inputs, i, j, -1, 0);
            
                if (j > 2) // Up Left
                    nbr += search(inputs, i, j, -1, -1);
                if (j < strlen(inputs[i]) - 3) // Up Right
                    nbr += search(inputs, i, j, -1, 1);
            }
            if (j > 2) // Left
                nbr += search(inputs, i, j, 0, -1);
            if (j < strlen(inputs[i]) - 3) // Right
                nbr += search(inputs, i, j, 0, 1);
            if (i < inputslen - 3) { // Down
                nbr += search(inputs, i, j, 1, 0);

                if (j > 2) // Down Left
                    nbr += search(inputs, i, j, 1, -1);
                if (j < strlen(inputs[i]) - 3) // Down Right
                    nbr += search(inputs, i, j, 1, 1);
            }
        }
	}

    printf("nbr: %d\n", nbr);

	return 0;
}
