#include "_.h"
#include <pthread.h>

typedef struct pair {
    long nbr;
    long max;
} pair_t;

typedef struct stones {
    pair_t pair;
    long key;
} stones_t;

stones_t **stones;

int index_stones(pair_t pair) {
    for (int i = 0; stones[i] != NULL; i++)
        if (stones[i]->pair.max == pair.max &&
            stones[i]->pair.nbr == pair.nbr)
            return i;
    return -1;
}

void insert_stones(pair_t pair, long v) {
    int i = 0;
    for (; stones[i] != NULL; i++);
    stones[i] = calloc(1, sizeof(stones_t));
    stones[i]->pair = pair;
    stones[i]->key = v;
}

long blink(long nbr, int max) {
    pair_t pair = {nbr, max}; 
    int i = index_stones(pair);
    if (i != -1)
        return stones[i]->key;
    long v = 1;
    for (; max > 0; max--) {
        if (nbr == 0) {
            nbr = 1;
            continue;
        }
        else if (((int)floor(log10(ABS(nbr))) + 1) % 2 == 0) {
            double len = floor(log10(ABS(nbr))) + 1;
            int left = nbr / (pow(10, len / 2)); 
            v += blink(left, max - 1);

            nbr = nbr % (long)(pow(10, len / 2)); 

            continue;
        }
        else 
            nbr *= 2024;
    }
    insert_stones(pair, v);
    return v;
}


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

	char *input = argv[1];
	char **inputs = str_split(strdup(input), ' ');


    long nbrs[1000] = { [0 ... 999] = -1};
	for (int i = 0; inputs[i] != NULL; i++) {
        nbrs[i] = atol(inputs[i]);
    }

    stones = calloc(100000, sizeof(stones_t*));
    long count = 0;
    for (long i = 0; nbrs[i] != -1; i++)
        count += blink(nbrs[i], 75);

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

	return 0;
}
