///|
priv struct WordFormat {
  lanes : Int32
  bits : Int32
  control : Int32
  selector : Int32
}

///|
// Indexed by the number of consumed differences minus one. Steim-1 can use
// three of a four-byte word's lanes at the end of the record.
let steim1_formats : FixedArray[WordFormat] = [
  { lanes: 1, bits: 32, control: 3, selector: 0, },
  { lanes: 2, bits: 16, control: 2, selector: 0, },
  { lanes: 4, bits: 8, control: 1, selector: 0, },
  { lanes: 4, bits: 8, control: 1, selector: 0, },
]

///|
let steim2_formats : FixedArray[WordFormat] = [
  { lanes: 1, bits: 30, control: 2, selector: 1, },
  { lanes: 2, bits: 15, control: 2, selector: 2, },
  { lanes: 3, bits: 10, control: 2, selector: 3, },
  { lanes: 4, bits: 8, control: 1, selector: 0, },
  { lanes: 5, bits: 6, control: 3, selector: 0, },
  { lanes: 6, bits: 5, control: 3, selector: 1, },
  { lanes: 7, bits: 4, control: 3, selector: 2, },
]

///|
// Compute the minimum number of words for every reachable prefix. Retaining
// the last word's length at each sample lets the writer reconstruct the
// choices. Only the previous seven costs can enter the next word.
fn plan_words(
  encoding : Encoding,
  formats : FixedArray[WordFormat],
  samples : ArrayView[Int32],
  word_budget : Int32,
) -> (Array[Byte], Int32) {
  let over_budget = word_budget + 1
  let costs = FixedArray::make(8, over_budget)
  let widths = FixedArray::make(8, 0)
  costs[0] = 0
  let choices : Array[Byte] = []
  let mut last_take = 0
  let mut word_count = 0
  for i in 0.. 536870911L {
        break
      }
      step.to_int()
    } else {
      samples[i] - samples[i - 1]
    }
    let magnitude = if difference < 0 { difference.lnot() } else { difference }
    widths[i & 7] = 33 - magnitude.clz()
    let mut suffix_width = 0
    let mut exact_cost = over_budget
    let mut exact_take = 0
    let mut terminal_cost = over_budget
    let mut terminal_take = 0
    for take in 1..<=(i + 1).min(formats.length()) {
      let start = i + 1 - take
      suffix_width = suffix_width.max(widths[start & 7])
      let format = formats[take - 1]
      if suffix_width > format.bits {
        break
      }
      let cost = costs[start & 7] + 1
      if cost < terminal_cost {
        terminal_cost = cost
        terminal_take = take
      }
      // Only a completely filled word can precede more samples.
      if format.lanes == take && cost < exact_cost {
        exact_cost = cost
        exact_take = take
      }
    }
    if terminal_cost > word_budget {
      break
    }
    costs[(i + 1) & 7] = exact_cost
    choices.push(exact_take.to_byte())
    last_take = terminal_take
    word_count = terminal_cost
  }
  // The independent d0 fits the first word for every nonempty input.
  choices[choices.length() - 1] = last_take.to_byte()
  (choices, word_count)
}

///|
fn emit_frames(
  samples : ArrayView[Int32],
  formats : FixedArray[WordFormat],
  choices : Array[Byte],
  word_count : Int32,
) -> Bytes {
  // Two slots in frame zero hold X0 and Xn. Each frame has 15 slots.
  let frames = (word_count + 16) / 15
  let words = FixedArray::make(frames * 16, 0)
  words[1] = samples[0]
  words[2] = samples[choices.length() - 1]
  let mut end = choices.length()
  for number = word_count - 1; number >= 0; number = number - 1 {
    let take = choices[end - 1].to_int()
    let start = end - take
    let format = formats[take - 1]
    let mask = (0xffffffffU >> (32 - format.bits)).reinterpret_as_int()
    let mut packed = format.selector << 30
    for j in start.. (words[i / 4] >> (24 - i % 4 * 8)).to_byte())
}

///|
/// Encode the longest prefix fitting `max_frames` consecutive 64-byte
/// big-endian Steim frames and return the payload and consumed sample count.
/// The first difference is zero so each record can be decoded independently.
/// Steim-2 starts a new record at a step outside its signed 30-bit range.
/// Continue with `samples[count:]` to encode the rest of the series.
///
/// A positive budget is required. Empty input returns zero bytes and zero
/// samples. A single call consumes at most 16,777,216 samples.
pub fn encode(
  encoding : Encoding,
  samples : ArrayView[Int32],
  max_frames~ : Int32,
) -> (Bytes, Int32) raise CodecError {
  if max_frames <= 0 {
    raise InvalidFrameBudget(max_frames)
  }
  if samples.is_empty() {
    return (b"", 0)
  }
  let limit = samples.length().min(MaxSamples)
  let word_budget = max_frames.min((limit + 16) / 15) * 15 - 2
  let formats = if encoding is Steim1 { steim1_formats } else { steim2_formats }
  let (choices, word_count) = plan_words(
    encoding,
    formats,
    samples[:limit],
    word_budget,
  )
  (emit_frames(samples, formats, choices, word_count), choices.length())
}