#include "util.h"

#include <stdint.h>

float interp(uint32_t n_points, const float* source_x, const float* source_y,
             float target_x) {
  uint32_t i;
  for (i = 0; i < n_points; i++) {
    if (source_x[i] > target_x) {
      break;
    }
  }
  if (i == 0) {
    // target_x is smaller than the smallest value in source_x
    i++;
  }
  if (i == n_points) {
    // target_y is larger than the largest value in source_x
    i--;
  }
  float x1 = source_x[i - 1];
  float x2 = source_x[i];
  float y1 = source_y[i - 1];
  float y2 = source_y[i];
  float slope = (y2 - y1) / (x2 - x1);
  return y1 + slope * (target_x - x1);
}
