///|
fn words(text : String) -> Array[String] {
  let output : Array[String] = []
  let word = StringBuilder()
  for character in text.to_array() {
    if character == ' ' ||
      character == '\t' ||
      character == '\r' ||
      character == '\n' {
      if !word.is_empty() {
        output.push(word.to_string())
        word.reset()
      }
    } else {
      word.write_char(character)
    }
  }
  if !word.is_empty() {
    output.push(word.to_string())
  }
  output
}

///|
fn paired_references(text : String) -> Array[String] raise CdfError {
  // CF cell_measures and formula_terms are key: variable pairs. Splitting the
  // colon explicitly also handles both 'area: a' and 'area:a'.
  let normalized = StringBuilder()
  for character in text.to_array() {
    if character == ':' {
      normalized.write_string(" : ")
    } else {
      normalized.write_char(character)
    }
  }
  let tokens = words(normalized.to_string())
  if tokens.length() % 3 != 0 {
    raise Invalid("malformed CF key: variable reference list")
  }
  let references : Array[String] = []
  for i = 0; i < tokens.length(); i = i + 3 {
    if tokens[i] == ":" || tokens[i + 1] != ":" || tokens[i + 2] == ":" {
      raise Invalid("malformed CF key: variable reference list")
    }
    references.push(tokens[i + 2])
  }
  references
}

///|
fn variable_references(variable : VariableInfo) -> Array[String] raise CdfError {
  let output : Array[String] = []
  for attribute in variable.attributes {
    match attribute.name {
      "coordinates" | "ancillary_variables" =>
        for name in words(attribute_text(attribute)) {
          output.push(name)
        }
      "bounds" | "climatology" | "grid_mapping" => {
        let names = words(attribute_text(attribute))
        if names.length() != 1 || names[0].contains(":") {
          raise Unsupported(
            "projection supports a single bounds, climatology or grid_mapping reference",
          )
        }
        output.push(names[0])
      }
      "cell_measures" | "formula_terms" =>
        for name in paired_references(attribute_text(attribute)) {
          output.push(name)
        }
      _ => ()
    }
  }
  output
}

///|
/// Keep selected variables with their dimension coordinates and explicit CF
/// dependencies. Recursively referenced variables retain their own dependencies.
/// Global attributes are copied verbatim. Unknown application-specific reference
/// attributes cannot be interpreted; applications must list those variables.
pub fn Dataset::project(
  self : Dataset,
  names : Array[String],
  include_dependencies~ : Bool = true,
) -> Bytes raise CdfError {
  if names.is_empty() || names.length() > self.limits.header_items {
    raise Invalid(
      "projection requires a nonempty bounded list of variable names",
    )
  }
  let selected : Map[String, Bool] = Map([])
  let queue : Array[String] = []
  for name in names {
    let variable = self.find(name)
    if selected.contains(variable.name) {
      raise Invalid("projection repeats a variable name")
    }
    selected[variable.name] = true
    queue.push(variable.name)
  }
  let mut index = 0
  while index < queue.length() {
    let variable = self.find(queue[index])
    index += 1
    if include_dependencies {
      let references = variable_references(variable)
      for id in variable.dimensions {
        let dimension = self.dims[id]
        if self.vars.any(v => v.name == dimension.name && v.dimensions == [id]) {
          references.push(dimension.name)
        }
      }
      for reference in references {
        let dependency = self.find(reference)
        if !selected.contains(dependency.name) {
          selected[dependency.name] = true
          queue.push(dependency.name)
        }
      }
    }
  }
  let kept : Array[VariableInfo] = self.vars.filter(variable => {
    selected.contains(variable.name)
  })
  let used = Array::make(self.dims.length(), false)
  let mut total = 0L
  for variable in kept {
    let size = shape_count(variable.shape, self.limits.result_values.to_int64())
    if size > self.limits.result_values.to_int64() - total {
      raise ResourceLimit("projected variable values exceed aggregate budget")
    }
    total += size
    for id in variable.dimensions {
      used[id] = true
    }
  }
  let dimensions : Array[Dimension] = []
  let mapping = Array::make(self.dims.length(), -1)
  for id, dimension in self.dims {
    if used[id] {
      mapping[id] = dimensions.length()
      dimensions.push(dimension)
    }
  }
  let variables : Array[Variable] = kept.map(variable => {
    name: variable.name,
    data_type: variable.data_type,
    dimensions: variable.dimensions.map(id => mapping[id]),
    attributes: variable.attributes.map(copy_attribute),
    values: self.values(variable.name),
  })
  write_bytes(
    {
      format: self.format,
      dimensions,
      attributes: self.attributes(),
      variables,
    },
    limits=self.limits,
  )
}

///|
/// Replace a variable's attributes through a validated new-file transaction.
/// _FillValue remains storage metadata: changing it never rewrites existing data.
pub fn Dataset::with_variable_attributes(
  self : Dataset,
  name : String,
  attributes : Array[Attribute],
) -> Bytes raise CdfError {
  let selected = self.find(name)
  let document = self.document()
  for index, variable in document.variables {
    if variable.name == selected.name {
      document.variables[index] = {
        ..variable,
        attributes: attributes.map(copy_attribute),
      }
    }
  }
  write_bytes(document, limits=self.limits)
}

///|
/// Add a complete typed variable using existing dimension ids. Replacement is
/// explicit; empty values initialize the new variable from its fill value.
pub fn Dataset::with_variable(
  self : Dataset,
  variable : Variable,
  replace~ : Bool = false,
) -> Bytes raise CdfError {
  let name = checked_name(variable.name, self.limits)
  let document = self.document()
  let existing = document.variables.search_by(v => v.name == name)
  match existing {
    Some(index) => {
      if !replace {
        raise Invalid("variable already exists; replacement must be explicit")
      }
      document.variables[index] = { ..variable, name, }
    }
    None => document.variables.push({ ..variable, name, })
  }
  write_bytes(document, limits=self.limits)
}

///|
/// Import edited long-form raw CSV into a checked section. Original coordinate
/// columns must be retained. Validation finishes before a new file is returned.
pub fn Dataset::import_csv(
  self : Dataset,
  name : String,
  text : String,
  start : Array[Int64],
  count : Array[Int64],
  stride~ : Array[Int64] = [],
) -> Bytes raise CdfError {
  let variable = self.find(name)
  let step = if stride.is_empty() {
    Array::make(variable.shape.length(), 1L)
  } else {
    stride
  }
  let _ = validate_section(
    variable.shape,
    start,
    count,
    step,
    self.limits.result_values,
  )
  let block = parse_block_csv(
    text,
    variable.data_type,
    count,
    start~,
    stride=step,
  )
  self.replace_section(name, start, count, block.values, stride=step)
}