// GF(256) decoding: Berlekamp–Massey locator and syndrome linear solve.

///|
fn gf_pow(a : Int, n : Int) -> Int {
  let mut out = 1
  for _ in 0.. Int {
  gf_mul(a, gf_pow(b, 254))
}

///|
fn syndromes(data : Array[Int], count : Int) -> Array[Int] {
  Array::makei(count, fn(i) {
    let x = gf_pow(2, i + 1)
    let mut y = 0
    for v in data {
      y = gf_mul(y, x) ^ v
    }
    y
  })
}

///|
fn correct_block(data : Array[Int], ecc : Int) -> Int raise DecodeError {
  let syn = syndromes(data, ecc)
  if syn.iter().all(fn(v) { v == 0 }) {
    return 0
  }
  let c = Array::make(ecc + 1, 0)
  let mut b = Array::make(ecc + 1, 0)
  c[0] = 1
  b[0] = 1
  let mut degree = 0
  let mut distance = 1
  let mut previous = 1
  for n in 0.. ecc {
    raise CorrectionFailed
  }
  let positions = []
  let roots = []
  for pos in 0..= 0; j = j - 1 {
      value = gf_mul(value, inverse) ^ c[j]
    }
    if value == 0 {
      positions.push(pos)
      roots.push(x)
    }
  }
  if positions.length() != degree {
    raise CorrectionFailed
  }
  let rows = Array::makei(degree, fn(i) {
    let row = roots.map(fn(x) { gf_pow(x, i + 1) })
    row.push(syn[i])
    row
  })
  for col in 0.. Int raise DecodeError {
  let mut corrected = 0
  for block in 0..