#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "lib.h"

#define NUM_ACCESSES 1000000

void measure_multiple_accesses(void (*addr)(void), size_t num_accesses, size_t* hits, size_t* misses) 
{
    for (size_t i = 0; i < num_accesses; i++) 
    {
        flush((void*) addr);
        misses[i] = time_maccess(addr);

        maccess((void*) addr);
        hits[i] = time_maccess(addr);
    }
}

void find_crossover_point(size_t* hits, size_t* misses, size_t num_accesses)
{
    size_t hit_sum = 0, miss_sum = 0;
    
    for (size_t i = 0; i < num_accesses; i++) 
    {
        hit_sum += hits[i];
        miss_sum += misses[i];
    }

    size_t avg_hit = hit_sum / num_accesses;
    size_t avg_miss = miss_sum / num_accesses;

    printf("Average hit time: %zu\n", avg_hit);
    printf("Average miss time: %zu\n", avg_miss);

    size_t threshold = (avg_hit + avg_miss) / 2;  // Midpoint as threshold
    printf("Midpoint: %zu\n", threshold);
}

int main()
{
    size_t* hits = malloc(NUM_ACCESSES * sizeof(size_t));
    size_t* misses = malloc(NUM_ACCESSES * sizeof(size_t));

    if (!hits || !misses)
    {
        perror("Memory allocation failed");
        return 1;
    }

    // We use the addr. of main for our test, but anything works.
    measure_multiple_accesses((void*) main, NUM_ACCESSES, hits, misses);
    find_crossover_point(hits, misses, NUM_ACCESSES);

    free(hits);
    free(misses);
    return 0;
}