// Implementación con un arreglo que crece: guarda todos los valores.
#include "tally.h"

#include <assert.h>
#include <stdlib.h>

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

Tally *tally_new(void) {
    Tally *tally = malloc(sizeof *tally);
    if (tally == NULL) {
        return NULL;
    }
    tally->values = NULL;
    tally->count = 0;
    tally->capacity = 0;
    return tally;
}

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

int tally_add(Tally *tally, int value) {
    if (tally->count == tally->capacity) {
        int capacity = tally->capacity == 0 ? 4 : 2 * tally->capacity;
        int *values = realloc(tally->values, capacity * sizeof *values);
        if (values == NULL) {
            return 0;
        }
        tally->values = values;
        tally->capacity = capacity;
    }
    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) {
    assert(tally->count > 0);
    int largest = tally->values[0];
    for (int i = 1; i < tally->count; i++) {
        if (tally->values[i] > largest) {
            largest = tally->values[i];
        }
    }
    return largest;
}
