#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, int verif, int verif_2, int j, int k) {

    for (int i = 0; inputs_1[i] != NULL; i++) {
        char **inputs_1_split = str_split(inputs_1[i], '|');
        int number_left = atoi(inputs_1_split[0]);
        int number_right = atoi(inputs_1_split[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;
}

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

	char **inputs_1 = str_split(strdup(argv[1]), '\n');
	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;
        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, verif_2, verif, j, k) == 0 ? 0 : is_good;
            }
        }
        if (is_good)
            count += atoi(inputs_2_comma[strslen(inputs_2_comma) / 2]);
	}

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

	return 0;
}
