///|
fn read_word(data : Bytes, offset : Int32, little : Bool) -> Int32 {
  let a = data[offset].to_int()
  let b = data[offset + 1].to_int()
  let c = data[offset + 2].to_int()
  let d = data[offset + 3].to_int()
  if little {
    a | (b << 8) | (c << 16) | (d << 24)
  } else {
    (a << 24) | (b << 16) | (c << 8) | d
  }
}

///|
/// Decode one record's consecutive 64-byte frames. Set `little_endian` for
/// legacy miniSEED 2 payloads declared little-endian in blockette 1000.
/// The sample count includes X0. The corresponding packed d0 links records
/// and is skipped. After the declared count, Appendix B of SEED 2.4 allows
/// unused fields and words. The final decoded sample must match Xn.
///
/// A zero sample count returns an empty array. At most 16,777,216 samples
/// can be decoded in one call.
pub fn decode(
  encoding : Encoding,
  payload : Bytes,
  sample_count : Int32,
  little_endian~ : Bool = false,
) -> Array[Int32] raise CodecError {
  let samples = []
  integrate(encoding, payload, sample_count, little_endian, Some(samples))
  samples
}

///|
/// Validate the packed differences and Xn using the same rules as `decode`,
/// keeping only the running sample value and count.
pub fn verify(
  encoding : Encoding,
  payload : Bytes,
  sample_count : Int32,
  little_endian~ : Bool = false,
) -> Unit raise CodecError {
  integrate(encoding, payload, sample_count, little_endian, None)
}

///|
fn integrate(
  encoding : Encoding,
  payload : Bytes,
  sample_count : Int32,
  little_endian : Bool,
  samples : Array[Int32]?,
) -> Unit raise CodecError {
  if sample_count < 0 || sample_count > MaxSamples {
    raise InvalidSampleCount(sample_count)
  }
  if payload.length() % 64 != 0 || (sample_count > 0 && payload.is_empty()) {
    raise InvalidPayloadLength(payload.length())
  }
  if sample_count == 0 {
    return
  }
  let frames = payload.length() / 64
  let max_lanes = if encoding is Steim1 { 4 } else { 7 }
  let min_words = (sample_count - 1) / max_lanes + 1
  if frames < (min_words + 16) / 15 {
    raise InvalidSampleCount(sample_count)
  }
  let mut current = read_word(payload, 4, little_endian)
  let reverse = read_word(payload, 8, little_endian)
  let mut found = 0
  for frame in 0..> (32 - first_word * 2) != 0 {
      raise InvalidFrameControl(frame)
    }
    for slot in first_word..<16 {
      let code = (control >> ((15 - slot) * 2)) & 3
      if code == 0 {
        continue
      }
      // The four byte differences retain their physical order. In Steim-1
      // the two 16-bit integers are individually byte-swapped as well.
      let raw = read_word(
        payload,
        offset + slot * 4,
        little_endian && code != 1,
      )
      let word = if little_endian && encoding is Steim1 && code == 2 {
        (raw << 16) | ((raw >> 16) & 0xffff)
      } else {
        raw
      }
      let dnib = (word >> 30) & 3
      let (lanes, width) = match (encoding, code, dnib) {
        (_, 1, _) => (4, 8)
        (Steim1, 2, _) => (2, 16)
        (Steim1, 3, _) => (1, 32)
        (Steim2, 2, 1) => (1, 30)
        (Steim2, 2, 2) => (2, 15)
        (Steim2, 2, 3) => (3, 10)
        (Steim2, 3, 0) => (5, 6)
        (Steim2, 3, 1) => (6, 5)
        (Steim2, 3, 2) => (7, 4)
        _ => raise ReservedSteim2Mode(frame, slot, code, dnib)
      }
      for lane in 0.. 0 {
          let field = word >> ((lanes - 1 - lane) * width)
          let difference = field << (32 - width) >> (32 - width)
          // SEED integrates signed 32-bit values, including wrap at the rails.
          current = current + difference
        }
        if samples is Some(output) {
          output.push(current)
        }
        found += 1
        if found == sample_count {
          if current != reverse {
            raise ReverseConstantMismatch(reverse, current)
          }
          return
        }
      }
    }
  }
  raise TooFewDifferences(sample_count, found)
}