// jo_sift.h - Single file SIFT implementation
// Public Domain. No warranty implied; use at your own risk
//
// To use this library, do this in *one* C/C++ file:
//     #define JO_SIFT_IMPLEMENTATION
//     #include "jo_sift.h"
// 
// You can then call the functions as normal.
//
// Version history:
//    0.1   - Initial release (1/28/2025)
//
// Basic usage:
//    // Create or load images using your preferred method
//    jo_sift_image img1 = {width, height, your_float_data};
//    jo_sift_image img2 = {width, height, your_float_data};
//    
//    // Detect keypoints and compute descriptors
//    int n_keys1;
//    jo_sift_keypoint* keys1 = jo_sift_detect(&img1, &n_keys1);
//    
//    int n_keys2;
//    jo_sift_keypoint* keys2 = jo_sift_detect(&img2, &n_keys2);
//    
//    // Match keypoints
//    int n_matches;
//    jo_sift_match* matches = jo_sift_match_keypoints(keys1, n_keys1, 
//                                                    keys2, n_keys2, &n_matches);
//    
//    // Cleanup
//    free(matches);
//    free(keys1);
//    free(keys2);

//#define JO_SIFT_IMPLEMENTATION
//#define JO_SIFT_TEST

#ifndef JO_SIFT_H
#define JO_SIFT_H

#ifdef __cplusplus
extern "C" {
#endif

// Core data structures
typedef struct {
    int width;
    int height;
    float* data;  // row-major: data[y*width + x], values should be in [0,1] range
} jo_sift_image;

typedef struct {
    float x;          // sub-pixel position in octave space
    float y;
    float real_x;     // position in original image space
    float real_y;
    int octave;
    int layer;
    float sigma;      // scale
    float orientation;// in radians
    float descriptor[128];
} jo_sift_keypoint;

typedef struct {
    int query_idx;
    int train_idx;
    float distance;
} jo_sift_match;

// Core API functions
jo_sift_keypoint* jo_sift_detect(const jo_sift_image* img, int* num_keypoints);
jo_sift_match* jo_sift_match_keypoints(const jo_sift_keypoint* keys1, int n_keys1,
                                      const jo_sift_keypoint* keys2, int n_keys2,
                                      int* num_matches);

#ifdef __cplusplus
}
#endif

#endif // JO_SIFT_H

#ifdef JO_SIFT_IMPLEMENTATION

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

// Constants and Macros
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

#define ORI_HIST_BINS 36
#define DESC_NUM_BINS 8
#define DESC_WIDTH 4
#define DESC_HIST_LEN (DESC_NUM_BINS * DESC_WIDTH * DESC_WIDTH)

#define CONTRAST_THRESHOLD 0.03f
#define EDGE_THRESHOLD 10.0f
#define ORI_PEAK_RATIO 0.8f
#define MATCH_RATIO_THRESHOLD 0.75f

// -----------------------------------------------------------------------------
// Utility Functions
// -----------------------------------------------------------------------------

static jo_sift_image* allocate_image(int width, int height) {
    jo_sift_image* img = (jo_sift_image*)malloc(sizeof(jo_sift_image));
    img->width = width;
    img->height = height;
    img->data = (float*)calloc(width * height, sizeof(float));
    return img;
}

static void free_image(jo_sift_image* img) {
    if (!img) return;
    free(img->data);
    free(img);
}

// -----------------------------------------------------------------------------
// Gaussian Blur
// -----------------------------------------------------------------------------

static jo_sift_image* gaussian_blur(const jo_sift_image* input, float sigma) {
    int kernel_size = (int)(6 * sigma + 1.0f);
    if (kernel_size % 2 == 0) kernel_size++;
    
    float* kernel = (float*)malloc(kernel_size * sizeof(float));
    float sum = 0.0f;
    int half = kernel_size / 2;
    for (int i = 0; i < kernel_size; i++) {
        int x = i - half;
        float v = expf(-(x * x) / (2.0f * sigma * sigma));
        kernel[i] = v;
        sum += v;
    }
    for (int i = 0; i < kernel_size; i++) {
        kernel[i] /= sum;
    }

    jo_sift_image* temp = allocate_image(input->width, input->height);
    jo_sift_image* blurred = allocate_image(input->width, input->height);

    // Horizontal pass
    for (int y = 0; y < input->height; y++) {
        for (int x = 0; x < input->width; x++) {
            float sum = 0.0f;
            if (x >= half && x < input->width - half) {
                for (int k = -half; k <= half; k++) {
                    sum += input->data[y * input->width + (x + k)] * kernel[k + half];
                }
            } else {
                for (int k = -half; k <= half; k++) {
                    int px = x + k;
                    px = px < 0 ? 0 : (px >= input->width ? input->width - 1 : px);
                    sum += input->data[y * input->width + px] * kernel[k + half];
                }
            }
            temp->data[y * input->width + x] = sum;
        }
    }

    // Vertical pass
    for (int y = 0; y < input->height; y++) {
        for (int x = 0; x < input->width; x++) {
            float sum = 0.0f;
            if (y >= half && y < input->height - half) {
                for (int k = -half; k <= half; k++) {
                    sum += temp->data[(y + k) * input->width + x] * kernel[k + half];
                }
            } else {
                for (int k = -half; k <= half; k++) {
                    int py = y + k;
                    py = py < 0 ? 0 : (py >= input->height ? input->height - 1 : py);
                    sum += temp->data[py * input->width + x] * kernel[k + half];
                }
            }
            blurred->data[y * input->width + x] = sum;
        }
    }

    free_image(temp);
    free(kernel);
    return blurred;
}

