#include "utils.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

float vec_dist(VecData x, VecData y) {
    float sum = 0.0;
    for (int i = 0; i < 128; i++) {
        float diff = x.vector[i] - y.vector[i];
        sum += diff * diff;
    }
    return sqrt(sum);
}

VecData* fvecs_read(const char* filename, int* bounds) {
    FILE* fid = fopen(filename, "rb");
    if (fid == NULL) {
        fprintf(stderr, "I/O error : Unable to open the file %s\n", filename);
        exit(EXIT_FAILURE);
    }

    int d; 
    fread(&d, sizeof(int), 1, fid);


    fseek(fid, 0, SEEK_END);
    long file_size = ftell(fid);
    fseek(fid, 0, SEEK_SET);
    long vec_size = (long) d * sizeof(float);
    long vec_count = (file_size - sizeof(int)) / vec_size;

    int a = 1;
    int bmax = vec_count;
    int b = bmax;

    if (bounds != NULL) {
        if (bounds[1] == 1) {
            b = bounds[0];
        } else if (bounds[1] == 2) {
            a = bounds[0];
            b = bounds[1];
        }
    }

    if (a < 1 || b > bmax || b < a) {
        VecData* v = NULL;
        fclose(fid);
        return v;
    }

    int n = b - a + 1;
    fseek(fid, (a - 1) * vec_size, SEEK_SET);

    
    // Read n vectors
    VecData* v = malloc(n * sizeof(VecData));
    for (int i = 0; i < n; i++) {
        VecData vec;
        vec.id = i + a;
        vec.vector = malloc(d * sizeof(float));
        fread(vec.vector, sizeof(float), d, fid);
        v[i] = vec;
    }


    fclose(fid);
    return v;
}