#include <Rinternals.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

/* given a filename, compute the occurance count of letters a-z */

static int update_freq(const char *file, int *freq_data)
{
    FILE *fh = fopen(file, "r");
    int c, res;
    while (EOF != (c = getc(fh))) {
        int i = tolower(c) - 'a';
        if (i > -1 && i < 26) freq_data[i] += 1;
    }
    res = ferror(fh);
    fclose(fh);
    return res;
}

SEXP nid_alpha_freq(SEXP fname)
{
    SEXP ans = Rf_allocVector(INTSXP, 26);
    const char *file = CHAR(STRING_ELT(fname, 0));
    int *freq_data;

    PROTECT(ans);

    freq_data = INTEGER(ans);
    memset(freq_data, 0, sizeof(int) * 26);
    update_freq(file, freq_data);

    UNPROTECT(1);
    return ans;
}