// -----------------------------------------------------------------------------
// Image Downsampling
// -----------------------------------------------------------------------------

static jo_sift_image* downsample_by_two(const jo_sift_image* img) {
    int new_w = img->width / 2;
    int new_h = img->height / 2;
    jo_sift_image* out = allocate_image(new_w, new_h);
    
    for (int y = 0; y < new_h; y++) {
        for (int x = 0; x < new_w; x++) {
            out->data[y * new_w + x] = img->data[(y * 2) * img->width + (x * 2)];
        }
    }
    return out;
}

// -----------------------------------------------------------------------------
// Building Gaussian and DoG Pyramids (Tracking Octave/Scale)
// -----------------------------------------------------------------------------

/**
 * Build Gaussian pyramid: gauss_pyr[octave][scale]
 * For each octave, we store (num_scales + 3) images to produce num_scales DoG images.
 * base_sigma is the nominal sigma for the base image
 */
static jo_sift_image*** build_gaussian_pyramid(const jo_sift_image* base,
                                int num_octaves,
                                int num_scales,
                                float base_sigma)
{
    float k = powf(2.0f, 1.0f / (float)num_scales);
    jo_sift_image*** gauss_pyr = (jo_sift_image***)malloc(num_octaves * sizeof(jo_sift_image**));
    for (int o = 0; o < num_octaves; o++) {
        gauss_pyr[o] = (jo_sift_image**)malloc((num_scales + 3) * sizeof(jo_sift_image*));
    }

    gauss_pyr[0][0] = allocate_image(base->width, base->height);
    memcpy(gauss_pyr[0][0]->data, base->data, sizeof(float) * base->width * base->height);

    float sig_prev = base_sigma;
    for (int s = 1; s < (num_scales + 3); s++) {
        float sigma_total = sig_prev * sqrtf(k*k - 1.0f);
        gauss_pyr[0][s] = gaussian_blur(gauss_pyr[0][s - 1], sigma_total);
        sig_prev = sig_prev * k;
    }

    for (int o = 1; o < num_octaves; o++) {
        gauss_pyr[o][0] = downsample_by_two(gauss_pyr[o - 1][num_scales]);

        sig_prev = base_sigma;
        for (int s = 1; s < (num_scales + 3); s++) {
            float sigma_total = sig_prev * sqrtf(k*k - 1.0f);
            gauss_pyr[o][s] = gaussian_blur(gauss_pyr[o][s - 1], sigma_total);
            sig_prev = sig_prev * k;
        }
    }
    return gauss_pyr;
}

/**
 * Build DoG (Difference of Gaussian) pyramid from Gaussian pyramid
 */
static jo_sift_image*** build_dog_pyramid(jo_sift_image*** gauss_pyr,
                           int num_octaves,
                           int num_scales)
{
    jo_sift_image*** dog_pyr = (jo_sift_image***)malloc(num_octaves * sizeof(jo_sift_image**));
    for (int o = 0; o < num_octaves; o++) {
        dog_pyr[o] = (jo_sift_image**)malloc((num_scales + 2) * sizeof(jo_sift_image*));
        for (int s = 0; s < (num_scales + 2); s++) {
            int w = gauss_pyr[o][s]->width;
            int h = gauss_pyr[o][s]->height;
            dog_pyr[o][s] = allocate_image(w, h);
            for (int i = 0; i < w * h; i++) {
                dog_pyr[o][s]->data[i] = gauss_pyr[o][s + 1]->data[i]
                                       - gauss_pyr[o][s]->data[i];
            }
        }
    }
    return dog_pyr;
}

/**
 * Compute gradient and Hessian of DoG at (x, y, s) for sub-pixel interpolation
 */
