///|
fn crc_zero(state : UInt32) -> UInt32 {
  (state >> 8) ^ crc_table[(state & 255U).reinterpret_as_int()]
}

///|
fn apply_crc_columns(columns : FixedArray[UInt32], state : UInt32) -> UInt32 {
  let mut bits = state
  let mut result = 0U
  let mut i = 0
  while bits != 0U {
    if (bits & 1U) != 0U {
      result = result ^ columns[i]
    }
    bits = bits >> 1
    i = i + 1
  }
  result
}

///|
/// Each column table advances a CRC by 2^i zero bytes over GF(2).
let crc_zero_powers : Array[FixedArray[UInt32]] = {
  let powers = [FixedArray::makei(32, i => crc_zero(1U << i))]
  for i = 1; i < 31; i = i + 1 {
    let last = powers[i - 1]
    powers.push(
      FixedArray::makei(32, bit => apply_crc_columns(last, last[bit])),
    )
  }
  powers
}

///|
fn advance_crc(state : UInt32, zeros : Int32) -> UInt32 {
  let mut shifted = state
  let mut count = zeros
  let mut i = 0
  while count > 0 {
    if (count & 1) != 0 {
      shifted = apply_crc_columns(crc_zero_powers[i], shifted)
    }
    count = count >> 1
    i = i + 1
  }
  shifted
}

///|
/// Contributions of each byte followed by the given number of zero bytes.
fn crc_byte_effects(zeros : Int32) -> FixedArray[UInt32] {
  if zeros == 0 {
    return crc_table
  }
  let table = FixedArray::make(256, 0U)
  for bit = 0; bit < 8; bit = bit + 1 {
    let half = 1 << bit
    let effect = advance_crc(crc_table[half], zeros)
    for i = 0; i < half; i = i + 1 {
      table[half + i] = table[i] ^ effect
    }
  }
  table
}

///|
/// Slide over every possible start, including overlapping windows. Two bounded
/// reads provide the outgoing and incoming bytes without buffering the file.
fn scan_windows(
  name : String,
  actual : UInt64,
  span : Int32,
  width : Int32,
  wanted : Map[UInt32, Map[Bytes, Array[Int32]]],
  outgoing : FixedArray[UInt32],
  found : (Int32, String, UInt64) -> Unit,
  reader : (String, UInt64, Int32) -> Bytes raise,
) -> Unit raise {
  if actual < span.to_uint64() {
    return
  }
  let padding = width - span
  let incoming = crc_byte_effects(padding)
  let confirm = (crc : UInt32, at : UInt64, hashes : Map[Bytes, Array[Int32]]) => {
    let data = read_exact(reader, name, at, span)
    let hash = md5(slice_at(data, 0, width))
    if hashes.remove_and_get(hash) is Some(indices) {
      for index in indices {
        found(index, name, at)
      }
      if hashes.is_empty() {
        wanted.remove(crc)
      }
    }
  }
  let first = read_exact(reader, name, 0UL, span)
  let mut raw = 0U
  for byte in first {
    raw = (raw >> 8) ^
      crc_table[((raw ^ byte.to_uint()) & 255U).reinterpret_as_int()]
  }
  raw = advance_crc(raw, padding)
  if wanted.get(raw) is Some(hashes) {
    confirm(raw, 0UL, hashes)
  }
  let last = actual - span.to_uint64()
  let mut start = 0UL
  while start < last && !wanted.is_empty() {
    let n = minimum(last - start, 262144UL).to_int()
    let leave = read_exact(reader, name, start, n)
    let enter = read_exact(reader, name, start + span.to_uint64(), n)
    for i = 0; i < n; i = i + 1 {
      // Advance the padded raw CRC, cancel the byte leaving the window and
      // insert the new byte just before the implicit zero padding.
      raw = crc_zero(raw) ^
        outgoing[leave[i].to_int()] ^
        incoming[enter[i].to_int()]
      if wanted.get(raw) is Some(hashes) {
        confirm(raw, start + i.to_uint64() + 1UL, hashes)
        if wanted.is_empty() {
          return
        }
      }
    }
    start = start + n.to_uint64()
  }
}

///|
priv struct SliceTargets {
  width : Int32
  crc_bias : UInt32
  spans : Map[Int32, Map[UInt32, Map[Bytes, Array[Int32]]]]
}

///|
fn SliceTargets::new(width : Int32) -> SliceTargets {
  {
    width,
    crc_bias: advance_crc(0xffffffffU, width) ^ 0xffffffffU,
    spans: Map([]),
  }
}

///|
fn SliceTargets::add(
  self : SliceTargets,
  entry : Member,
  slice : Int32,
  span : Int32,
  global_index : Int32,
) -> Unit {
  let p = 16 + slice * 20
  let crc = le32(entry.sums, p + 16) ^ self.crc_bias
  let hashes = self.spans
    .get_or_init(span, () => Map([]))
    .get_or_init(crc, () => Map([]))
  hashes
  .get_or_init(entry.sums[p:p + 16].to_owned(), () => [])
  .push(global_index)
}

///|
fn SliceTargets::search(
  self : SliceTargets,
  candidates : Array[(String, UInt64)],
  reader : (String, UInt64, Int32) -> Bytes raise,
  found : (Int32, String, UInt64) -> Unit,
) -> Unit raise {
  if self.spans.is_empty() {
    return
  }
  let outgoing = crc_byte_effects(self.width)
  for (key, length) in candidates {
    if self.spans.is_empty() {
      break
    }
    // Snapshot the keys because a confirmed match can exhaust a whole length.
    for span in self.spans.keys().to_array() {
      let wanted = self.spans[span]
      scan_windows(
        key,
        length,
        span,
        self.width,
        wanted,
        outgoing,
        found,
        reader,
      )
      if wanted.is_empty() {
        self.spans.remove(span)
      }
    }
  }
}

///|
fn resync_member(
  entry : Member,
  actual : UInt64,
  width : Int32,
  bad : Array[Int32],
  first_index : Int32,
  offsets : Array[UInt64?],
  reader : (String, UInt64, Int32) -> Bytes raise,
) -> Unit raise {
  // There are at most two window lengths per member: full slices and its tail.
  let targets = SliceTargets::new(width)
  for i in bad {
    let at = i.to_uint64() * width.to_uint64()
    let span = minimum(entry.length - at, width.to_uint64()).to_int()
    if actual < span.to_uint64() {
      continue
    }
    // A single edit shifts the surviving suffix by the file length difference.
    // Confirm this cheap end-relative position before starting a rolling scan.
    let from_end = entry.length - at
    if actual != entry.length && actual >= from_end {
      let candidate = actual - from_end
      let data = read_exact(reader, entry.name, candidate, span)
      if entry.matches_slice(i, slice_at(data, 0, width)) {
        offsets[first_index + i] = Some(candidate)
        continue
      }
    }
    targets.add(entry, i, span, first_index + i)
  }
  targets.search([(entry.name, actual)], reader, (i, _, at) => {
    offsets[i] = Some(at)
  })
}