///|
/// Sub-grid multi-point cell sampling with Gaussian spatial kernel for robust bit decoding under noise.
pub fn sample_cell_intensity_multisample(
  sampled_grid : Image,
  cell_r : Int,
  cell_c : Int,
  total_cells : Int,
  samples_per_dim? : Int = 3,
) -> Double {
  let cell_w = sampled_grid.width.to_double() / total_cells.to_double()
  let cell_h = sampled_grid.height.to_double() / total_cells.to_double()

  let n = samples_per_dim
  let offset_step = 0.5 / (n.to_double() + 1.0)
  let mut sum_intensity = 0.0
  let mut sum_weight = 0.0

  let center_x = (cell_c.to_double() + 0.5) * cell_w
  let center_y = (cell_r.to_double() + 0.5) * cell_h

  for sy in 0.. 1.0e-12 {
    sum_intensity / sum_weight
  } else {
    sampled_grid.sample_bilinear(Point2D::new(center_x, center_y))
  }
}

///|
/// Verifies the quiet zone (white margin surrounding the fiducial marker).
pub fn verify_quiet_zone(
  sampled_grid : Image,
  total_cells : Int,
  white_threshold? : Int = 128,
  min_white_rate? : Double = 0.70,
) -> Bool {
  let cell_w = sampled_grid.width.to_double() / (total_cells.to_double() + 2.0)
  let cell_h = sampled_grid.height.to_double() / (total_cells.to_double() + 2.0)
  let grid_dim = total_cells + 2

  let mut total_quiet_pixels = 0
  let mut white_quiet_pixels = 0

  for r in 0..= white_threshold {
          white_quiet_pixels += 1
        }
      }
    }
  }

  if total_quiet_pixels == 0 {
    return true
  }

  white_quiet_pixels.to_double() / total_quiet_pixels.to_double() >=
  min_white_rate
}

///|
/// Extracts binary grid payload bits using Otsu's optimal binarization threshold on the inner grid.
pub fn sample_payload_bits_otsu(
  sampled_grid : Image,
  dict : MarkerDictionary,
) -> Int64 {
  let data_size = dict.grid_size
  let total_cells = data_size + 2
  let intensities = Array::make(data_size * data_size, 0.0)

  let mut min_val = 255.0
  let mut max_val = 0.0

  for r in 0.. max_val {
        max_val = val
      }
    }
  }

  // Midpoint threshold
  let thresh = (min_val + max_val) * 0.5
  let mut payload = 0L

  for r in 0..= thresh { 1L } else { 0L }
      let bit_idx = r * data_size + c
      if bit == 1L {
        payload = payload | (1L << bit_idx)
      }
    }
  }

  payload
}