static void compute_derivative_hessian(jo_sift_image*** dog_pyr, int o, int s, int x, int y,
                                       float* grad, float H[3][3])
{
    int width = dog_pyr[o][s]->width;
    float dx = (dog_pyr[o][s]->data[y * width + (x+1)]
              - dog_pyr[o][s]->data[y * width + (x-1)]) * 0.5f;

    float dy = (dog_pyr[o][s]->data[(y+1) * width + x]
              - dog_pyr[o][s]->data[(y-1) * width + x]) * 0.5f;

    float ds = (dog_pyr[o][s+1]->data[y * width + x]
              - dog_pyr[o][s-1]->data[y * width + x]) * 0.5f;

    grad[0] = dx;
    grad[1] = dy;
    grad[2] = ds;

    float v = dog_pyr[o][s]->data[y * width + x];

    float dxx = dog_pyr[o][s]->data[y * width + (x+1)]
              + dog_pyr[o][s]->data[y * width + (x-1)]
              - 2.0f * v;

    float dyy = dog_pyr[o][s]->data[(y+1) * width + x]
              + dog_pyr[o][s]->data[(y-1) * width + x]
              - 2.0f * v;

    float dss = dog_pyr[o][s+1]->data[y * width + x]
              + dog_pyr[o][s-1]->data[y * width + x]
              - 2.0f * v;

    float dxy = ((dog_pyr[o][s]->data[(y+1) * width + (x+1)]
                - dog_pyr[o][s]->data[(y+1) * width + (x-1)]
                - dog_pyr[o][s]->data[(y-1) * width + (x+1)]
                + dog_pyr[o][s]->data[(y-1) * width + (x-1)])) * 0.25f;

    float dxs = ((dog_pyr[o][s+1]->data[y * width + (x+1)]
                - dog_pyr[o][s+1]->data[y * width + (x-1)]
                - dog_pyr[o][s-1]->data[y * width + (x+1)]
                + dog_pyr[o][s-1]->data[y * width + (x-1)])) * 0.25f;

    float dys = ((dog_pyr[o][s+1]->data[(y+1) * width + x]
                - dog_pyr[o][s+1]->data[(y-1) * width + x]
                - dog_pyr[o][s-1]->data[(y+1) * width + x]
                + dog_pyr[o][s-1]->data[(y-1) * width + x])) * 0.25f;

    H[0][0] = dxx; H[0][1] = dxy; H[0][2] = dxs;
    H[1][0] = dxy; H[1][1] = dyy; H[1][2] = dys;
    H[2][0] = dxs; H[2][1] = dys; H[2][2] = dss;
}

/**
 * Attempt sub-pixel refinement at (x, y, s) in the dog pyramid.
 * Return refined offsets in dx, dy, ds (in scale index space).
 * Return 0 if success, -1 if it fails (too large offset, etc.).
 */
static int refine_local_extrema(jo_sift_image*** dog_pyr, int o, int s,
                                int x, int y,
                                float* fx, float* fy, float* fs)
{
    float grad[3];
    float H[3][3];
    compute_derivative_hessian(dog_pyr, o, s, x, y, grad, H);

    float det = H[0][0]*(H[1][1]*H[2][2]-H[1][2]*H[2][1])
              - H[0][1]*(H[1][0]*H[2][2]-H[1][2]*H[2][0])
              + H[0][2]*(H[1][0]*H[2][1]-H[1][1]*H[2][0]);
    if (fabs(det) < 1e-12) {
        return -1;
    }
    float invdet = 1.0f / det;
    float invH[3][3];
    invH[0][0] = invdet*(H[1][1]*H[2][2]-H[1][2]*H[2][1]);
    invH[0][1] = invdet*(H[0][2]*H[2][1]-H[0][1]*H[2][2]);
    invH[0][2] = invdet*(H[0][1]*H[1][2]-H[0][2]*H[1][1]);
    invH[1][0] = invdet*(H[1][2]*H[2][0]-H[1][0]*H[2][2]);
    invH[1][1] = invdet*(H[0][0]*H[2][2]-H[0][2]*H[2][0]);
    invH[1][2] = invdet*(H[0][2]*H[1][0]-H[0][0]*H[1][2]);
    invH[2][0] = invdet*(H[1][0]*H[2][1]-H[1][1]*H[2][0]);
    invH[2][1] = invdet*(H[0][1]*H[2][0]-H[0][0]*H[2][1]);
    invH[2][2] = invdet*(H[0][0]*H[1][1]-H[0][1]*H[1][0]);

    float dx = -(invH[0][0]*grad[0] + invH[0][1]*grad[1] + invH[0][2]*grad[2]);
    float dy = -(invH[1][0]*grad[0] + invH[1][1]*grad[1] + invH[1][2]*grad[2]);
    float ds_ = -(invH[2][0]*grad[0] + invH[2][1]*grad[1] + invH[2][2]*grad[2]);

    if (fabsf(dx) > 1.5f || fabsf(dy) > 1.5f || fabsf(ds_) > 1.5f) {
        return -1;
    }
    *fx = dx;
    *fy = dy;
    *fs = ds_;
    return 0;
}

static int is_extrema(jo_sift_image*** dog_pyr, int o, int s, int x, int y) {
    int width = dog_pyr[o][s]->width;
    float* curr_data = dog_pyr[o][s]->data;
    float val = curr_data[y * width + x];
    int is_max = 1;
    int is_min = 1;
    
    for (int ds = -1; ds <= 1; ds++) {
        float* layer_data = dog_pyr[o][s + ds]->data;
        for (int dy = -1; dy <= 1; dy++) {
            int idx = (y + dy) * width + x;
            for (int dx = -1; dx <= 1; dx++) {
                if (dx == 0 && dy == 0 && ds == 0) continue;
                float comp = layer_data[idx + dx];
                if (comp > val) { is_max = 0; }
                if (comp < val) { is_min = 0; }
                if (!is_max && !is_min) {
                    return 0;
                }
            }
        }
    }
    return (is_max || is_min);
}

