#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(11, 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 = 1;
    long lens = strslen(numbers);
    for (; i < lens; i++) {
        char *to_place;
        long j = lens - 1;
        for (;numbers[j][0] == '.'; j--);
        to_place = numbers[j];

        for (long k = 0; k < lens; k++) {
            if (numbers[k][0] == '.') {
                for (int w = 0; w < strlen(numbers[j]); w++)
                    numbers[k][w] = to_place[w];
                break;
            }
        }
        for (int k = 0; numbers[j][k] != '\0'; k++)
            numbers[j][k] = '.';
    }
    //display(numbers);

    return numbers;
}

long cal(char **numbers) {
    long calc = 0;
    int i = 0;
    for (; numbers[i] != NULL && numbers[i][0] != '.'; 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;
}
