///|
priv struct Component {
  center : Point
  width : Int32
  height : Int32
  fill : Double
}

///|
pub struct Registration {
  corners : ArrayView[Point]
  orientation : Int32
  contrast : Double
  manual : Bool
  priv transform : Projection
}

///|
fn marker_mask(
  image : GrayImage,
  threshold : Int32,
  step : Int32,
) -> (Int32, Int32, FixedArray[Byte]) {
  let width = image.width / step
  let height = image.height / step
  let mask = FixedArray::makei(width * height, i => {
    let x = i % width * step + step / 2
    let y = i / width * step + step / 2
    if image.pixel(x, y) <= threshold {
      b'\x01'
    } else {
      b'\x00'
    }
  })
  (width, height, mask)
}

///|
fn fill_component(
  mask : FixedArray[Byte],
  width : Int32,
  height : Int32,
  start : Int32,
  step : Int32,
) -> Component {
  let queue = [start]
  mask[start] = b'\x00'
  let mut cursor = 0
  let mut left = width
  let mut right = 0
  let mut top = height
  let mut bottom = 0
  let mut sum_x = 0L
  let mut sum_y = 0L
  while cursor < queue.length() {
    let at = queue[cursor]
    cursor += 1
    let x = at % width
    let y = at / width
    left = @cmp.minimum(left, x)
    right = @cmp.maximum(right, x)
    top = @cmp.minimum(top, y)
    bottom = @cmp.maximum(bottom, y)
    sum_x += x.to_int64()
    sum_y += y.to_int64()
    if x > 0 {
      flood_add(mask, queue, at - 1)
    }
    if x + 1 < width {
      flood_add(mask, queue, at + 1)
    }
    if y > 0 {
      flood_add(mask, queue, at - width)
    }
    if y + 1 < height {
      flood_add(mask, queue, at + width)
    }
  }
  let w = right - left + 1
  let h = bottom - top + 1
  let count = queue.length().to_double()
  {
    center: {
      x: sum_x.to_double() / count * step.to_double() + (step / 2).to_double(),
      y: sum_y.to_double() / count * step.to_double() + (step / 2).to_double(),
    },
    width: w,
    height: h,
    fill: count / (w * h).to_double(),
  }
}

///|
fn flood_add(mask : FixedArray[Byte], queue : Array[Int32], at : Int32) -> Unit {
  if mask[at] != b'\x00' {
    mask[at] = b'\x00'
    queue.push(at)
  }
}

///|
fn marker_candidates(image : GrayImage, threshold : Int32) -> Array[Component] {
  let longest = @cmp.maximum(image.width, image.height)
  let step = @cmp.maximum(1, (longest + 1299) / 1300)
  let (width, height, mask) = marker_mask(image, threshold, step)
  let minimum = @cmp.maximum(4, @cmp.minimum(width, height) / 90)
  let maximum = @cmp.maximum(minimum, @cmp.minimum(width, height) / 8)
  let candidates : Array[Component] = []
  for i in 0..= minimum &&
        c.height >= minimum &&
        c.width <= maximum &&
        c.height <= maximum &&
        c.width.to_double() <= c.height.to_double() * 2.3 &&
        c.height.to_double() <= c.width.to_double() * 2.3 &&
        c.fill >= 0.54 {
        candidates.push(c)
      }
    }
  }
  candidates
}

///|
fn group_candidates(
  image : GrayImage,
  components : Array[Component],
) -> Array[Array[Component]] {
  let groups : Array[Array[Component]] = [[], [], [], []]
  let mid_x = image.width.to_double() * 0.5
  let mid_y = image.height.to_double() * 0.5
  let anchors = [
    point(0, 0),
    point(image.width - 1, 0),
    point(image.width - 1, image.height - 1),
    point(0, image.height - 1),
  ]
  for component in components {
    let side = if component.center.x < mid_x { 0 } else { 1 }
    let quadrant = if component.center.y < mid_y { side } else { 3 - side }
    groups[quadrant].push(component)
  }
  for i in 0..<4 {
    let anchor = anchors[i]
    groups[i].sort_by((a, b) => {
      let d1 = a.center.distance_squared(anchor)
      let d2 = b.center.distance_squared(anchor)
      d1.compare(d2)
    })
    while groups[i].length() > 4 {
      ignore(groups[i].pop())
    }
  }
  groups
}