/**
 * Perform the Hessian-based edge response check (Lowe's paper).
 * Discard keypoints with high ratio of principal curvatures.
 */
static int pass_edge_response_check(jo_sift_image*** dog_pyr, int o, int s, int x, int y) {
    int width = dog_pyr[o][s]->width;
    float dxx = dog_pyr[o][s]->data[y * width + (x+1)]
              + dog_pyr[o][s]->data[y * width + (x-1)]
              - 2.0f * dog_pyr[o][s]->data[y * width + x];

    float dyy = dog_pyr[o][s]->data[(y+1) * width + x]
              + dog_pyr[o][s]->data[(y-1) * width + x]
              - 2.0f * dog_pyr[o][s]->data[y * width + x];

    float dxy = ((dog_pyr[o][s]->data[(y+1) * width + (x+1)]
                - dog_pyr[o][s]->data[(y+1) * width + (x-1)]
                - dog_pyr[o][s]->data[(y-1) * width + (x+1)]
                + dog_pyr[o][s]->data[(y-1) * width + (x-1)])) * 0.25f;

    float tr = dxx + dyy;
    float det = dxx*dyy - dxy*dxy;
    if (det <= 0.0f) return 0;

    float rc = (tr*tr)/det;
    if (rc > EDGE_THRESHOLD) {
        return 0;
    }
    return 1;
}

static float dog_value_at_offset(jo_sift_image*** dog_pyr, int o, int s, int x, int y,
                                 float fx, float fy, float fs)
{
    float grad[3];
    float H[3][3];
    compute_derivative_hessian(dog_pyr, o, s, x, y, grad, H);

    float val = dog_pyr[o][s]->data[y * dog_pyr[o][s]->width + x];
    float offset_val = val + 0.5f * (grad[0]*fx + grad[1]*fy + grad[2]*fs);
    return offset_val;
}

/**
 * Detect keypoints across the DoG pyramid with sub-pixel and scale refinement.
 */
static jo_sift_keypoint* detect_keypoints(jo_sift_image*** dog_pyr, jo_sift_image*** gauss_pyr,
                           int num_octaves, int num_scales,
                           float base_sigma, int* out_num_keys)
{
    const int MAX_KEYS = 10000;
    jo_sift_keypoint* keys = (jo_sift_keypoint*)malloc(MAX_KEYS * sizeof(jo_sift_keypoint));
    int count = 0;

    for (int o = 0; o < num_octaves; o++) {
        int w = dog_pyr[o][0]->width;
        int h = dog_pyr[o][0]->height;
        for (int s = 1; s < (num_scales + 1); s++) {
            for (int y = 1; y < h - 1; y++) {
                for (int x = 1; x < w - 1; x++) {
                    if (!is_extrema(dog_pyr, o, s, x, y)) continue;

                    float fx, fy, fs;
                    if (refine_local_extrema(dog_pyr, o, s, x, y, &fx, &fy, &fs) != 0) {
                        continue;
                    }
                    float val = fabs(dog_value_at_offset(dog_pyr, o, s, x, y, fx, fy, fs));
                    if (val < CONTRAST_THRESHOLD) {
                        continue;
                    }
                    if (!pass_edge_response_check(dog_pyr, o, s, x, y)) {
                        continue;
                    }

                    float scale_factor = powf(2.0f, (float)o);
                    float layer_sigma = base_sigma * powf(2.0f, (s + fs)/(float)num_scales);

                    float kx = (float)x + fx;
                    float ky = (float)y + fy;

                    if (count < MAX_KEYS) {
                        keys[count].octave = o;
                        keys[count].layer = s;
                        keys[count].x = kx;
                        keys[count].y = ky;
                        keys[count].sigma = layer_sigma * scale_factor;
                        keys[count].real_x = scale_factor * kx;
                        keys[count].real_y = scale_factor * ky;
                        keys[count].orientation = 0.0f;
                        memset(keys[count].descriptor, 0, sizeof(keys[count].descriptor));
                        count++;
                    }
                }
            }
        }
    }
    *out_num_keys = count;
    return keys;
}

// -----------------------------------------------------------------------------
// Orientation Assignment (with Multiple Peaks)
// -----------------------------------------------------------------------------

/**
 * Build orientation histogram around (x, y) in gauss_pyr[o][layer].
 * Return the main orientation, and also store any additional peaks
 * above peak * ORI_PEAK_RATIO in the out_peaks array. 
 */
