// Tally que guarda todos los valores, en un arreglo que crece.
#include "tally.h"

#include <stdlib.h>

#define FIRST_CAPACITY 4

struct tally {
    int *values;
    int count;
    int capacity;
};

Tally *tally_new(void) {
    Tally *tally = malloc(sizeof(*tally));
    if (tally == NULL) {
        return NULL;
    }

    tally->values = malloc(FIRST_CAPACITY * sizeof(int));
    if (tally->values == NULL) {
        free(tally);
        return NULL;
    }
    tally->count = 0;
    tally->capacity = FIRST_CAPACITY;
    return tally;
}

void tally_free(Tally *tally) {
    if (tally != NULL) {
        free(tally->values);
        free(tally);
    }
}

int tally_add(Tally *tally, int value) {
    if (tally->count == tally->capacity) {
        int *grown = realloc(tally->values, 2 * tally->capacity * sizeof(int));
        if (grown == NULL) {
            return 0;
        }
        tally->values = grown;
        tally->capacity *= 2;
    }
    tally->values[tally->count] = value;
    tally->count++;
    return 1;
}

int tally_count(const Tally *tally) {
    return tally->count;
}

int tally_sum(const Tally *tally) {
    int sum = 0;
    for (int i = 0; i < tally->count; i++) {
        sum += tally->values[i];
    }
    return sum;
}

int tally_max(const Tally *tally) {
    int max = tally->values[0];
    for (int i = 1; i < tally->count; i++) {
        if (tally->values[i] > max) {
            max = tally->values[i];
        }
    }
    return max;
}