///|
fn check_pilot_legacy(
  image : GrayImage,
  template : Template,
  transform : Projection,
) -> Double? {
  let mut darkest_light = 255.0
  let mut lightest_dark = 0.0
  for index in 0..<(CODE_BITS + 4) {
    guard patch_mean(image, transform, point(pilot_x(index), PILOT_Y), 2)
      is Some(value) else {
      return None
    }
    if pilot_bit(template, index) {
      lightest_dark = @cmp.maximum(lightest_dark, value)
    } else {
      darkest_light = @cmp.minimum(darkest_light, value)
    }
  }
  let contrast = darkest_light - lightest_dark
  if contrast >= 42.0 && lightest_dark <= 170.0 {
    Some(contrast)
  } else {
    None
  }
}

///|
fn check_pilot(
  image : GrayImage,
  template : Template,
  transform : Projection,
  legacy : Bool,
) -> Double? {
  if legacy {
    return check_pilot_legacy(image, template, transform)
  }
  let mut lightest_mark = 1.0
  let mut darkest_space = 0.0
  for index in 0..<(CODE_BITS + 4) {
    let x = pilot_x(index)
    guard patch_mean(image, transform, point(x, PILOT_Y), 2) is Some(level) &&
      patch_mean(image, transform, point(x, PILOT_Y - 9), 2) is Some(above) &&
      patch_mean(image, transform, point(x, PILOT_Y + 9), 2) is Some(below) else {
      return None
    }
    let paper = (above + below) / 2.0
    if paper < 25.0 || (above - below).abs() > paper * 0.60 {
      return None
    }
    let ink = clamp_unit((paper - level) / paper)
    if pilot_bit(template, index) {
      lightest_mark = @cmp.minimum(lightest_mark, ink)
    } else {
      darkest_space = @cmp.maximum(darkest_space, ink)
    }
  }
  if lightest_mark >= 0.40 && darkest_space <= 0.28 {
    Some((lightest_mark - darkest_space) * 255.0)
  } else {
    None
  }
}

///|
fn evaluate_quad(
  image : GrayImage,
  template : Template,
  corners : Array[Point],
  legacy : Bool,
) -> Registration? {
  if !convex_quad(corners) ||
    quad_area(corners) <
    image.width.to_double() * image.height.to_double() * 0.12 {
    return None
  }
  let mut best : Registration? = None
  for orientation in 0..<4 {
    let ordered = Array::makei(4, i => corners[(i + orientation) % 4])
    if projection(template_markers(), ordered) is Some(transform) &&
      check_pilot(image, template, transform, legacy) is Some(contrast) {
      if best is Some(previous) && previous.contrast > contrast {
        continue
      }
      best = Some({
        corners: ordered[:],
        orientation,
        contrast,
        manual: false,
        transform,
      })
    }
  }
  best
}

///|
pub fn register(
  image : GrayImage,
  template : Template,
) -> Registration raise MarkError {
  register_version(image, template, 3)
}

///|
fn register_version(
  image : GrayImage,
  template : Template,
  version : Int32,
) -> Registration raise MarkError {
  let legacy = version == 1
  let ranked : Array[(Registration, Double)] = []
  if image.width < 240 || image.height < 240 {
    raise RegistrationFailed("image needs at least 240 pixels on both axes")
  }
  let candidate_sets : Array[Array[Component]] = []
  for threshold in [95, 135, 165] {
    let candidates = marker_candidates(image, threshold)
    candidate_sets.push(candidates)
    let groups = group_candidates(image, candidates)
    let mut best : Registration? = None
    for upper_left in groups[0] {
      for upper_right in groups[1] {
        for lower_right in groups[2] {
          for lower_left in groups[3] {
            let markers = [upper_left, upper_right, lower_right, lower_left]
            let corners = markers.map(marker => marker.center)
            if evaluate_quad(image, template, corners, legacy) is Some(result) {
              if version == 3 {
                if registration_score(image, result, markers) is Some(score) {
                  ranked.push((result, score))
                }
                continue
              }
              if best is Some(previous) && previous.contrast >= result.contrast {
                continue
              }
              best = Some(result)
            }
          }
        }
      }
    }
    if best is Some(result) {
      return result
    }
  }
  if version == 3 {
    let candidate_limit = if ranked.is_empty() { 16 } else { 10 }
    for candidates in candidate_sets {
      ignore(
        search_corners(
          image,
          template,
          candidates,
          Some(ranked),
          candidate_limit,
        ),
      )
    }
    if choose_registration(image, ranked) is Some(result) {
      return result
    }
  } else if !legacy {
    let mut best : Registration? = None
    for candidates in candidate_sets {
      if search_corners(image, template, candidates, None, 16) is Some(result) {
        if best is None || result.contrast > best.unwrap().contrast {
          best = Some(result)
        }
      }
    }
    if best is Some(result) {
      return result
    }
  }
  raise RegistrationFailed(
    "four corner marks and matching template code were not found",
  )
}

