///|
pub struct TilePlan {
  variable : String
  shape : Array[Int64]
  tile_shape : Array[Int64]
  grid_shape : Array[Int64]
  tiles : Int32
  values : Int64
  peak_values : Int32
}

///|
/// Plan a bounded traversal without allocating the entire variable. A tile may
/// contain at most result_values. At most 65,536 callbacks are allowed per scan.
pub fn Dataset::plan_tiles(
  self : Dataset,
  name : String,
  tile_shape : Array[Int64],
) -> TilePlan raise CdfError {
  let variable = self.find(name)
  if tile_shape.length() != variable.shape.length() {
    raise Invalid("tile shape must match variable rank")
  }
  let grid : Array[Int64] = []
  let clipped : Array[Int64] = []
  for axis, extent in variable.shape {
    let step = tile_shape[axis]
    if step < 1L {
      raise Invalid("tile extents must be positive")
    }
    grid.push(if extent == 0L { 0L } else { (extent - 1L) / step + 1L })
    clipped.push(if step < extent { step } else { extent })
  }
  let peak = shape_count(clipped, self.limits.result_values.to_int64())
  let tiles = shape_count(grid, 65536L)
  let values = shape_count(variable.shape, self.limits.file_bytes.to_int64())
  {
    variable: variable.name,
    shape: variable.shape.copy(),
    tile_shape: tile_shape.copy(),
    grid_shape: grid,
    tiles: tiles.to_int(),
    values,
    peak_values: peak.to_int(),
  }
}

///|
/// Invoke callback in row-major tile order. The callback receives independent
/// arrays, can stop a scan by raising CdfError, and cannot mutate the source.
pub fn Dataset::for_each_tile(
  self : Dataset,
  name : String,
  tile_shape : Array[Int64],
  callback : (Array[Int64], DataBlock) -> Unit raise CdfError,
) -> Unit raise CdfError {
  let plan = self.plan_tiles(name, tile_shape)
  for index in 0..= 0; axis = axis - 1 {
      origin[axis] = remaining % plan.grid_shape[axis] * plan.tile_shape[axis]
      remaining /= plan.grid_shape[axis]
      let available = plan.shape[axis] - origin[axis]
      count[axis] = if available < plan.tile_shape[axis] {
        available
      } else {
        plan.tile_shape[axis]
      }
    }
    callback(origin, self.section(name, origin, count))
  }
}

///|
/// Summarize a whole numeric variable through tiles, including variables larger
/// than the single-result limit. Only one raw and one physical tile are held at
/// once. The 64 MiB file limit still applies; this is not streaming file I/O.
pub fn Dataset::scan_summary(
  self : Dataset,
  name : String,
  tile_values~ : Int32 = 65536,
) -> NumericSummary raise CdfError {
  if tile_values < 1 || tile_values > self.limits.result_values {
    raise Invalid("tile value budget must be within the result budget")
  }
  let variable = self.find(name)
  let tile_shape = Array::make(variable.shape.length(), 1L)
  let model = packing(variable.data_type, variable.attributes)
  let mut remaining = tile_values.to_int64()
  for axis = tile_shape.length() - 1; axis >= 0; axis = axis - 1 {
    let extent = if variable.shape[axis] < 1L {
      1L
    } else {
      variable.shape[axis]
    }
    let step = if extent < remaining { extent } else { remaining }
    tile_shape[axis] = step
    remaining /= step
  }
  let total = summary_state()
  self.for_each_tile(name, tile_shape, (_origin, block) => {
    let physical = decode_with_packing(block, model)
    for value in physical.values {
      total.observe(value)
    }
  })
  total.finish()
}