static int orientation_histogram(const jo_sift_image* img, float cx, float cy,
                                 float scale, float hist[ORI_HIST_BINS])
{
    memset(hist, 0, ORI_HIST_BINS * sizeof(float));
    float radius = 3.0f * scale;
    int rad = (int)floor(radius);

    for (int dy = -rad; dy <= rad; dy++) {
        for (int dx = -rad; dx <= rad; dx++) {
            float nx = cx + dx;
            float ny = cy + dy;
            float dist_sq = (float)(dx*dx + dy*dy);
            if (dist_sq > radius*radius) continue;

            // Ensure integer pixel coordinates are in range:
            int ix = (int)nx;
            int iy = (int)ny;
            if (ix < 1 || ix >= (img->width  - 1))  continue;
            if (iy < 1 || iy >= (img->height - 1))  continue;

            // Correct indexing for gx and gy
            float gx = img->data[iy * img->width + (ix + 1)]
                     - img->data[iy * img->width + (ix - 1)];

            float gy = img->data[(iy + 1) * img->width + ix]
                     - img->data[(iy - 1) * img->width + ix];

            float mag   = sqrtf(gx*gx + gy*gy);
            float angle = atan2f(gy, gx);
            if (angle < 0.0f) {
                angle += 2.0f * (float)M_PI;
            }

            float w = expf(-dist_sq / (2.0f * (0.5f * radius) * (0.5f * radius)));
            mag *= w;

            float bin_f = (angle * ORI_HIST_BINS) / (2.0f * (float)M_PI);
            int bin = (int)floor(bin_f);
            bin = (bin + ORI_HIST_BINS) % ORI_HIST_BINS;
            float frac = bin_f - bin;

            hist[bin] += (1.0f - frac) * mag;
            hist[(bin + 1) % ORI_HIST_BINS] += frac * mag;
        }
    }
    return 0;
}

/**
 * Smooth orientation histogram (Lowe suggests a simple 6x circular convolution).
 */
static void smooth_orientation_histogram(float hist[ORI_HIST_BINS]) {
    float tmp[ORI_HIST_BINS];
    for (int i = 0; i < 6; i++) {
        memcpy(tmp, hist, ORI_HIST_BINS * sizeof(float));
        for (int j = 0; j < ORI_HIST_BINS; j++) {
            float prev = tmp[(j - 1 + ORI_HIST_BINS) % ORI_HIST_BINS];
            float curr = tmp[j];
            float next = tmp[(j + 1) % ORI_HIST_BINS];
            hist[j] = 0.25f * prev + 0.5f * curr + 0.25f * next;
        }
    }
}

/**
 * Assign orientations to keypoints. If a secondary peak is within
 * ORI_PEAK_RATIO of the main peak, add a new keypoint with that orientation.
 *
 * This potentially increases the number of keypoints.
 */
static jo_sift_keypoint* assign_orientations(jo_sift_keypoint* keys, int* num_keys_ptr,
                              jo_sift_image*** gauss_pyr, int num_scales)
{
    int num_keys = *num_keys_ptr;
    jo_sift_keypoint* new_keys = (jo_sift_keypoint*)malloc(sizeof(jo_sift_keypoint)*num_keys*4);
    int count = 0;

    for (int i = 0; i < num_keys; i++) {
        jo_sift_keypoint* k = &keys[i];
        int o = k->octave;
        int layer = k->layer;
        jo_sift_image* img = gauss_pyr[o][layer];
        float region_scale = 1.5f * (k->sigma / powf(2.0f, (float)o));

        float hist[ORI_HIST_BINS];
        orientation_histogram(img, k->x, k->y, region_scale, hist);
        smooth_orientation_histogram(hist);

        float max_val = 0.0f;
        for (int b = 0; b < ORI_HIST_BINS; b++) {
            if (hist[b] > max_val) {
                max_val = hist[b];
            }
        }

        for (int b = 0; b < ORI_HIST_BINS; b++) {
            int prev_b = (b - 1 + ORI_HIST_BINS) % ORI_HIST_BINS;
            int next_b = (b + 1) % ORI_HIST_BINS;
            if (hist[b] > hist[prev_b] && hist[b] > hist[next_b] && hist[b] >= 0.8f*max_val) {
                float theta = 2.0f*(float)M_PI * ((float)b + 0.5f*(hist[prev_b]-hist[next_b]) 
                          /(hist[prev_b]-2.0f*hist[b]+hist[next_b]))
                        / (float)ORI_HIST_BINS;
                if (theta < 0.0f) theta += 2.0f*(float)M_PI;
                if (theta >= 2.0f*(float)M_PI) theta -= 2.0f*(float)M_PI;

                new_keys[count] = *k;
                new_keys[count].orientation = theta;
                count++;
            }
        }
    }
    free(keys);
    *num_keys_ptr = count;
    return new_keys;
}