///|
fn search_corners(
  image : GrayImage,
  template : Template,
  candidates : Array[Component],
  ranked : Array[(Registration, Double)]?,
  candidate_limit : Int32,
) -> Registration? {
  candidates.sort_by((a, b) => {
    let a_size = @cmp.minimum(a.width, a.height).to_double() * a.fill
    let b_size = @cmp.minimum(b.width, b.height).to_double() * b.fill
    b_size.compare(a_size)
  })
  let limit = @cmp.minimum(candidate_limit, candidates.length())
  let mut best : Registration? = None
  for a in 0.. marker.center)
            if evaluate_quad(image, template, corners, false) is Some(result) {
              if ranked is Some(results) {
                if registration_score(image, result, markers) is Some(score) {
                  results.push((result, score))
                }
                continue
              }
              if best is None || result.contrast > best.unwrap().contrast {
                best = Some(result)
              }
            }
          }
        }
      }
    }
  }
  best
}

///|
fn registration_score(
  image : GrayImage,
  result : Registration,
  markers : Array[Component],
) -> Double? {
  let step = @cmp.maximum(
    1,
    (@cmp.maximum(image.width, image.height) + 1299) / 1300,
  ).to_double()
  let mut fit = 0.0
  let half = MARKER_HALF.to_double()
  let expected = template_markers()
  for i in 0..<4 {
    let marker = markers[(i + result.orientation) % 4]
    let center = expected[i]
    let mut min_x = marker.center.x
    let mut max_x = min_x
    let mut min_y = marker.center.y
    let mut max_y = min_y
    for dx in [-half, half] {
      for dy in [-half, half] {
        guard result.transform.map(center.x + dx, center.y + dy) is Some(p) else {
          return None
        }
        min_x = @cmp.minimum(min_x, p.x)
        max_x = @cmp.maximum(max_x, p.x)
        min_y = @cmp.minimum(min_y, p.y)
        max_y = @cmp.maximum(max_y, p.y)
      }
    }
    let width = marker.width.to_double() * step
    let height = marker.height.to_double() * step
    let dx = (width - (max_x - min_x)).abs() / width
    let dy = (height - (max_y - min_y)).abs() / height
    if dx > 0.65 || dy > 0.65 {
      return None
    }
    fit += dx + dy
  }
  Some(result.contrast - fit * 10.0)
}

///|
fn choose_registration(
  image : GrayImage,
  candidates : Array[(Registration, Double)],
) -> Registration? raise MarkError {
  if candidates.is_empty() {
    return None
  }
  candidates.sort_by((a, b) => b.1.compare(a.1))
  let (best, score) = candidates[0]
  let tolerance = @cmp.minimum(image.width, image.height).to_double() * 0.015
  for (other, other_score) in candidates {
    if score - other_score > 8.0 {
      break
    }
    for i in 0..<4 {
      if Point::distance_squared(best.corners[i], other.corners[i]) >
        tolerance * tolerance {
        raise RegistrationFailed(
          "multiple plausible pages; select four corners manually",
        )
      }
    }
  }
  Some(best)
}

///|
pub fn Registration::rectify(
  self : Registration,
  image : GrayImage,
) -> GrayImage raise MarkError {
  warp(image, self.transform, PAGE_WIDTH, PAGE_HEIGHT)
}

///|
/// Use the four printed square centers in template order after automatic
/// registration fails. The printed layout code remains mandatory.
pub fn register_corners(
  image : GrayImage,
  template : Template,
  centers : Array[Point],
) -> Registration raise MarkError {
  register_corners_version(image, template, centers, false)
}

///|
fn register_corners_version(
  image : GrayImage,
  template : Template,
  centers : Array[Point],
  legacy : Bool,
) -> Registration raise MarkError {
  if centers.length() != 4 || !convex_quad(centers) {
    raise RegistrationFailed(
      "corners must form a clockwise convex quadrilateral",
    )
  }
  for center in centers {
    if !(center.x >= 0.0 &&
      center.y >= 0.0 &&
      center.x < image.width.to_double() &&
      center.y < image.height.to_double()) {
      raise RegistrationFailed("corner center lies outside the original image")
    }
  }
  guard projection(template_markers(), centers) is Some(transform) else {
    raise RegistrationFailed("corner centers do not define a stable transform")
  }
  guard check_pilot(image, template, transform, legacy) is Some(contrast) else {
    raise RegistrationFailed(
      "manual corner centers do not match the printed layout code",
    )
  }
  {
    corners: centers.copy()[:],
    orientation: 0,
    contrast,
    manual: true,
    transform,
  }
}