///|
fn normalized_attributes(
  attributes : Array[Attribute],
  format : Format,
  limits : Limits,
  budget : HeaderBudget,
) -> Array[Attribute] raise CdfError {
  if attributes.length() > budget.remaining {
    raise ResourceLimit("too many header entries")
  }
  budget.remaining -= attributes.length()
  let names : Map[String, Bool] = Map([])
  let output : Array[Attribute] = []
  for attribute in attributes {
    let name = checked_name(attribute.name, limits)
    if names.contains(name) {
      raise Invalid("duplicate normalized attribute name")
    }
    names[name] = true
    let _ = data_type(attribute.data_type.tag(), format)
    if attribute.values.length() > budget.value_remaining {
      raise ResourceLimit("aggregate attribute value count exceeds budget")
    }
    budget.value_remaining -= attribute.values.length()
    let values = attribute.values.map(value => {
      storage_value(value, attribute.data_type)
    })
    output.push({ ..attribute, name, values, })
  }
  output
}

///|
fn fill_for(variable : Variable) -> Value {
  for attribute in variable.attributes {
    if attribute.name == "_FillValue" {
      return attribute.values[0]
    }
  }
  variable.data_type.fill_value()
}

///|
fn normalized_document(
  document : Document,
  limits : Limits,
) -> Document raise CdfError {
  checked_limits(limits)
  let budget = HeaderBudget::{
    remaining: limits.header_items,
    value_remaining: limits.result_values,
  }
  if document.dimensions.length() > budget.remaining {
    raise ResourceLimit("too many dimensions")
  }
  budget.remaining -= document.dimensions.length()
  let dimension_names : Map[String, Bool] = Map([])
  let dimensions : Array[Dimension] = []
  let mut has_unlimited = false
  for dimension in document.dimensions {
    let name = checked_name(dimension.name, limits)
    if dimension_names.contains(name) ||
      dimension.length < 0L ||
      (!dimension.unlimited && dimension.length == 0L) ||
      (dimension.unlimited && has_unlimited) {
      raise Invalid("invalid or duplicate dimension")
    }
    if document.format != Cdf5 && dimension.length >= 4294967295L {
      raise Unsupported("dimension or record count requires CDF-5")
    }
    dimension_names[name] = true
    has_unlimited = has_unlimited || dimension.unlimited
    dimensions.push({ ..dimension, name, })
  }
  let attributes = normalized_attributes(
    document.attributes,
    document.format,
    limits,
    budget,
  )
  if document.variables.length() > budget.remaining {
    raise ResourceLimit("too many variables")
  }
  budget.remaining -= document.variables.length()
  let variable_names : Map[String, Bool] = Map([])
  let variables : Array[Variable] = []
  let mut total_values = 0L
  let mut record_variables = 0
  for variable in document.variables {
    let name = checked_name(variable.name, limits)
    if variable_names.contains(name) {
      raise Invalid("duplicate normalized variable name")
    }
    variable_names[name] = true
    let _ = data_type(variable.data_type.tag(), document.format)
    let shape = variable_shape(variable.dimensions, dimensions, limits)
    let count = shape_count(shape, limits.result_values.to_int64())
    if count > limits.result_values.to_int64() - total_values {
      raise ResourceLimit("document exceeds aggregate value budget")
    }
    total_values += count
    let attrs = normalized_attributes(
      variable.attributes,
      document.format,
      limits,
      budget,
    )
    validate_fill(attrs, variable.data_type)
    for value in variable.values {
      checked_value(value, variable.data_type)
    }
    let mut normalized = {
      ..variable,
      name,
      dimensions: variable.dimensions.copy(),
      attributes: attrs,
      values: variable.values.copy(),
    }
    if normalized.values.is_empty() && count > 0L {
      normalized = {
        ..normalized,
        values: Array::make(count.to_int(), fill_for(normalized)),
      }
    } else if normalized.values.length().to_int64() != count {
      raise Invalid("variable value count disagrees with its dimensions")
    }
    if !variable.dimensions.is_empty() &&
      dimensions[variable.dimensions[0]].unlimited {
      record_variables += 1
    }
    variables.push(normalized)
  }
  for dimension in dimensions {
    if dimension.unlimited && dimension.length > 0L && record_variables == 0 {
      raise Invalid(
        "nonzero record count requires at least one record variable",
      )
    }
  }
  { format: document.format, dimensions, attributes, variables, }
}

///|
fn encode_attributes(
  output : Encoder,
  attributes : Array[Attribute],
  format : Format,
  limits : Limits,
) -> Unit raise CdfError {
  output.uint(if attributes.is_empty() { 0UL } else { 12UL }, 4)
  output.count(attributes.length().to_int64(), format)
  for attribute in attributes {
    output.name(attribute.name, format, limits)
    output.uint(attribute.data_type.tag().to_uint64(), 4)
    output.count(attribute.values.length().to_int64(), format)
    for value in attribute.values {
      output.value(value, attribute.data_type)
    }
    output.padding()
  }
}

