///|
fn edge_opt_length(tree : PhyloTree, a : Int32, b : Int32) -> Double? {
  if tree.arena[a].parent == Some(b) {
    tree.arena[a].length
  } else {
    tree.arena[b].length
  }
}

///|
/// Reroot a tree on an explicit outgroup bipartition and return an audited
/// TransformResult with Rooted semantics. Works on Rooted, Unrooted, and Unknown
/// trees, with or without branch lengths.
///
/// Validation order: EmptySelection, UnknownTaxon / DuplicateSelection in input
/// order, EmptyIngroup (all taxa selected), then NonMonophyleticOutgroup when no
/// undirected branch separates the outgroup from the remaining ingroup taxa.
/// When all branches along the separating path have known lengths, the new root
/// is placed at the exact BigInt midpoint of that path (reusing an internal
/// vertex on exact ties, or cutting an edge with witness split_edge and offset)
/// so all pairwise patristic distances are preserved. If any branch on the
/// separating path has an unknown length, the outgroup boundary edge is cut with
/// unknown incident lengths (offset = None). Dangling non-taxon stems are dropped
/// and degree-2 former roots are compacted with exact single rounding, returning
/// NumericOverflow if a retained compacted edge overflows binary64.
pub fn PhyloTree::reroot_outgroup(
  self : PhyloTree,
  outgroup : Array[String],
) -> Result[TransformResult, PhyloError] {
  if outgroup.is_empty() {
    return Err(EmptySelection)
  }
  let count = self.arena.length()
  let leaves : Map[String, Int32] = Map([])
  for id, node in self.arena {
    if node.children.is_empty() {
      leaves[node.label.unwrap()] = id
    }
  }
  let is_outgroup_leaf = Array::make(count, false)
  let seen : Map[String, Bool] = Map([])
  for taxon in outgroup {
    guard leaves.get(taxon) is Some(id) else { return Err(UnknownTaxon(taxon)) }
    if seen.contains(taxon) {
      return Err(DuplicateSelection(taxon))
    }
    seen[taxon] = true
    is_outgroup_leaf[id] = true
  }
  let total_leaves = leaves.length()
  let out_count = seen.length()
  if out_count == total_leaves {
    return Err(EmptyIngroup)
  }
  let in_count = total_leaves - out_count
  let order = traversal(self)
  let sub_total = Array::make(count, 0)
  let sub_out = Array::make(count, 0)
  for k = order.length() - 1; k >= 0; k = k - 1 {
    let id = order[k]
    let node = self.arena[id]
    if node.children.is_empty() {
      sub_total[id] = 1
      sub_out[id] = if is_outgroup_leaf[id] { 1 } else { 0 }
    } else {
      for child in node.children {
        sub_total[id] = sub_total[id] + sub_total[child]
        sub_out[id] = sub_out[id] + sub_out[child]
      }
    }
  }
  // Collect all undirected edges separating outgroup from ingroup, each directed
  // from the outgroup side toward the ingroup side.
  let next_map : Map[Int32, Int32] = Map([])
  let has_prev : Map[Int32, Bool] = Map([])
  let mut edge_count = 0
  for id, node in self.arena {
    if node.parent is Some(parent) {
      if sub_out[id] == out_count && sub_total[id] == out_count {
        next_map[id] = parent
        has_prev[parent] = true
        edge_count = edge_count + 1
      } else if sub_out[id] == 0 && sub_total[id] == in_count {
        next_map[parent] = id
        has_prev[id] = true
        edge_count = edge_count + 1
      }
    }
  }
  if edge_count == 0 {
    return Err(NonMonophyleticOutgroup)
  }
  let mut start = -1
  for u, _ in next_map {
    if !has_prev.contains(u) {
      start = u
      break
    }
  }
  let path : Array[Int32] = []
  let mut cur = start
  while true {
    path.push(cur)
    match next_map.get(cur) {
      Some(nxt) => cur = nxt
      None => break
    }
  }
  let mut all_known = true
  for i = 0; i + 1 < path.length(); i = i + 1 {
    if edge_opt_length(self, path[i], path[i + 1]) is None {
      all_known = false
      break
    }
  }
  let mut new_root = -1
  let mut new_root_pos = -1
  let mut cut_a = -1
  let mut cut_b = -1
  let mut offset : Double? = None
  if all_known {
    let zero = @bigint.BigInt::from_int(0)
    let mut remaining = zero
    for i = 0; i + 1 < path.length(); i = i + 1 {
      remaining = remaining +
        length_units(edge_opt_length(self, path[i], path[i + 1]).unwrap())
    }
    if remaining == zero {
      if path.length() >= 3 {
        new_root = path[1]
        new_root_pos = 1
      } else {
        cut_a = path[0]
        cut_b = path[1]
        offset = Some(0.0)
      }
    } else {
      for i = 0; i + 1 < path.length(); i = i + 1 {
        let a = path[i]
        let b = path[i + 1]
        let len = edge_opt_length(self, a, b).unwrap()
        let twice_len = length_units(len) << 1
        if remaining < twice_len {
          cut_a = a
          cut_b = b
          offset = Some(rounded_half_length(remaining))
          break
        }
        remaining = remaining - twice_len
        if remaining == zero {
          new_root = b
          new_root_pos = i + 1
          break
        }
      }
    }
  } else {
    cut_a = path[0]
    cut_b = path[1]
    offset = None
  }
  let extra = if new_root < 0 { 1 } else { 0 }
  if extra == 1 {
    new_root = count
  }
  let graph : Array[Array[(Int32, Double?)]] = Array::makei(count + extra, _ => {
    []
  })
  for id, node in self.arena {
    if node.parent is Some(p) {
      if extra == 1 &&
        ((id == cut_a && p == cut_b) || (id == cut_b && p == cut_a)) {
        continue
      }
      graph[id].push((p, node.length))
      graph[p].push((id, node.length))
    }
  }
  if extra == 1 {
    let (len_a, len_b) = match offset {
      Some(off) => {
        let full = edge_opt_length(self, cut_a, cut_b).unwrap()
        (Some(off), Some(full - off))
      }
      None => (None, None)
    }
    graph[new_root].push((cut_a, len_a))
    graph[cut_a].push((new_root, len_a))
    graph[new_root].push((cut_b, len_b))
    graph[cut_b].push((new_root, len_b))
  } else {
    // Ensure deterministic child order at the reused root: outgroup first,
    // ingroup second, followed by any dangling non-taxon stem neighbors.
    let out_neighbor = path[new_root_pos - 1]
    let in_neighbor = path[new_root_pos + 1]
    let reordered : Array[(Int32, Double?)] = []
    for item in graph[new_root] {
      if item.0 == out_neighbor {
        reordered.push(item)
      }
    }
    for item in graph[new_root] {
      if item.0 == in_neighbor {
        reordered.push(item)
      }
    }
    for item in graph[new_root] {
      if item.0 != out_neighbor && item.0 != in_neighbor {
        reordered.push(item)
      }
    }
    graph[new_root] = reordered
  }
  let arena : Array[Node] = Array::makei(count + extra, i => {
    let node = new_node(
      None,
      if i < count {
        self.arena[i].label
      } else {
        None
      },
    )
    if i < count {
      node.comments.append(self.arena[i].comments)
    }
    node
  })
  let visited = Array::make(count + extra, false)
  visited[new_root] = true
  let stack = [new_root]
  while !stack.is_empty() {
    let a = stack.pop().unwrap()
    for item in graph[a] {
      let (b, len) = item
      if !visited[b] {
        visited[b] = true
        arena[b].parent = Some(a)
        arena[b].length = len
        arena[a].children.push(b)
        stack.push(b)
      }
    }
  }
  let oriented = PhyloTree::{
    arena,
    root: new_root,
    rooting: Rooted,
    comments: self.comments.copy(),
  }
  let keep = Array::makei(count + extra, i => {
    i < count && self.arena[i].children.is_empty()
  })
  try {
    let (tree, mapping, paths) = compact(oriented, keep, count)
    Ok({
      tree,
      witness: {
        old_to_new: mapping,
        retained_taxa: tree.taxa(),
        edge_paths: paths,
        diameter_endpoints: [],
        diameter: None,
        split_edge: if extra == 1 {
          [cut_a, cut_b]
        } else {
          []
        },
        offset,
      },
    })
  } catch {
    Fault(error) => Err(error)
  }
}