#include "_.h"

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

int is_first(char ***inputs_1_split, int verif, int verif_2, int j, int k) {

    for (int i = 0; inputs_1_split[i] != NULL; i++) {
        int number_left = atoi(inputs_1_split[i][0]);
        int number_right = atoi(inputs_1_split[i][1]);

        if (number_left != verif && number_right != verif)
            continue;
        if (number_left != verif_2 && number_right != verif_2)
            continue;

        if (j > k) {
            if (number_left == verif)
                continue;
            else
                return 0;
        }
        else {
            if (number_right == verif)
                continue;
            else
                return 0;
        }
    }

    return 1;
}

void swap(char **str_1, char **str_2) {
    char *tmp = *str_1;
    *str_1 = *str_2;
    *str_2 = tmp;
}

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

	char **inputs_1 = str_split(strdup(argv[1]), '\n');
    char ***inputs_1_split = calloc(strslen(inputs_1) + 1, sizeof(char**));
    for (int i = 0; inputs_1[i] != NULL; i++)
        inputs_1_split[i] = str_split(inputs_1[i], '|');
    char **inputs_2 = str_split(strdup(argv[2]), '\n');

    int count = 0;
	for (int i = 0; inputs_2[i] != NULL; i++) {
        char **inputs_2_comma = str_split(inputs_2[i], ',');
        int is_good = 1;
        int is_good_final = 1;
        for (int j = 0; inputs_2_comma[j] != NULL; j++) {
            int verif = atoi(inputs_2_comma[j]);
            for (int k = 0; inputs_2_comma[k] != NULL; k++) {
                int verif_2 = atoi(inputs_2_comma[k]);
                if (k != j)
                    is_good = is_first(inputs_1_split, verif_2, verif, j, k);
                is_good_final = is_good == 0 ? 0 : is_good_final;
                if (!is_good) {
                    swap(&inputs_2_comma[j], &inputs_2_comma[k]);
                    j = 0;
                    break;
                }
            }
        }
        if (!is_good_final) {
            count += atoi(inputs_2_comma[strslen(inputs_2_comma) / 2]);
        }
	}

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

	return 0;
}