///|
fn document_records(document : Document) -> Int64 {
  for dimension in document.dimensions {
    if dimension.unlimited {
      return dimension.length
    }
  }
  0L
}

///|
fn is_record(variable : Variable, dims : Array[Dimension]) -> Bool {
  !variable.dimensions.is_empty() && dims[variable.dimensions[0]].unlimited
}

///|
fn encode_header(
  document : Document,
  sizes : Array[Int64],
  offsets : Array[Int64],
  limits : Limits,
) -> Encoder raise CdfError {
  let output = Encoder::{ data: [], limit: limits.file_bytes, }
  output.raw(b"CDF")
  output.uint(
    match document.format {
      Cdf1 => 1UL
      Cdf2 => 2UL
      Cdf5 => 5UL
    },
    1,
  )
  output.count(document_records(document), document.format)
  output.uint(if document.dimensions.is_empty() { 0UL } else { 10UL }, 4)
  output.count(document.dimensions.length().to_int64(), document.format)
  for dimension in document.dimensions {
    output.name(dimension.name, document.format, limits)
    output.count(
      if dimension.unlimited {
        0L
      } else {
        dimension.length
      },
      document.format,
    )
  }
  encode_attributes(output, document.attributes, document.format, limits)
  output.uint(if document.variables.is_empty() { 0UL } else { 11UL }, 4)
  output.count(document.variables.length().to_int64(), document.format)
  for index, variable in document.variables {
    output.name(variable.name, document.format, limits)
    output.count(variable.dimensions.length().to_int64(), document.format)
    for dimension in variable.dimensions {
      output.count(dimension.to_int64(), document.format)
    }
    encode_attributes(output, variable.attributes, document.format, limits)
    output.uint(variable.data_type.tag().to_uint64(), 4)
    output.count(sizes[index], document.format)
    output.uint(
      offsets[index].reinterpret_as_uint64(),
      if document.format == Cdf1 {
        4
      } else {
        8
      },
    )
  }
  output
}

///|
fn encode_values(
  output : Encoder,
  variable : Variable,
  start : Int32,
  count : Int32,
  padding : Bool,
) -> Unit raise CdfError {
  for index in start..<(start + count) {
    output.value(variable.values[index], variable.data_type)
  }
  if padding {
    let count = (4 - output.data.length() % 4) % 4
    if count > 0 {
      let fill = Encoder::{ data: [], limit: 8, }
      fill.value(fill_for(variable), variable.data_type)
      output.need(count)
      for index in 0.. Bytes raise CdfError {
  let document = normalized_document(document, limits)
  let count = document.variables.length()
  let sizes : Array[Int64] = []
  let slab_values : Array[Int32] = []
  let record_ids : Array[Int32] = []
  for index, variable in document.variables {
    let shape = variable_shape(variable.dimensions, document.dimensions, limits)
    let record = is_record(variable, document.dimensions)
    let slab_shape = if record { shape[1:].to_owned() } else { shape }
    let values = shape_count(slab_shape, limits.file_bytes.to_int64())
    let bytes = checked_product(
      values,
      variable.data_type.width().to_int64(),
      limits.file_bytes.to_int64(),
    )
    sizes.push(padded4(bytes))
    slab_values.push(values.to_int())
    if record {
      record_ids.push(index)
    }
  }
  let offsets = Array::make(count, 0L)
  let first_header = encode_header(document, sizes, offsets, limits)
  let mut position = first_header.data.length().to_int64()
  for index, variable in document.variables {
    if !is_record(variable, document.dimensions) {
      offsets[index] = position
      position += sizes[index]
    }
  }
  let record_base = position
  let mut record_step = 0L
  for index in record_ids {
    offsets[index] = record_base + record_step
    record_step += sizes[index]
  }
  if record_ids.length() == 1 {
    let index = record_ids[0]
    record_step = slab_values[index].to_int64() *
      document.variables[index].data_type.width().to_int64()
  }
  let record_bytes = checked_product(
    document_records(document),
    record_step,
    limits.file_bytes.to_int64(),
  )
  if position > limits.file_bytes.to_int64() - record_bytes {
    raise ResourceLimit("encoded file exceeds byte budget")
  }
  let output = encode_header(document, sizes, offsets, limits)
  for variable in document.variables {
    if !is_record(variable, document.dimensions) {
      encode_values(output, variable, 0, variable.values.length(), true)
    }
  }
  for record in 0.. 1,
      )
    }
  }
  Bytes::from_array(output.data[:])
}