static void compute_sift_descriptors(jo_sift_keypoint* keys, int num_keys,
                                     jo_sift_image*** gauss_pyr,
                                     int num_scales) 
{
    // Size of the descriptor region around the keypoint in terms of
    // scale multiples (Lowe used 3 * key->sigma for radius, descriptor is 16x16)
    const int DESC_WINDOW = 16;       

    // Each 16×16 region is broken down into 4×4 cells,
    // each cell has 8 orientation bins
    const int N_HIST = 4;
    const int N_BINS = 8;

    for (int i = 0; i < num_keys; i++) {
        jo_sift_keypoint* key = &keys[i];

        int o = key->octave;
        int layer = key->layer;
        jo_sift_image* img = gauss_pyr[o][layer];

        float cos_t = cosf(key->orientation);
        float sin_t = sinf(key->orientation);

        // Spatial bin size relative to key->sigma
        float hist_spacing = 3.0f * key->sigma / ((float)N_HIST);

        // Zero out the local histogram array
        float hist[N_HIST][N_HIST][N_BINS];
        memset(hist, 0, sizeof(hist));

        // For each pixel in a 16×16 window around the keypoint
        // (in practice, go a bit bigger to handle the Gaussian weighting)
        int radius = (int)(roundf((DESC_WINDOW / 2.0f) * key->sigma));
        for (int dy = -radius; dy <= radius; dy++) {
            for (int dx = -radius; dx <= radius; dx++) {
                // Rotate (dx, dy) by key->orientation
                float r_x = ( dx * cos_t - dy * sin_t);
                float r_y = ( dx * sin_t + dy * cos_t);

                // Decide which histogram cell this pixel falls into
                float bin_x = (r_x / hist_spacing) + (N_HIST / 2.0f) - 0.5f;
                float bin_y = (r_y / hist_spacing) + (N_HIST / 2.0f) - 0.5f;

                int ix = (int)floorf(key->x + dx + 0.5f);
                int iy = (int)floorf(key->y + dy + 0.5f);

                // Check boundaries
                if (ix < 1 || ix >= img->width - 1 || iy < 1 || iy >= img->height - 1)
                    continue;

                // Compute gradient in original (unrotated) coords
                float gx = img->data[iy * img->width + (ix+1)] 
                         - img->data[iy * img->width + (ix-1)];
                float gy = img->data[(iy+1) * img->width + ix]
                         - img->data[(iy-1) * img->width + ix];

                // Magnitude and orientation
                float mag = sqrtf(gx*gx + gy*gy);
                float theta = atan2f(gy, gx) - key->orientation;
                // Normalize angle to [0, 2π)
                while (theta < 0.0f)       theta += 2.0f * (float)M_PI;
                while (theta >= 2.0f*M_PI) theta -= 2.0f * (float)M_PI;

                // Weighted by a Gaussian
                float gauss_sigma = 0.5f * DESC_WINDOW * key->sigma; 
                float dist_sq = r_x*r_x + r_y*r_y;
                float weight = expf(-dist_sq / (2.0f * gauss_sigma * gauss_sigma));
                mag *= weight;

                // Determine orientation bin
                float bin_f = (theta * (float)N_BINS) / (2.0f*(float)M_PI);
                // Orientation bin index
                int bin_o = (int)floorf(bin_f) % N_BINS;
                float bin_o_frac = bin_f - floorf(bin_f);

                // Assign to histogram if we are in range
                if (bin_x > -1.0 && bin_x < N_HIST && bin_y > -1.0 && bin_y < N_HIST) {
                    // For interpolation, find integer bins around (bin_x, bin_y)
                    int bx0 = (int)floorf(bin_x);
                    int by0 = (int)floorf(bin_y);
                    float tx = bin_x - bx0;
                    float ty = bin_y - by0;

                    for (int byi = 0; byi <= 1; byi++) {
                        int by_idx = by0 + byi;
                        if (by_idx < 0 || by_idx >= N_HIST) continue;
                        float w_y = (byi ? ty : (1.0f - ty));

                        for (int bxi = 0; bxi <= 1; bxi++) {
                            int bx_idx = bx0 + bxi;
                            if (bx_idx < 0 || bx_idx >= N_HIST) continue;
                            float w_x = (bxi ? tx : (1.0f - tx));

                            // Distribute orientation to bin_o and bin_o+1
                            // (because of orientation bin interpolation)
                            float w = mag * w_x * w_y;

                            hist[by_idx][bx_idx][bin_o] += w * (1.0f - bin_o_frac);
                            hist[by_idx][bx_idx][(bin_o+1) % N_BINS] += w * bin_o_frac;
                        }
                    }
                }
            }
        }

        // Now flatten the 4×4×8 histogram block into a 128-dim array
        int idx = 0;
        for (int hy = 0; hy < N_HIST; hy++) {
            for (int hx = 0; hx < N_HIST; hx++) {
                for (int hb = 0; hb < N_BINS; hb++) {
                    key->descriptor[idx++] = hist[hy][hx][hb];
                }
            }
        }

        // Normalize descriptor
        float norm = 0.0f;
        for (int j = 0; j < 128; j++) {
            norm += key->descriptor[j] * key->descriptor[j];
        }
        norm = sqrtf(norm) + 1e-6f; // avoid divide-by-zero

        for (int j = 0; j < 128; j++) {
            key->descriptor[j] /= norm;
        }

        // Thresholding large values and renormalize (Lowe's step)
        for (int j = 0; j < 128; j++) {
            if (key->descriptor[j] > 0.2f) {
                key->descriptor[j] = 0.2f;
            }
        }
        // Recompute norm
        norm = 0.0f;
        for (int j = 0; j < 128; j++) {
            norm += key->descriptor[j] * key->descriptor[j];
        }
        norm = sqrtf(norm) + 1e-6f;
        for (int j = 0; j < 128; j++) {
            key->descriptor[j] /= norm;
        }
    }
}

