#include "_.h"

void display(char **numbers) {
    for (int i = 0; numbers[i] != NULL; i++) {
        for (int j = 0; numbers[i][j] != '\0'; j++)
            printf("%c", numbers[i][j]);
        printf(" ");
    }
    printf("\n");
}

char **first_line(char *input) {

    char **numbers = calloc(pow(strlen(input), 2) + 1, sizeof(char*));
    int count = 0;
    int id = 0;
	for (int i = 0; input[i] != '\0'; i++) {
        int nbr = atoi(strndup(&input[i], 1));
        char *add = calloc(255, 1);
        add[0] = '.';
        if (i % 2 == 0)
            sprintf(add, "%d", id++);

        for (int j = 0; j < nbr; j++)
            numbers[count++] = strdup(add); 
	}

    //display(numbers);

    return numbers;
}

char **finish(char **numbers) {
    long i = 0;
    long lens = strslen(numbers);
    for (; i < lens - 1;) {
        char *to_place[10] = { [0 ... 9] = NULL };
        long j = lens - 1 - i;
        for (;numbers[j][0] == '.' && j > 0; j--);
        i = lens - j - 1;
        int w = 0;
        for (; j - w > 0 && strcmp(numbers[j], numbers[j - w]) == 0; w++) {
            to_place[w] = numbers[j - w];
        }

        int placed = 0;
        for (long k = 0; k < lens && k < j; k++) {
            if (numbers[k][0] == '.') {
                int y = 0;
                for (; numbers[k + y] != NULL && numbers[k + y][0] == '.'; y++);
                if (y < w)
                    continue;
                placed = 1;
                for (int v = 0; to_place[v] != NULL; v++) {
                    for (int x = 0; to_place[v][x] != '\0'; x++) {
                        numbers[k + v][x] = to_place[v][x];
                    }
                }
                break;
            }
        }
        if (placed)
            for (int k = 0; to_place[k] != NULL; k++)
                for (int l = 0; to_place[k][l] != '\0'; l++)
                    to_place[k][l] = '.';
        i += strslen(to_place);
    }
    //display(numbers);

    return numbers;
}

long cal(char **numbers) {
    long calc = 0;
    int i = 0;
    for (; numbers[i] != NULL; i++)
        calc += i * atol(numbers[i]);
    return calc;
}

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

	char *input = argv[1];
    char **numbers = first_line(input);
    long result = cal(finish(numbers));
    //display(numbers);

    printf("result: %ld\n", result);
	return 0;
}
