// melody_validator.c
#include "melody_validator.h"
#include <string.h>
#include <stdlib.h>

void melody_validator_init(melody_validator_t *m, const int *expected,
                           size_t count, int tolerance)
{
    memset(m, 0, sizeof(*m));
    if (count > MELODY_MAX_NOTES) count = MELODY_MAX_NOTES;
    if (tolerance < 0) tolerance = 0;
    m->count = count;
    m->tolerance = tolerance;
    for (size_t i = 0; i < count; i++) m->expected[i] = expected[i];
}

bool melody_validator_feed(melody_validator_t *m, int note)
{
    if (m->count == 0 || m->pos >= m->count) return false;
    if (abs(note - m->expected[m->pos]) <= m->tolerance) {
        m->pos++;
        return m->pos == m->count;
    }
    // out of tolerance: reset, but let this note seed index 0 if it fits
    m->pos = 0;
    if (abs(note - m->expected[0]) <= m->tolerance) m->pos = 1;
    return false;
}
