ERL_NIF_TERM _hh_count_at(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    long value = 0;
    hh_ctx_t* ctx = NULL;

    ErlNifResourceType* ctx_type = get_hh_ctx_type(env);
    if (argc != 1 ||
        ctx_type == NULL ||
        !enif_get_resource(env, argv[0], ctx_type, (void **)&ctx) ||
        !enif_get_int64(env, argv[1], &value))
    {
        return enif_make_badarg(env);
    }
   
    if (ctx != NULL)
    {
        return enif_make_long(env, hdr_count_at_value(ctx->data, value));
    }

    return make_error(env, "bad_hdr_histogram_nif_impl");
}
static char* log_reader_aggregates_into_single_histogram()
{
    const char* file_name = "histogram.log";
    hdr_timespec timestamp;
    hdr_timespec interval;

    hdr_gettime(&timestamp);
    interval.tv_sec = 5;
    interval.tv_nsec = 2000000;

    struct hdr_log_writer writer;
    struct hdr_log_reader reader;
    hdr_log_writer_init(&writer);
    hdr_log_reader_init(&reader);
    int rc = 0;

    FILE* log_file = fopen(file_name, "w+");

    hdr_log_write_header(&writer, log_file, "Test log", &timestamp);
    hdr_log_write(&writer, log_file, &timestamp, &interval, cor_histogram);
    hdr_log_write(&writer, log_file, &timestamp, &interval, raw_histogram);
    fflush(log_file);
    fclose(log_file);

    log_file = fopen(file_name, "r");

    struct hdr_histogram* histogram;
    hdr_alloc(INT64_C(3600) * 1000 * 1000, 3, &histogram);

    rc = hdr_log_read_header(&reader, log_file);
    mu_assert("Failed header read", validate_return_code(rc));
    rc = hdr_log_read(&reader, log_file, &histogram, NULL, NULL);
    mu_assert("Failed corrected read", validate_return_code(rc));
    rc = hdr_log_read(&reader, log_file, &histogram, NULL, NULL);
    mu_assert("Failed raw read", validate_return_code(rc));

    struct hdr_iter iter;
    hdr_iter_recorded_init(&iter, histogram);
    int64_t expected_total_count =
        raw_histogram->total_count + cor_histogram->total_count;

    mu_assert(
        "Total counts incorrect",
        compare_int64(histogram->total_count, expected_total_count));

    while (hdr_iter_next(&iter))
    {
        int64_t count = iter.count;
        int64_t value = iter.value;

        int64_t expected_count =
            hdr_count_at_value(raw_histogram, value) +
            hdr_count_at_value(cor_histogram, value);

        mu_assert("Incorrect count", compare_int64(count, expected_count));
    }

    fclose(log_file);
    remove(file_name);
    free(histogram);

    return 0;
}