/**
 * Main SIFT detection function. Detects keypoints in the given image and returns
 * an array of keypoints. The number of keypoints is written to num_keypoints.
 * The caller is responsible for freeing the returned array.
 */
jo_sift_keypoint* jo_sift_detect(const jo_sift_image* img, int* num_keypoints) {
    // Early bailout if the image is too small to do anything
    if (img->width < 2 || img->height < 2) {
        *num_keypoints = 0;
        return NULL;
    }

    // Calculate number of octaves, but clamp to at least 1
    int num_octaves = (int)(log2f((float)fmin(img->width, img->height))) - 3;
    if (num_octaves < 1) {
        num_octaves = 1;
    }

    const int num_scales = 3;
    const float base_sigma = 1.6f;

    jo_sift_image*** gauss_pyr = build_gaussian_pyramid(img, num_octaves, num_scales, base_sigma);
    jo_sift_image*** dog_pyr   = build_dog_pyramid(gauss_pyr, num_octaves, num_scales);

    int n_keys = 0;
    jo_sift_keypoint* keys = detect_keypoints(dog_pyr, gauss_pyr,
                                              num_octaves, num_scales,
                                              base_sigma, &n_keys);
    keys = assign_orientations(keys, &n_keys, gauss_pyr, num_scales);
    compute_sift_descriptors(keys, n_keys, gauss_pyr, num_scales);

    for (int o = 0; o < num_octaves; o++) {
        for (int s = 0; s < (num_scales + 3); s++) {
            free_image(gauss_pyr[o][s]);
        }
        for (int s = 0; s < (num_scales + 2); s++) {
            free_image(dog_pyr[o][s]);
        }
        free(gauss_pyr[o]);
        free(dog_pyr[o]);
    }
    free(gauss_pyr);
    free(dog_pyr);

    *num_keypoints = n_keys;
    return keys;
}

/**
 * Match keypoints between two sets using Lowe's ratio test.
 * Returns array of matches, with number of matches written to num_matches.
 * The caller is responsible for freeing the returned array.
 */
jo_sift_match* jo_sift_match_keypoints(const jo_sift_keypoint* keys1, int n_keys1,
                                      const jo_sift_keypoint* keys2, int n_keys2,
                                      int* num_matches) 
{
    jo_sift_match* matches = (jo_sift_match*)malloc(n_keys1 * sizeof(jo_sift_match));
    int count = 0;

    for (int i = 0; i < n_keys1; i++) {
        float best_dist = INFINITY;
        float second_best_dist = INFINITY;
        int best_idx = -1;

        for (int j = 0; j < n_keys2; j++) {
            float dist = 0.0f;
            for (int k = 0; k < 128; k++) {
                float diff = keys1[i].descriptor[k] - keys2[j].descriptor[k];
                dist += diff * diff;
            }
            
            if (dist < best_dist) {
                second_best_dist = best_dist;
                best_dist = dist;
                best_idx = j;
            } else if (dist < second_best_dist) {
                second_best_dist = dist;
            }
        }

        if (best_idx != -1 && best_dist < second_best_dist * MATCH_RATIO_THRESHOLD * MATCH_RATIO_THRESHOLD) {
            matches[count].query_idx = i;
            matches[count].train_idx = best_idx;
            matches[count].distance = sqrtf(best_dist);
            count++;
        }
    }

    *num_matches = count;
    return matches;
}

#endif // JO_SIFT_IMPLEMENTATION

#ifdef JO_SIFT_TEST

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

static jo_sift_image* load_test_image(const char* filename) {
    int w, h, channels;
    unsigned char* data = stbi_load(filename, &w, &h, &channels, 1);
    if (!data) return NULL;

    jo_sift_image* img = (jo_sift_image*)malloc(sizeof(jo_sift_image));
    img->width = w;
    img->height = h;
    img->data = (float*)malloc(w * h * sizeof(float));

    for (int i = 0; i < w * h; i++) {
        img->data[i] = data[i] / 255.0f;
    }

    stbi_image_free(data);
    return img;
}

/**
 * Create a side-by-side visualization of matches between two images
 */
