// APPROXIMATE layer (M3): 2D least-squares curve fitting, mirroring the 3D fit
// (NURBS Book Eq 9.63/9.67) with Householder QR. Used by 2D offset to re-fit the
// sampled offset locus as a NURBS curve.

///|
fn params2(points : FixedArray[@f64.DVec2]) -> FixedArray[Double]? {
  let n = points.length() - 1
  let uk : FixedArray[Double] = FixedArray::make(n + 1, 0.0)
  let mut total = 0.0
  for i = 1; i <= n; i = i + 1 {
    total = total + (points[i] - points[i - 1]).length()
  }
  if total == 0.0 {
    return None
  }
  for i = 1; i < n; i = i + 1 {
    uk[i] = uk[i - 1] + (points[i] - points[i - 1]).length() / total
  }
  uk[n] = 1.0
  Some(uk)
}

///|
pub fn NurbsCurve2::fit(
  points : FixedArray[@f64.DVec2],
  degree : Int,
  num_cpts? : Int,
) -> NurbsCurve2? {
  let num_dpts = points.length()
  let nc = match num_cpts {
    Some(x) => x
    None => num_dpts - 1
  }
  if degree < 1 || num_dpts < 2 || nc < degree + 1 || nc > num_dpts - 1 {
    return None
  }
  let uk = match params2(points) {
    None => return None
    Some(x) => x
  }
  let kv = match fit_knots(degree, num_dpts, nc, uk) {
    None => return None
    Some(x) => x
  }
  let n = nc - 1
  let ctrl : FixedArray[@f64.DVec2] = FixedArray::make(nc, @f64.DVec2::zero())
  ctrl[0] = points[0]
  ctrl[nc - 1] = points[num_dpts - 1]
  let rows = num_dpts - 2
  let cols = nc - 2
  if rows >= 1 && cols >= 1 {
    let mat = dmat(rows, cols)
    let rkx : FixedArray[Double] = FixedArray::make(rows, 0.0)
    let rky : FixedArray[Double] = FixedArray::make(rows, 0.0)
    for i = 1; i <= num_dpts - 2; i = i + 1 {
      let u = uk[i]
      let n0 = kv.basis_one(degree, n, 0, u)
      let nn = kv.basis_one(degree, n, n, u)
      rkx[i - 1] = points[i].x - n0 * points[0].x - nn * points[num_dpts - 1].x
      rky[i - 1] = points[i].y - n0 * points[0].y - nn * points[num_dpts - 1].y
      for j = 1; j <= nc - 2; j = j + 1 {
        dmat_set(mat, i - 1, j - 1, kv.basis_one(degree, n, j, u))
      }
    }
    let px = match qr_solve(mat, rkx) {
      None => return None
      Some(x) => x
    }
    let py = match qr_solve(mat, rky) {
      None => return None
      Some(x) => x
    }
    for j = 1; j <= nc - 2; j = j + 1 {
      ctrl[j] = @f64.DVec2::new(px[j - 1], py[j - 1])
    }
  }
  NurbsCurve2::from_points(degree, kv, ctrl)
}