static void draw_matches(const char* output_path,
                        const unsigned char* img1_data, int w1, int h1,
                        const unsigned char* img2_data, int w2, int h2,
                        const jo_sift_match* matches, int n_matches,
                        const jo_sift_keypoint* keys1,
                        const jo_sift_keypoint* keys2) 
{
    // Create side-by-side output image
    int out_w = w1 + w2;
    int out_h = h1 > h2 ? h1 : h2;
    unsigned char* out_data = (unsigned char*)malloc(out_w * out_h * 3);
    memset(out_data, 255, out_w * out_h * 3); // White background

    // Copy first image to left side
    for (int y = 0; y < h1; y++) {
        for (int x = 0; x < w1; x++) {
            unsigned char gray = img1_data[y * w1 + x];
            out_data[(y * out_w + x) * 3 + 0] = gray;
            out_data[(y * out_w + x) * 3 + 1] = gray;
            out_data[(y * out_w + x) * 3 + 2] = gray;
        }
    }

    // Copy second image to right side
    for (int y = 0; y < h2; y++) {
        for (int x = 0; x < w2; x++) {
            unsigned char gray = img2_data[y * w2 + x];
            out_data[(y * out_w + (x + w1)) * 3 + 0] = gray;
            out_data[(y * out_w + (x + w1)) * 3 + 1] = gray;
            out_data[(y * out_w + (x + w1)) * 3 + 2] = gray;
        }
    }

    // Draw matches (simple line drawing)
    for (int i = 0; i < n_matches; i++) {
        int x1 = (int)keys1[matches[i].query_idx].real_x;
        int y1 = (int)keys1[matches[i].query_idx].real_y;
        int x2 = (int)keys2[matches[i].train_idx].real_x + w1; // Offset for right image
        int y2 = (int)keys2[matches[i].train_idx].real_y;

        // Draw line using Bresenham's algorithm
        int dx = abs(x2 - x1), sx = x1 < x2 ? 1 : -1;
        int dy = -abs(y2 - y1), sy = y1 < y2 ? 1 : -1;
        int err = dx + dy, e2;

        while (1) {
            if (x1 >= 0 && x1 < out_w && y1 >= 0 && y1 < out_h) {
                // Draw in green
                out_data[(y1 * out_w + x1) * 3 + 0] = 0;
                out_data[(y1 * out_w + x1) * 3 + 1] = 255;
                out_data[(y1 * out_w + x1) * 3 + 2] = 0;
            }
            if (x1 == x2 && y1 == y2) break;
            e2 = 2 * err;
            if (e2 >= dy) { err += dy; x1 += sx; }
            if (e2 <= dx) { err += dx; y1 += sy; }
        }

        // Draw small circles at keypoints
        for (int dy = -2; dy <= 2; dy++) {
            for (int dx = -2; dx <= 2; dx++) {
                if (dx*dx + dy*dy > 6) continue; // Rough circle
                
                // First keypoint (red)
                int px = (int)keys1[matches[i].query_idx].real_x + dx;
                int py = (int)keys1[matches[i].query_idx].real_y + dy;
                if (px >= 0 && px < w1 && py >= 0 && py < out_h) {
                    out_data[(py * out_w + px) * 3 + 0] = 255;
                    out_data[(py * out_w + px) * 3 + 1] = 0;
                    out_data[(py * out_w + px) * 3 + 2] = 0;
                }

                // Second keypoint (red)
                px = (int)keys2[matches[i].train_idx].real_x + w1 + dx;
                py = (int)keys2[matches[i].train_idx].real_y + dy;
                if (px >= 0 && px < out_w && py >= 0 && py < out_h) {
                    out_data[(py * out_w + px) * 3 + 0] = 255;
                    out_data[(py * out_w + px) * 3 + 1] = 0;
                    out_data[(py * out_w + px) * 3 + 2] = 0;
                }
            }
        }
    }

    // Save output image
    stbi_write_png(output_path, out_w, out_h, 3, out_data, out_w * 3);
    free(out_data);
}

int main(int argc, char** argv) {
    if (argc != 3) {
        printf("Usage: %s image1.jpg image2.jpg\n", argv[0]);
        return 1;
    }

    // Load original image data (for visualization)
    int w1, h1, channels1;
    unsigned char* img1_data = stbi_load(argv[1], &w1, &h1, &channels1, 1);
    int w2, h2, channels2;
    unsigned char* img2_data = stbi_load(argv[2], &w2, &h2, &channels2, 1);

    if (!img1_data || !img2_data) {
        printf("Failed to load images\n");
        return 1;
    }

    // Convert to float images for SIFT
    jo_sift_image* img1 = load_test_image(argv[1]);
    jo_sift_image* img2 = load_test_image(argv[2]);

    printf("Detecting SIFT features in image 1 (%dx%d)...\n", img1->width, img1->height);
    int n_keys1;
    jo_sift_keypoint* keys1 = jo_sift_detect(img1, &n_keys1);
    printf("Found %d keypoints\n", n_keys1);

    printf("Detecting SIFT features in image 2 (%dx%d)...\n", img2->width, img2->height);
    int n_keys2;
    jo_sift_keypoint* keys2 = jo_sift_detect(img2, &n_keys2);
    printf("Found %d keypoints\n", n_keys2);

    printf("Matching keypoints...\n");
    int n_matches;
    jo_sift_match* matches = jo_sift_match_keypoints(keys1, n_keys1, keys2, n_keys2, &n_matches);
    printf("Found %d matches\n", n_matches);

    // Draw and save visualization
    printf("Saving visualization to 'matches.png'...\n");
    draw_matches("matches.png", img1_data, w1, h1, img2_data, w2, h2,
                matches, n_matches, keys1, keys2);

    // Cleanup
    stbi_image_free(img1_data);
    stbi_image_free(img2_data);
    free(matches);
    free(keys1);
    free(keys2);
    free(img1->data);
    free(img1);
    free(img2->data);
    free(img2);

    return 0;
}

#endif // JO_SIFT_TEST
