///|
priv struct SheetRun {
  spec : SheetSpec
  layout : Layout
  transforms : Array[PlacementTransform]
  strategy_index : Int32
}

///|
priv struct StrategyTask {
  config : GeometryConfig
  spec : SheetSpec
  part_gaps : Array[Int64]
  pair_gaps : Array[(Int32, Int32, Int64)]
  margin : Int64
  sheet_margin : SheetMargin?
  hole_clearance : Int64
  join : GapJoin
  quality : Array[QualityRegion]
  strategy : SearchStrategy
  budget : SearchBudget
  suites : Array[SuiteSpec]
  rotations : Array[Int32]
  sheet_parts : Array[Part]
  fixed_candidates : Array[Candidate]
  preoccupied : @moonclip.Paths64
  strategy_index : Int32
  started_at : @bench.Timestamp
}

///|
/// Converts JSON into a nesting problem, quantizing fractional coordinates.
pub fn Problem::from_json(
  value : Json,
  precision? : Precision,
) -> Problem raise NestError {
  let config = json_config(precision)
  let (margin, sheet_margin) = parse_margin(
    json_field(value, "margin", config),
    config,
  )
  let gap = json_nonnegative(
    json_double(json_field(value, "gap", config), "gap", config),
    "gap",
    config,
  )
  let hole_clearance = match
    json_optional_field(value, "hole_clearance", config) {
    Some(Null) | None => 0.0
    Some(value) =>
      json_nonnegative(
        json_double(value, "hole_clearance", config),
        "hole_clearance",
        config,
      )
  }
  let sheets = parse_sheets(value, config)
  let sheet = match sheets {
    Some(specs) => specs[0].stock
    None => parse_sheet(json_field(value, "sheet", config), config)
  }
  let parts_json = json_array(
    json_field(value, "parts", config),
    "parts",
    config,
  )
  if parts_json.is_empty() {
    raise JsonError("parts must contain at least one part")
  }
  let parts = parts_json.mapi(fn(index, item) raise NestError {
    parse_part(item, index, config)
  })
  let pair_gaps = parse_pair_gaps(value, config, parts.length())
  let fixed = parse_fixed(value, config, parts.length())
  let preoccupied = parse_preoccupied(value, config)
  let quality_regions = parse_quality_regions(value, config, parts.length())
  let strategies = parse_strategies(value, config)
  let budget = parse_budget(value, config)
  let suites = parse_suites(value, config, parts.length())
  let machine = parse_machine(value, config)
  match machine {
    Some(machine) => {
      let stocks = match sheets {
        Some(specs) => specs.map(fn(spec) { spec.stock })
        None => [sheet]
      }
      validate_machine_envelope(machine, stocks, config)
    }
    None => ()
  }
  let cutting = parse_cutting(value, config)
  let production = parse_production(value, config, parts.length())
  Problem::validate(
    parts,
    margin,
    gap,
    precision=match precision {
      Some(value) => value
      None => { digits: None, }
    },
  )
  {
    sheet,
    sheets,
    parts,
    gap,
    margin,
    sheet_margin,
    pair_gaps,
    hole_clearance,
    join: parse_join(value, config),
    fixed,
    preoccupied,
    quality_regions,
    strategies,
    budget,
    suites,
    precision,
    rotations: json_rotations(value, config),
    machine,
    cutting,
    production,
  }
}

///|
/// Serializes a layout to the public JSON format.
pub fn Layout::to_json(
  self : Layout,
  precision? : Precision,
) -> Json raise NestError {
  let effective = match precision {
    Some(value) => value
    None => self.precision
  }
  let config = json_config(Some(effective))
  let nesting_config = json_config(Some(self.precision))
  let contours = json_grid_paths(self.contours, nesting_config, config)
  let placements = self.placements.map(fn(placement) raise NestError {
    {
      "instance_id": Json(placement.instance_id),
      "sheet": Json(placement.sheet),
      "part": Json(placement.part),
      "contour_index": Json(placement.contour_index),
      "rotation_degrees": Json(placement.rotation_degrees),
      "mirrored": Json(placement.mirrored),
      "source_x": json_number(placement.source_x, config),
      "source_y": json_number(placement.source_y, config),
      "origin": Json(
        match placement.origin {
          PlacementOrigin::Fixed => "fixed"
          PlacementOrigin::Searched => "searched"
        },
      ),
    }
  })
  let instances = self.instances.map(fn(instance) raise NestError {
    {
      "instance_id": Json(instance.instance_id),
      "part": Json(instance.part),
      "part_instance_index": Json(instance.part_instance_index),
      "sheet": Json(instance.sheet),
      "rotation_degrees": Json(instance.rotation_degrees),
      "mirrored": Json(instance.mirrored),
      "translation_x": json_number(
        instance.translation_x.to_double() / nesting_config.scale.to_double(),
        config,
      ),
      "translation_y": json_number(
        instance.translation_y.to_double() / nesting_config.scale.to_double(),
        config,
      ),
      "source_anchor_x": json_number(
        instance.source_anchor_x.to_double() / nesting_config.scale.to_double(),
        config,
      ),
      "source_anchor_y": json_number(
        instance.source_anchor_y.to_double() / nesting_config.scale.to_double(),
        config,
      ),
      "final_anchor_x": json_number(
        instance.final_anchor_x.to_double() / nesting_config.scale.to_double(),
        config,
      ),
      "final_anchor_y": json_number(
        instance.final_anchor_y.to_double() / nesting_config.scale.to_double(),
        config,
      ),
      "contour_indices": Json(instance.contour_indices),
      "hole_indices": Json(instance.hole_indices),
      "origin": Json(
        match instance.origin {
          PlacementOrigin::Fixed => "fixed"
          PlacementOrigin::Searched => "searched"
        },
      ),
    }
  })
  let unplaced_details = self.unplaced_details.map(fn(item) {
    {
      "part": Json(item.part),
      "part_instance_index": Json(item.part_instance_index),
      "reason": Json(
        match item.reason {
          UnplacedReason::TooLarge => "too_large"
          UnplacedReason::NoAllowedRotation => "no_allowed_rotation"
          UnplacedReason::NoAllowedSheet => "no_allowed_sheet"
          UnplacedReason::FixedConflict => "fixed_conflict"
          UnplacedReason::BudgetExhausted => "budget_exhausted"
          UnplacedReason::InvalidGeometry => "invalid_geometry"
          UnplacedReason::Occupied => "occupied"
        },
      ),
    }
  })
  let sheets = self.sheets.map(fn(sheet) raise NestError {
    {
      "sheet": Json(sheet.sheet),
      "sheet_id": Json(sheet.sheet_id),
      "instance_ids": Json(sheet.instance_ids),
      "contour_indices": Json(sheet.contour_indices),
      "width": json_number(sheet.width, config),
      "height": json_number(sheet.height, config),
      "material_area2": Json(sheet.material_area2),
      "used_area2": Json(sheet.used_area2),
      "hole_area2": Json(sheet.hole_area2),
      "gap_area2": Json(sheet.gap_area2),
      "unused_area2": Json(sheet.unused_area2),
      "utilization": json_number(sheet.utilization, config),
      "unused": json_grid_paths(sheet.unused, nesting_config, config),
    }
  })
  let part_totals = self.report.part_totals.map(fn(total) {
    {
      "part": Json(total.part),
      "count": Json(total.count),
      "area2": Json(total.area2),
    }
  })
  let strategy_summaries = self.strategy_summaries.map(fn(
    summary,
  ) raise NestError {
    {
      "sheet": Json(summary.sheet),
      "strategy_index": Json(summary.strategy_index),
      "placed": Json(summary.placed),
      "unplaced": Json(summary.unplaced),
      "area2": Json(summary.area2),
      "width": json_number(summary.width, config),
      "height": json_number(summary.height, config),
      "quality_cost": Json(summary.quality_cost),
    }
  })
  let suites = self.suites.map(fn(suite) {
    {
      "suite_id": Json(suite.suite_id),
      "outer_instance": Json(suite.outer_instance),
      "inner_instances": Json(suite.inner_instances),
    }
  })
  {
    "width": json_number(self.width, config),
    "height": json_number(self.height, config),
    "precision": Json(
      match self.precision.digits {
        Some(digits) => digits
        None => 3
      },
    ),
    "area2": Json(self.area2),
    "quality_cost": Json(self.quality_cost),
    "contours": Json(contours),
    "placements": Json(placements),
    "instances": Json(instances),
    "sheets": Json(sheets),
    "unplaced": Json(self.unplaced),
    "unplaced_details": Json(unplaced_details),
    "report": {
      "width": json_number(self.report.width, config),
      "height": json_number(self.report.height, config),
      "hole_area2": Json(self.report.hole_area2),
      "gap_area2": Json(self.report.gap_area2),
      "unused_area2": Json(self.report.unused_area2),
      "part_totals": Json(part_totals),
    },
    "compression": {
      "before_width": json_number(self.compression.before_width, config),
      "before_height": json_number(self.compression.before_height, config),
      "after_width": json_number(self.compression.after_width, config),
      "after_height": json_number(self.compression.after_height, config),
      "iterations": Json(self.compression.iterations),
    },
    "winning_strategy": Json(self.winning_strategy),
    "strategy_summaries": Json(strategy_summaries),
    "budget": {
      "max_nodes": Json(self.budget.max_nodes),
      "max_backtracks": Json(self.budget.max_backtracks),
      "beam_width": Json(self.budget.beam_width),
      "workers": Json(self.budget.workers),
      "max_milliseconds": Json(self.budget.max_milliseconds),
      "max_candidates": Json(self.budget.max_candidates),
    },
    "cache_hits": Json(self.cache_hits),
    "nodes": Json(self.nodes),
    "backtracks": Json(self.backtracks),
    "budget_exhausted": Json(self.budget_exhausted),
    "suites": Json(suites),
    "iterations": Json(self.iterations),
    "trials": Json(self.trials),
  }
}

///|
fn json_exact_paths(
  paths : Array[Array[(Double, Double)]],
  nesting_config : GeometryConfig,
) -> Json {
  Json(
    paths.map(fn(contour) {
      Json(
        contour.map(fn(point) {
          {
            "x": Json(point.0 / nesting_config.scale.to_double()),
            "y": Json(point.1 / nesting_config.scale.to_double()),
          }
        }),
      )
    }),
  )
}

///|
fn json_grid_paths(
  paths : @moonclip.Paths64,
  nesting_config : GeometryConfig,
  output_config : GeometryConfig,
) -> Json raise NestError {
  Json(
    paths.map(fn(contour) raise NestError {
      Json(
        contour.map(fn(point) raise NestError {
          let x = point.x.to_double() / nesting_config.scale.to_double()
          let y = point.y.to_double() / nesting_config.scale.to_double()
          {
            "x": json_number(x, output_config),
            "y": json_number(y, output_config),
          }
        }),
      )
    }),
  )
}

///|
fn path_winding(point : @moonclip.Point64, path : @moonclip.Path64) -> Int32 {
  let mut winding = 0
  if path.is_empty() {
    return winding
  }
  let mut previous = path[path.length() - 1]
  for current in path {
    let side = cross_value(previous, current, point)
    if previous.y <= point.y {
      if current.y > point.y && side > 0L {
        winding += 1
      }
    } else if current.y <= point.y && side < 0L {
      winding -= 1
    }
    previous = current
  }
  winding
}

///|
fn double_path_winding(point : DoublePoint, path : DoublePath) -> Int32 {
  let mut winding = 0
  if path.is_empty() {
    return winding
  }
  let mut previous = path[path.length() - 1]
  for current in path {
    let side = cross_double(
      current.0 - previous.0,
      current.1 - previous.1,
      point.0 - previous.0,
      point.1 - previous.1,
    )
    if previous.1 <= point.1 {
      if current.1 > point.1 && side > 0.0 {
        winding += 1
      }
    } else if current.1 <= point.1 && side < 0.0 {
      winding -= 1
    }
    previous = current
  }
  winding
}

///|
fn double_point_on_path_boundary(
  point : DoublePoint,
  path : DoublePath,
) -> Bool {
  if path.is_empty() {
    return false
  }
  let mut previous = path[path.length() - 1]
  for current in path {
    let side = cross_double(
      current.0 - previous.0,
      current.1 - previous.1,
      point.0 - previous.0,
      point.1 - previous.1,
    ).abs()
    if side <= 0.0000001 &&
      point.0 >= (if previous.0 < current.0 { previous.0 } else { current.0 }) &&
      point.0 <= (if previous.0 > current.0 { previous.0 } else { current.0 }) &&
      point.1 >= (if previous.1 < current.1 { previous.1 } else { current.1 }) &&
      point.1 <= (if previous.1 > current.1 { previous.1 } else { current.1 }) {
      return true
    }
    previous = current
  }
  false
}

///|
fn point_on_path_boundary(
  point : @moonclip.Point64,
  path : @moonclip.Path64,
) -> Bool {
  if path.is_empty() {
    return false
  }
  let mut previous = path[path.length() - 1]
  for current in path {
    if point_on_segment_value(point, previous, current) {
      return true
    }
    previous = current
  }
  false
}

///|
/// Tests forbidden-region membership using nonzero winding. Boundary-only
/// contact is not considered forbidden unless another contour covers it.
pub fn NoFitRegion::contains(
  self : NoFitRegion,
  point : @moonclip.Point64,
) -> Bool {
  if !self.exact_contours.is_empty() {
    let exact_point = (point.x.to_double(), point.y.to_double())
    if self.exact_contours.any(fn(contour) {
        double_point_on_path_boundary(exact_point, contour)
      }) {
      return false
    }
    let mut exact_winding = 0
    for contour in self.exact_contours {
      exact_winding += double_path_winding(exact_point, contour)
    }
    return exact_winding != 0
  }
  if self.contours.any(fn(contour) { point_on_path_boundary(point, contour) }) {
    return false
  }
  let mut winding = 0
  for contour in self.contours {
    winding += path_winding(point, contour)
  }
  winding != 0
}

///|
/// Serializes a complete no-fit region.
pub fn NoFitRegion::to_json(
  self : NoFitRegion,
  precision? : Precision,
) -> Json raise NestError {
  let effective = match precision {
    Some(value) => value
    None => self.precision
  }
  let config = json_config(Some(effective))
  let nesting_config = json_config(Some(self.precision))
  {
    "moving": Json(self.moving),
    "stationary": Json(self.stationary),
    "moving_degrees": Json(self.moving_degrees),
    "stationary_degrees": Json(self.stationary_degrees),
    "moving_mirrored": Json(self.moving_mirrored),
    "stationary_mirrored": Json(self.stationary_mirrored),
    "contours": json_grid_paths(self.contours, nesting_config, config),
    "exact_contours": json_exact_paths(self.exact_contours, nesting_config),
  }
}

///|
/// Serializes a representative no-fit polygon.
pub fn NoFitPolygon::to_json(
  self : NoFitPolygon,
  precision? : Precision,
) -> Json raise NestError {
  let effective = match precision {
    Some(value) => value
    None => self.precision
  }
  let config = json_config(Some(effective))
  let nesting_config = json_config(Some(self.precision))
  {
    "moving": Json(self.moving),
    "stationary": Json(self.stationary),
    "moving_degrees": Json(self.moving_degrees),
    "stationary_degrees": Json(self.stationary_degrees),
    "moving_mirrored": Json(self.moving_mirrored),
    "stationary_mirrored": Json(self.stationary_mirrored),
    "contour": json_grid_paths([self.contour], nesting_config, config),
  }
}

///|
/// Maps a point from input coordinates to sheet coordinates.
pub fn PlacementTransform::to_sheet(
  self : PlacementTransform,
  point : @moonclip.Point64,
) -> @moonclip.Point64 {
  let local_point = @moonclip.Point64::new(
    point.x - self.source_anchor_x,
    if self.mirrored {
      self.source_anchor_y - point.y
    } else {
      point.y - self.source_anchor_y
    },
  )
  let rotated = rotate_point(local_point, self.rotation_degrees)
  @moonclip.Point64::new(
    rotated.x - self.rotated_anchor_x + self.translation_x,
    rotated.y - self.rotated_anchor_y + self.translation_y,
  )
}

///|
/// Maps a point from input coordinates to normalized output coordinates.
pub fn PlacementTransform::to_output(
  self : PlacementTransform,
  point : @moonclip.Point64,
) -> @moonclip.Point64 {
  let sheet = self.to_sheet(point)
  @moonclip.Point64::new(
    sheet.x - self.output_origin_x,
    sheet.y - self.output_origin_y,
  )
}

///|
/// Maps a point from normalized output coordinates back to input coordinates.
/// Arbitrary-angle rotations use the same grid rounding as placement.
pub fn PlacementTransform::to_source(
  self : PlacementTransform,
  point : @moonclip.Point64,
) -> @moonclip.Point64 {
  let oriented = @moonclip.Point64::new(
    point.x + self.output_origin_x - self.translation_x + self.rotated_anchor_x,
    point.y + self.output_origin_y - self.translation_y + self.rotated_anchor_y,
  )
  let local_point = unrotate_point(oriented, self.rotation_degrees)
  @moonclip.Point64::new(
    local_point.x + self.source_anchor_x,
    if self.mirrored {
      self.source_anchor_y - local_point.y
    } else {
      local_point.y + self.source_anchor_y
    },
  )
}

///|
/// Renders the layout as a standalone SVG.
pub fn Layout::to_svg(
  self : Layout,
  precision? : Precision,
) -> String raise NestError {
  let effective = match precision {
    Some(value) => value
    None => self.precision
  }
  self.to_svg_with_extra(effective, "")
}

///|
fn Layout::to_svg_with_extra(
  self : Layout,
  precision : Precision,
  extra : String,
) -> String raise NestError {
  let config = json_config(Some(precision))
  let nesting_config = json_config(Some(self.precision))
  let width = json_nonnegative(self.width, "width", config)
  let height = json_nonnegative(self.height, "height", config)
  let palette = [
    "#2563eb", "#ea580c", "#059669", "#9333ea", "#db2777", "#0891b2",
  ]
  let body = StringBuilder()
  body.write_string(
    "\n",
  )
  body.write_string("\n")
  let placement_by_contour : Map[Int32, Placement] = Map([])
  for placement in self.placements {
    placement_by_contour[placement.contour_index] = placement
  }
  for i in 0.. palette[placement.part % palette.length()]
      None => "#475569"
    }
    body.write_string("\n")
  }
  body.write_string(extra)
  body.write_string("\n")
  body.to_string()
}

///|
/// Renders the layout with source anchors, local anchors and translation
/// vectors for every placed instance.
pub fn NestingResult::to_debug_svg(
  self : NestingResult,
  precision? : Precision,
) -> String raise NestError {
  let effective = match precision {
    Some(value) => value
    None => self.layout.precision
  }
  let config = json_config(Some(effective))
  let nesting_config = json_config(Some(self.layout.precision))
  let markers = StringBuilder()
  markers.write_string(
    "\n",
  )
  for transform in self.transforms {
    let source = transform.to_output(
      @moonclip.Point64::new(
        transform.source_anchor_x,
        transform.source_anchor_y,
      ),
    )
    let local_anchor = @moonclip.Point64::new(
      transform.translation_x - transform.output_origin_x,
      transform.translation_y - transform.output_origin_y,
    )
    let source_x = source.x.to_double() / nesting_config.scale.to_double()
    let source_y = source.y.to_double() / nesting_config.scale.to_double()
    let local_x = local_anchor.x.to_double() / nesting_config.scale.to_double()
    let local_y = local_anchor.y.to_double() / nesting_config.scale.to_double()
    markers.write_string(
      "\n",
    )
    markers.write_string(
      "\n",
    )
    markers.write_string(
      "\n",
    )
    markers.write_string(
      "instance \{transform.instance_id} source\n",
    )
    markers.write_string(
      "local\n",
    )
    markers.write_string(
      "translation\n",
    )
  }
  markers.write_string("\n")
  self.layout.to_svg_with_extra(effective, markers.to_string())
}

///|
/// Validates part geometry and quantities without a sheet.
pub fn Problem::validate(
  parts : Array[Part],
  margin : Double,
  gap : Double,
  precision~ : Precision,
) -> Unit raise NestError {
  let config = json_config(Some(precision))
  json_nonnegative(margin, "margin", config) |> ignore
  json_nonnegative(gap, "gap", config) |> ignore
  if parts.is_empty() {
    raise JsonError("parts must contain at least one part")
  }
  for i in 0.. ignore
    }
    if part.rules.min_quantity < 0 || part.rules.min_quantity > part.quantity {
      raise JsonError(
        "parts[\{i}].rules.min_quantity must be between zero and quantity",
      )
    }
    if part.rules.rotations is Some(rotations) && rotations.is_empty() {
      raise JsonError("parts[\{i}].rules.rotations must not be empty")
    }
    if part.rules.sheets is Some(sheets) && sheets.is_empty() {
      raise JsonError("parts[\{i}].rules.sheets must not be empty")
    }
    validate_region(part.contours, part.holes, "parts[\{i}]", config)
  }
}

///|
/// Returns structured geometry diagnostics for a problem without nesting it.
pub fn diagnose_geometry(
  problem : Problem,
) -> Array[GeometryDiagnostic] raise NestError {
  let config = json_config(problem.precision)
  let result = region_diagnostics(
    [problem.sheet.contour],
    problem.sheet.holes,
    "sheet",
    config,
  )
  for i in 0.. Json raise NestError {
  let config = json_config(problem.precision)
  let normalized = normalize_problem(problem, config)
  let output_config = json_config(
    Some(
      match problem.precision {
        Some(value) => value
        None => { digits: None, }
      },
    ),
  )
  let specs = match normalized.sheets {
    Some(specs) => specs
    None =>
      [{ id: "sheet-0", stock: normalized.sheet, quantity: 1, cost: 0.0, }]
  }
  let sheets = specs.map(fn(spec) raise NestError {
    {
      "id": Json(spec.id),
      "quantity": Json(spec.quantity),
      "cost": Json(spec.cost),
      "contour": json_grid_paths([spec.stock.contour], config, output_config),
      "holes": json_grid_paths(spec.stock.holes, config, output_config),
    }
  })
  let parts = normalized.parts.map(fn(part) raise NestError {
    {
      "id": Json(part.id),
      "quantity": Json(part.quantity),
      "contours": json_grid_paths(part.contours, config, output_config),
      "rules": {
        "rotations": Json(
          match part.rules.rotations {
            Some(value) => value
            None => []
          },
        ),
        "mirror": Json(part.rules.mirror),
        "priority": Json(part.rules.priority),
        "min_quantity": Json(part.rules.min_quantity),
      },
    }
  })
  {
    "precision": Json(
      match output_config.digits {
        Some(value) => value
        None => 3
      },
    ),
    "sheets": Json(sheets),
    "parts": Json(parts),
  }
}

///|
/// Nests parts deterministically and reports work counters through `stats`.
pub fn nest(problem : Problem, stats? : Array[Stats]) -> Layout raise NestError {
  match stats {
    Some(destination) => nest_with_transforms(problem, stats=destination).layout
    None => nest_with_transforms(problem).layout
  }
}

///|
fn layout_better(
  candidate : Layout,
  current : Layout,
  candidate_instances : Int32,
  current_instances : Int32,
) -> Bool {
  if candidate_instances != current_instances {
    return candidate_instances > current_instances
  }
  if candidate.area2 != current.area2 {
    return candidate.area2 > current.area2
  }
  let candidate_area = candidate.width * candidate.height
  let current_area = current.width * current.height
  if candidate_area != current_area {
    return candidate_area < current_area
  }
  candidate.quality_cost < current.quality_cost
}

///|
fn run_strategy_task(task : StrategyTask) -> (SheetRun, Stats) raise NestError {
  let engine : Engine = {
    config: task.config,
    sheet_contour: task.spec.stock.contour,
    sheet_holes: task.spec.stock.holes,
    part_gaps: task.part_gaps,
    pair_gaps: task.pair_gaps,
    margin: task.margin,
    sheet_margin: task.sheet_margin,
    hole_clearance: task.hole_clearance,
    join: task.join,
    quality: task.quality,
    strategy: task.strategy,
    budget: task.budget,
    suites: task.suites,
    cache: GeometryCache::default(),
    rotations: task.rotations,
    started_at: task.started_at,
    stats: {
      iterations: 0,
      placements: 0,
      rejected: 0,
      nfps: 0,
      candidates: 0,
      nodes: 0,
      backtracks: 0,
      budget_exhausted: false,
      elapsed_ms: 0.0,
      cache_hits: 0,
      started_at: @bench.monotonic_clock_start(),
    },
  }
  let (layout, transforms) = engine.run(
    task.sheet_parts,
    task.fixed_candidates,
    task.preoccupied,
  )
  (
    {
      spec: task.spec,
      layout,
      transforms,
      strategy_index: task.strategy_index,
    },
    engine.stats,
  )
}

///|
async fn run_strategy_tasks(
  tasks : Array[StrategyTask],
  parallel : Bool,
  workers : Int32,
) -> Array[(SheetRun, Stats)] raise NestError {
  if !parallel || workers <= 1 {
    return tasks.map(fn(task) raise NestError { run_strategy_task(task) })
  }
  let results : Array[Result[(SheetRun, Stats), NestError]?] = Array::make(
    tasks.length(),
    None,
  )
  let mut offset = 0
  while offset < tasks.length() {
    let finish = if offset + workers < tasks.length() {
      offset + workers
    } else {
      tasks.length()
    }
    try
      @async.with_task_group() <| group => {
        for i in offset.. {
            let task_result : Result[(SheetRun, Stats), NestError] = Ok(
              run_strategy_task(tasks[i]),
            ) catch {
              error => Err(error)
            }
            results[i] = Some(task_result)
          }
        }
      }
    catch {
      error => raise PlacementFailed(error.to_string())
    }
    offset = finish
  }
  let output : Array[(SheetRun, Stats)] = []
  for result in results {
    match result {
      Some(Ok(value)) => output.push(value)
      Some(Err(error)) => raise error
      None =>
        raise PlacementFailed("parallel strategy task did not return a result")
    }
  }
  output
}

///|
/// Nests parts and returns the reversible coordinate transform for every
/// placed instance. The layout is identical to `nest` for the same input.
pub fn nest_with_transforms(
  problem : Problem,
  stats? : Array[Stats],
) -> NestingResult raise NestError {
  nest_impl_sync(problem, stats, false)
}

///|
/// Async variant that can execute independent strategies in parallel.
pub async fn nest_with_transforms_async(
  problem : Problem,
  stats? : Array[Stats],
) -> NestingResult raise NestError {
  nest_impl(problem, stats, true)
}

///|
async fn nest_impl(
  problem : Problem,
  stats : Array[Stats]?,
  parallel : Bool,
) -> NestingResult raise NestError {
  let config = json_config(problem.precision)
  let normalized = normalize_problem(problem, config)
  Problem::validate(
    normalized.parts,
    normalized.margin,
    normalized.gap,
    precision=match problem.precision {
      Some(value) => value
      None => { digits: None, }
    },
  )
  let rotations = rotation_angles(normalized.rotations)
  if rotations.is_empty() {
    raise PlacementFailed("rotations.step_degrees must be zero or divide 90")
  }
  let global_gap = round_away(normalized.gap * config.scale.to_double()).to_int64()
  let part_gaps = normalized.parts.map(fn(part) {
    match part.gap {
      Some(value) => round_away(value * config.scale.to_double()).to_int64()
      None => global_gap
    }
  })
  let pair_gaps = normalized.pair_gaps.map(fn(pair) {
    (
      pair.first,
      pair.second,
      round_away(pair.gap * config.scale.to_double()).to_int64(),
    )
  })
  let specs = match normalized.sheets {
    Some(specs) => specs
    None =>
      [{ id: "sheet-0", stock: normalized.sheet, quantity: 1, cost: 0.0, }]
  }
  let mut total_sheets = 0
  for spec in specs {
    total_sheets += spec.quantity
  }
  for fixed in normalized.fixed {
    if fixed.sheet >= total_sheets {
      raise PlacementFailed("fixed placement references an unknown sheet")
    }
    if normalized.parts[fixed.part].rules.sheets is Some(sheets) &&
      !sheets.contains(fixed.sheet) {
      raise PlacementFailed("fixed placement uses a disallowed sheet")
    }
  }
  for region in normalized.preoccupied {
    if region.sheet >= total_sheets {
      raise PlacementFailed("preoccupied region references an unknown sheet")
    }
  }
  for region in normalized.quality_regions {
    if region.sheet >= total_sheets {
      raise PlacementFailed("quality region references an unknown sheet")
    }
  }
  let fixed_counts : Array[Int32] = Array::make(normalized.parts.length(), 0)
  for fixed in normalized.fixed {
    fixed_counts[fixed.part] += 1
  }
  let remaining = normalized.parts.mapi(fn(index, part) raise NestError {
    let count = part.quantity - fixed_counts[index]
    if count < 0 {
      raise PlacementFailed("fixed placements exceed part quantity")
    }
    count
  })
  let runs : Array[SheetRun] = []
  let strategies = match normalized.strategies {
    Some(value) => value
    None => [SearchStrategy::default()]
  }
  let strategy_summaries : Array[StrategySummary] = []
  let strategy_wins : Array[Int32] = Array::make(strategies.length(), 0)
  let total_stats : Stats = {
    iterations: 0,
    placements: 0,
    rejected: 0,
    nfps: 0,
    candidates: 0,
    nodes: 0,
    backtracks: 0,
    budget_exhausted: false,
    elapsed_ms: 0.0,
    cache_hits: 0,
    started_at: @bench.monotonic_clock_start(),
  }
  let mut physical_sheet = 0
  for spec in specs {
    for _ in 0.. sheets.contains(physical_sheet)
          None => true
        }
        {
          id: part.id,
          quantity: if allowed {
            remaining[index]
          } else {
            0
          },
          contours: part.contours,
          holes: part.holes,
          gap: part.gap,
          rules: part.rules,
        }
      })
      let tasks = strategies.mapi(fn(strategy_index, strategy) {
        {
          config,
          spec,
          part_gaps,
          pair_gaps,
          margin: round_away(normalized.margin * config.scale.to_double()).to_int64(),
          sheet_margin: normalized.sheet_margin,
          hole_clearance: round_away(
            normalized.hole_clearance * config.scale.to_double(),
          ).to_int64(),
          join: normalized.join,
          quality: normalized.quality_regions.filter(fn(region) {
            region.sheet == physical_sheet
          }),
          strategy,
          budget: normalized.budget,
          suites: normalized.suites,
          rotations,
          sheet_parts,
          fixed_candidates,
          preoccupied: preoccupied_paths,
          strategy_index,
          started_at: total_stats.started_at,
        }
      })
      let task_results = run_strategy_tasks(
        tasks,
        parallel,
        normalized.budget.workers,
      )
      let mut best : SheetRun? = None
      let mut best_index = 0
      for result in task_results {
        let (run, engine_stats) = result
        let strategy_index = run.strategy_index
        strategy_summaries.push({
          sheet: physical_sheet,
          strategy_index,
          placed: run.transforms.length(),
          unplaced: run.layout.unplaced.length(),
          area2: run.layout.area2,
          width: run.layout.width,
          height: run.layout.height,
          quality_cost: run.layout.quality_cost,
        })
        total_stats.iterations += engine_stats.iterations
        total_stats.placements += engine_stats.placements
        total_stats.rejected += engine_stats.rejected
        total_stats.nfps += engine_stats.nfps
        total_stats.candidates += engine_stats.candidates
        total_stats.cache_hits += engine_stats.cache_hits
        total_stats.nodes += engine_stats.nodes
        total_stats.backtracks += engine_stats.backtracks
        total_stats.budget_exhausted = total_stats.budget_exhausted ||
          engine_stats.budget_exhausted
        if best is None ||
          layout_better(
            run.layout,
            best.unwrap().layout,
            run.transforms.length(),
            best.unwrap().transforms.length(),
          ) {
          best = Some(run)
          best_index = strategy_index
        }
      }
      let best = best.unwrap()
      let unplaced_counts : Array[Int32] = Array::make(
        normalized.parts.length(),
        0,
      )
      for part_index in best.layout.unplaced {
        unplaced_counts[part_index] += 1
      }
      for i in 0.. sheets.contains(physical_sheet)
          None => true
        }
        if allowed {
          remaining[i] = unplaced_counts[i]
        }
      }
      runs.push(best)
      strategy_wins[best_index] += 1
      physical_sheet += 1
    }
  }
  let placed_counts : Array[Int32] = Array::make(normalized.parts.length(), 0)
  for run in runs {
    for transform in run.transforms {
      placed_counts[transform.part] += 1
    }
  }
  for i in 0.. strategy_wins[winning_strategy] {
      winning_strategy = i
    }
  }
  total_stats.elapsed_ms = @bench.monotonic_clock_end(total_stats.started_at) /
    1000.0
  let result = combine_sheet_runs(
    runs, remaining, normalized, config, total_stats, winning_strategy, strategy_summaries,
  )
  if stats is Some(destination) {
    destination.push(total_stats)
  }
  result
}

///|
fn nest_impl_sync(
  problem : Problem,
  stats : Array[Stats]?,
  _parallel : Bool,
) -> NestingResult raise NestError {
  let config = json_config(problem.precision)
  let normalized = normalize_problem(problem, config)
  Problem::validate(
    normalized.parts,
    normalized.margin,
    normalized.gap,
    precision=match problem.precision {
      Some(value) => value
      None => { digits: None, }
    },
  )
  let rotations = rotation_angles(normalized.rotations)
  if rotations.is_empty() {
    raise PlacementFailed("rotations.step_degrees must be zero or divide 90")
  }
  let global_gap = round_away(normalized.gap * config.scale.to_double()).to_int64()
  let part_gaps = normalized.parts.map(fn(part) {
    match part.gap {
      Some(value) => round_away(value * config.scale.to_double()).to_int64()
      None => global_gap
    }
  })
  let pair_gaps = normalized.pair_gaps.map(fn(pair) {
    (
      pair.first,
      pair.second,
      round_away(pair.gap * config.scale.to_double()).to_int64(),
    )
  })
  let specs = match normalized.sheets {
    Some(specs) => specs
    None =>
      [{ id: "sheet-0", stock: normalized.sheet, quantity: 1, cost: 0.0, }]
  }
  let mut total_sheets = 0
  for spec in specs {
    total_sheets += spec.quantity
  }
  for fixed in normalized.fixed {
    if fixed.sheet >= total_sheets {
      raise PlacementFailed("fixed placement references an unknown sheet")
    }
    if normalized.parts[fixed.part].rules.sheets is Some(sheets) &&
      !sheets.contains(fixed.sheet) {
      raise PlacementFailed("fixed placement uses a disallowed sheet")
    }
  }
  for region in normalized.preoccupied {
    if region.sheet >= total_sheets {
      raise PlacementFailed("preoccupied region references an unknown sheet")
    }
  }
  for region in normalized.quality_regions {
    if region.sheet >= total_sheets {
      raise PlacementFailed("quality region references an unknown sheet")
    }
  }
  let fixed_counts : Array[Int32] = Array::make(normalized.parts.length(), 0)
  for fixed in normalized.fixed {
    fixed_counts[fixed.part] += 1
  }
  let remaining = normalized.parts.mapi(fn(index, part) raise NestError {
    let count = part.quantity - fixed_counts[index]
    if count < 0 {
      raise PlacementFailed("fixed placements exceed part quantity")
    }
    count
  })
  let runs : Array[SheetRun] = []
  let strategies = match normalized.strategies {
    Some(value) => value
    None => [SearchStrategy::default()]
  }
  let strategy_summaries : Array[StrategySummary] = []
  let strategy_wins : Array[Int32] = Array::make(strategies.length(), 0)
  let total_stats : Stats = {
    iterations: 0,
    placements: 0,
    rejected: 0,
    nfps: 0,
    candidates: 0,
    nodes: 0,
    backtracks: 0,
    budget_exhausted: false,
    elapsed_ms: 0.0,
    cache_hits: 0,
    started_at: @bench.monotonic_clock_start(),
  }
  let mut physical_sheet = 0
  for spec in specs {
    for _ in 0.. sheets.contains(physical_sheet)
          None => true
        }
        {
          id: part.id,
          quantity: if allowed {
            remaining[index]
          } else {
            0
          },
          contours: part.contours,
          holes: part.holes,
          gap: part.gap,
          rules: part.rules,
        }
      })
      let tasks = strategies.mapi(fn(strategy_index, strategy) {
        {
          config,
          spec,
          part_gaps,
          pair_gaps,
          margin: round_away(normalized.margin * config.scale.to_double()).to_int64(),
          sheet_margin: normalized.sheet_margin,
          hole_clearance: round_away(
            normalized.hole_clearance * config.scale.to_double(),
          ).to_int64(),
          join: normalized.join,
          quality: normalized.quality_regions.filter(fn(region) {
            region.sheet == physical_sheet
          }),
          strategy,
          budget: normalized.budget,
          suites: normalized.suites,
          rotations,
          sheet_parts,
          fixed_candidates,
          preoccupied: preoccupied_paths,
          strategy_index,
          started_at: total_stats.started_at,
        }
      })
      let task_results = tasks.map(fn(task) raise NestError {
        run_strategy_task(task)
      })
      let mut best : SheetRun? = None
      let mut best_index = 0
      for result in task_results {
        let (run, engine_stats) = result
        let strategy_index = run.strategy_index
        strategy_summaries.push({
          sheet: physical_sheet,
          strategy_index,
          placed: run.transforms.length(),
          unplaced: run.layout.unplaced.length(),
          area2: run.layout.area2,
          width: run.layout.width,
          height: run.layout.height,
          quality_cost: run.layout.quality_cost,
        })
        total_stats.iterations += engine_stats.iterations
        total_stats.placements += engine_stats.placements
        total_stats.rejected += engine_stats.rejected
        total_stats.nfps += engine_stats.nfps
        total_stats.candidates += engine_stats.candidates
        total_stats.cache_hits += engine_stats.cache_hits
        total_stats.nodes += engine_stats.nodes
        total_stats.backtracks += engine_stats.backtracks
        total_stats.budget_exhausted = total_stats.budget_exhausted ||
          engine_stats.budget_exhausted
        if best is None ||
          layout_better(
            run.layout,
            best.unwrap().layout,
            run.transforms.length(),
            best.unwrap().transforms.length(),
          ) {
          best = Some(run)
          best_index = strategy_index
        }
      }
      let best = best.unwrap()
      let unplaced_counts : Array[Int32] = Array::make(
        normalized.parts.length(),
        0,
      )
      for part_index in best.layout.unplaced {
        unplaced_counts[part_index] += 1
      }
      for i in 0.. sheets.contains(physical_sheet)
          None => true
        }
        if allowed {
          remaining[i] = unplaced_counts[i]
        }
      }
      runs.push(best)
      strategy_wins[best_index] += 1
      physical_sheet += 1
    }
  }
  let placed_counts : Array[Int32] = Array::make(normalized.parts.length(), 0)
  for run in runs {
    for transform in run.transforms {
      placed_counts[transform.part] += 1
    }
  }
  for i in 0.. strategy_wins[winning_strategy] {
      winning_strategy = i
    }
  }
  total_stats.elapsed_ms = @bench.monotonic_clock_end(total_stats.started_at) /
    1000.0
  let result = combine_sheet_runs(
    runs, remaining, normalized, config, total_stats, winning_strategy, strategy_summaries,
  )
  if stats is Some(destination) {
    destination.push(total_stats)
  }
  result
}

///|
fn part_gap_for_report(
  problem : Problem,
  config : GeometryConfig,
  part : Int32,
) -> Int64 {
  match problem.parts[part].gap {
    Some(value) => round_away(value * config.scale.to_double()).to_int64()
    None => round_away(problem.gap * config.scale.to_double()).to_int64()
  }
}

///|
fn unplaced_reason(
  problem : Problem,
  runs : Array[SheetRun],
  part_index : Int32,
) -> UnplacedReason {
  let part = problem.parts[part_index]
  let allowed_sheets = match part.rules.sheets {
    Some(sheets) => sheets
    None => Array::makei(runs.length(), fn(index) { index })
  }
  let mut has_sheet = false
  for sheet in allowed_sheets {
    if sheet >= 0 && sheet < runs.length() {
      has_sheet = true
      break
    }
  }
  if !has_sheet {
    return UnplacedReason::NoAllowedSheet
  }
  let rotations = match part.rules.rotations {
    Some(value) => value
    None => rotation_angles(problem.rotations)
  }
  if rotations.is_empty() {
    return UnplacedReason::NoAllowedRotation
  }
  for sheet in allowed_sheets {
    if sheet < 0 || sheet >= runs.length() {
      continue
    }
    let (sheet_min_x, sheet_min_y, sheet_max_x, sheet_max_y) = paths_bounds([
      runs[sheet].spec.stock.contour,
    ])
    for degrees in rotations {
      for mirrored in (if part.rules.mirror { [false, true] } else { [false] }) {
        let orientation = oriented_part_at(part, part_index, degrees, mirrored)
        let width = orientation.bounds.2 - orientation.bounds.0
        let height = orientation.bounds.3 - orientation.bounds.1
        if width <= sheet_max_x - sheet_min_x &&
          height <= sheet_max_y - sheet_min_y {
          return UnplacedReason::Occupied
        }
      }
    }
  }
  UnplacedReason::TooLarge
}

///|
fn point_in_ring_doubled(
  x2 : Int64,
  y2 : Int64,
  path : @moonclip.Path64,
) -> Bool {
  let mut inside = false
  let mut previous = path[path.length() - 1]
  for current in path {
    let dx = current.x - previous.x
    let dy = current.y - previous.y
    let side = dx * (y2 - 2L * previous.y) - dy * (x2 - 2L * previous.x)
    if (2L * previous.y > y2) != (2L * current.y > y2) {
      if (current.y > previous.y && side > 0L) ||
        (current.y < previous.y && side < 0L) {
        inside = !inside
      }
    }
    previous = current
  }
  inside
}

///|
fn point_in_region_doubled(
  region : @moonclip.Paths64,
  x2 : Int64,
  y2 : Int64,
) -> Bool {
  let mut inside = false
  for path in region {
    if point_in_ring_doubled(x2, y2, path) {
      inside = !inside
    }
  }
  inside
}

///|
fn paths_are_orthogonal(paths : @moonclip.Paths64) -> Bool {
  for path in paths {
    for i in 0.. Bool {
  let xs : Array[Int64] = []
  let ys : Array[Int64] = []
  for paths in [first, second] {
    for path in paths {
      for point in path {
        if !xs.contains(point.x) {
          xs.push(point.x)
        }
        if !ys.contains(point.y) {
          ys.push(point.y)
        }
      }
    }
  }
  xs.sort()
  ys.sort()
  for j in 0..<(ys.length() - 1) {
    for i in 0..<(xs.length() - 1) {
      let x2 = xs[i] + xs[i + 1]
      let y2 = ys[j] + ys[j + 1]
      if point_in_region_doubled(first, x2, y2) &&
        point_in_region_doubled(second, x2, y2) {
        return true
      }
    }
  }
  false
}

///|
fn orthogonal_contains(
  outer : @moonclip.Paths64,
  inner : @moonclip.Paths64,
) -> Bool {
  let xs : Array[Int64] = []
  let ys : Array[Int64] = []
  for paths in [outer, inner] {
    for path in paths {
      for point in path {
        if !xs.contains(point.x) {
          xs.push(point.x)
        }
        if !ys.contains(point.y) {
          ys.push(point.y)
        }
      }
    }
  }
  xs.sort()
  ys.sort()
  for j in 0..<(ys.length() - 1) {
    for i in 0..<(xs.length() - 1) {
      let x2 = xs[i] + xs[i + 1]
      let y2 = ys[j] + ys[j + 1]
      if point_in_region_doubled(inner, x2, y2) &&
        !point_in_region_doubled(outer, x2, y2) {
        return false
      }
    }
  }
  true
}

///|
fn orthogonal_cells(
  region : @moonclip.Paths64,
) -> Array[(Int64, Int64, Int64, Int64)] {
  let xs : Array[Int64] = []
  let ys : Array[Int64] = []
  for path in region {
    for point in path {
      if !xs.contains(point.x) {
        xs.push(point.x)
      }
      if !ys.contains(point.y) {
        ys.push(point.y)
      }
    }
  }
  xs.sort()
  ys.sort()
  let cells : Array[(Int64, Int64, Int64, Int64)] = []
  for j in 0..<(ys.length() - 1) {
    for i in 0..<(xs.length() - 1) {
      if point_in_region_doubled(region, xs[i] + xs[i + 1], ys[j] + ys[j + 1]) {
        cells.push((xs[i], ys[j], xs[i + 1], ys[j + 1]))
      }
    }
  }
  cells
}

///|
fn merge_rectangles(
  rectangles : Array[(Int64, Int64, Int64, Int64)],
) -> Array[(Int64, Int64, Int64, Int64)] {
  let result = rectangles
  let mut changed = true
  while changed {
    changed = false
    let mut i = 0
    while i < result.length() && !changed {
      let mut j = i + 1
      while j < result.length() {
        let a = result[i]
        let b = result[j]
        let merged = if a.0 == b.0 && a.2 == b.2 && (a.3 == b.1 || b.3 == a.1) {
          Some(
            (
              a.0,
              if a.1 < b.1 {
                a.1
              } else {
                b.1
              },
              a.2,
              if a.3 > b.3 {
                a.3
              } else {
                b.3
              },
            ),
          )
        } else if a.1 == b.1 && a.3 == b.3 && (a.2 == b.0 || b.2 == a.0) {
          Some(
            (
              if a.0 < b.0 {
                a.0
              } else {
                b.0
              },
              a.1,
              if a.2 > b.2 {
                a.2
              } else {
                b.2
              },
              a.3,
            ),
          )
        } else {
          None
        }
        if merged is Some(value) {
          result[i] = value
          ignore(result.remove(j))
          changed = true
          break
        }
        j += 1
      }
      if !changed {
        i += 1
      }
    }
  }
  result
}

///|
fn orthogonal_union_paths(
  rectangles : Array[(Int64, Int64, Int64, Int64)],
) -> @moonclip.Paths64 {
  if rectangles.is_empty() {
    return []
  }
  let xs : Array[Int64] = []
  let ys : Array[Int64] = []
  for rectangle in rectangles {
    for x in [rectangle.0, rectangle.2] {
      if !xs.contains(x) {
        xs.push(x)
      }
    }
    for y in [rectangle.1, rectangle.3] {
      if !ys.contains(y) {
        ys.push(y)
      }
    }
  }
  xs.sort()
  ys.sort()
  let covered = fn(i : Int32, j : Int32) {
    if i < 0 || j < 0 || i >= xs.length() - 1 || j >= ys.length() - 1 {
      false
    } else {
      let x2 = xs[i] + xs[i + 1]
      let y2 = ys[j] + ys[j + 1]
      let mut found = false
      for rectangle in rectangles {
        if x2 > 2L * rectangle.0 &&
          x2 < 2L * rectangle.2 &&
          y2 > 2L * rectangle.1 &&
          y2 < 2L * rectangle.3 {
          found = true
          break
        }
      }
      found
    }
  }
  let edges : Array[(@moonclip.Point64, @moonclip.Point64)] = []
  for j in 0..<(ys.length() - 1) {
    for i in 0..<(xs.length() - 1) {
      if !covered(i, j) {
        continue
      }
      let left = xs[i]
      let right = xs[i + 1]
      let bottom = ys[j]
      let top = ys[j + 1]
      if !covered(i, j - 1) {
        edges.push(
          (
            @moonclip.Point64::new(left, bottom),
            @moonclip.Point64::new(right, bottom),
          ),
        )
      }
      if !covered(i + 1, j) {
        edges.push(
          (
            @moonclip.Point64::new(right, bottom),
            @moonclip.Point64::new(right, top),
          ),
        )
      }
      if !covered(i, j + 1) {
        edges.push(
          (
            @moonclip.Point64::new(right, top),
            @moonclip.Point64::new(left, top),
          ),
        )
      }
      if !covered(i - 1, j) {
        edges.push(
          (
            @moonclip.Point64::new(left, top),
            @moonclip.Point64::new(left, bottom),
          ),
        )
      }
    }
  }
  let result : @moonclip.Paths64 = []
  let remaining = edges
  let edge_count = edges.length()
  while !remaining.is_empty() {
    let first = remaining[0]
    ignore(remaining.remove(0))
    let path : @moonclip.Path64 = [first.0, first.1]
    let mut current = first.1
    let mut steps = 0
    while current != first.0 {
      steps += 1
      if steps > edge_count + 1 {
        break
      }
      let mut selected = -1
      for i in 0.. 1 && path[0] == path[path.length() - 1] {
        ignore(path.pop())
      }
      result.push(remove_collinear(path))
    }
  }
  result
}

///|
fn orthogonal_no_fit_region(
  moving : @moonclip.Paths64,
  stationary : @moonclip.Paths64,
) -> @moonclip.Paths64 {
  let moving_cells = orthogonal_cells(moving)
  let stationary_cells = orthogonal_cells(stationary)
  let rectangles : Array[(Int64, Int64, Int64, Int64)] = []
  for a in moving_cells {
    for b in stationary_cells {
      rectangles.push((b.0 - a.2, b.1 - a.3, b.2 - a.0, b.3 - a.1))
    }
  }
  if rectangles.is_empty() {
    return []
  }
  let xs : Array[Int64] = []
  let ys : Array[Int64] = []
  for rectangle in rectangles {
    for x in [rectangle.0, rectangle.2] {
      if !xs.contains(x) {
        xs.push(x)
      }
    }
    for y in [rectangle.1, rectangle.3] {
      if !ys.contains(y) {
        ys.push(y)
      }
    }
  }
  xs.sort()
  ys.sort()
  let rectangles_out : Array[(Int64, Int64, Int64, Int64)] = []
  for j in 0..<(ys.length() - 1) {
    let bottom = ys[j]
    let top = ys[j + 1]
    let mut run_start : Int64? = None
    let mut run_end = 0L
    for i in 0..<=xs.length() {
      let covered = if i < xs.length() - 1 {
        let x2 = xs[i] + xs[i + 1]
        let y2 = bottom + top
        let mut found = false
        for rectangle in rectangles {
          if x2 > 2L * rectangle.0 &&
            x2 < 2L * rectangle.2 &&
            y2 > 2L * rectangle.1 &&
            y2 < 2L * rectangle.3 {
            found = true
            break
          }
        }
        found
      } else {
        false
      }
      if covered {
        if run_start is None {
          run_start = Some(xs[i])
        }
        run_end = xs[i + 1]
      } else if run_start is Some(start) {
        rectangles_out.push((start, bottom, run_end, top))
        run_start = None
      }
    }
  }
  orthogonal_union_paths(merge_rectangles(rectangles_out))
}

///|
fn orthogonal_unused(
  usable : @moonclip.Paths64,
  materials : Array[@moonclip.Paths64],
) -> @moonclip.Paths64 {
  let xs : Array[Int64] = []
  let ys : Array[Int64] = []
  let collect = fn(paths : @moonclip.Paths64) {
    for path in paths {
      for point in path {
        if !xs.contains(point.x) {
          xs.push(point.x)
        }
        if !ys.contains(point.y) {
          ys.push(point.y)
        }
      }
    }
  }
  collect(usable)
  for material in materials {
    collect(material)
  }
  xs.sort()
  ys.sort()
  let rectangles_out : Array[(Int64, Int64, Int64, Int64)] = []
  for j in 0..<(ys.length() - 1) {
    let bottom = ys[j]
    let top = ys[j + 1]
    let mut run_start : Int64? = None
    let mut run_end = 0L
    for i in 0..<=xs.length() {
      let unused = if i < xs.length() - 1 {
        let cell_left = xs[i]
        let cell_right = xs[i + 1]
        let usable_cell = point_in_region_doubled(
          usable,
          cell_left + cell_right,
          bottom + top,
        )
        let mut occupied = false
        if usable_cell {
          for material in materials {
            if point_in_region_doubled(
                material,
                cell_left + cell_right,
                bottom + top,
              ) {
              occupied = true
              break
            }
          }
        }
        usable_cell && !occupied
      } else {
        false
      }
      if unused {
        if run_start is None {
          run_start = Some(xs[i])
        }
        run_end = xs[i + 1]
      } else if run_start is Some(start) {
        rectangles_out.push((start, bottom, run_end, top))
        run_start = None
      }
    }
  }
  orthogonal_union_paths(merge_rectangles(rectangles_out))
}

///|
fn subtract_material_region(
  region : @moonclip.Paths64,
  material : @moonclip.Paths64,
  config : GeometryConfig,
) -> @moonclip.Paths64 raise NestError {
  let outers = material.filter(fn(path) { exact_area2(path) > 0L })
  let holes = material.filter(fn(path) { exact_area2(path) < 0L })
  let mut unused = region
  if !outers.is_empty() {
    unused = match
      @moonclip.boolean_op(
        unused,
        outers,
        @moonclip.Difference,
        fill_rule=@moonclip.NonZero,
        limits=config.limits,
      ) {
      Ok(paths) => paths
      Err(error) => raise JsonError(error.message())
    }
  }
  if !holes.is_empty() {
    unused = unused.add(holes.map(reversed))
  }
  unused
}

///|
fn combine_sheet_runs(
  runs : Array[SheetRun],
  remaining : Array[Int32],
  problem : Problem,
  config : GeometryConfig,
  stats : Stats,
  winning_strategy : Int32,
  strategy_summaries : Array[StrategySummary],
) -> NestingResult raise NestError {
  let contours : @moonclip.Paths64 = []
  let placements = []
  let transforms : Array[PlacementTransform] = []
  let instances : Array[Instance] = []
  let sheets : Array[SheetLayout] = []
  let part_counts : Array[Int32] = Array::make(problem.parts.length(), 0)
  let part_areas : Array[Int64] = Array::make(problem.parts.length(), 0L)
  let mut offset_x = 0L
  let mut max_height = 0.0
  let mut area2 = 0L
  let mut total_quality_cost = 0L
  let mut total_hole_area2 = 0L
  let mut total_gap_area2 = 0L
  let mut total_unused_area2 = 0L
  let mut compression_iterations = 0
  let mut compression_before_width = 0.0
  let mut compression_before_height = 0.0
  let mut compression_after_width = 0.0
  let mut compression_after_height = 0.0
  let sheet_gap = config.scale
  for sheet_index in 0.. 0L && !material_sheet.is_empty() {
        let clearance = inflate_material(
          material_sheet,
          gap,
          config,
          problem.join,
        )
        let extra = material_area2(clearance) - material_area2(material_sheet)
        if extra > 0L {
          sheet_gap_area2 = checked_add(sheet_gap_area2, extra)
        }
      }
      let final_anchor = global_transform.to_output(
        @moonclip.Point64::new(
          local_transform.source_anchor_x,
          local_transform.source_anchor_y,
        ),
      )
      instances.push({
        instance_id,
        part: local_transform.part,
        part_instance_index: part_counts[local_transform.part],
        sheet: sheet_index,
        rotation_degrees: local_transform.rotation_degrees,
        mirrored: local_transform.mirrored,
        translation_x: local_transform.translation_x,
        translation_y: local_transform.translation_y,
        source_anchor_x: local_transform.source_anchor_x,
        source_anchor_y: local_transform.source_anchor_y,
        final_anchor_x: final_anchor.x,
        final_anchor_y: final_anchor.y,
        contour_indices,
        hole_indices,
        origin: local_transform.origin,
      })
      part_counts[local_transform.part] += 1
      part_areas[local_transform.part] = checked_add(
        part_areas[local_transform.part],
        instance_area2,
      )
    }
    for local_placement in run.layout.placements {
      placements.push({
        instance_id: instance_base + local_placement.instance_id,
        sheet: sheet_index,
        part: local_placement.part,
        contour_index: base + local_placement.contour_index,
        rotation_degrees: local_placement.rotation_degrees,
        mirrored: local_placement.mirrored,
        source_x: local_placement.source_x,
        source_y: local_placement.source_y,
        origin: local_placement.origin,
      })
    }
    let usable = prepare_sheet(
      run.spec.stock.contour,
      run.spec.stock.holes,
      round_away(problem.margin * config.scale.to_double()).to_int64(),
      problem.sheet_margin,
      round_away(problem.hole_clearance * config.scale.to_double()).to_int64(),
      config,
      problem.join,
    )
    let usable = usable.map(fn(path) {
      translate_paths([path], -sheet_min_x, -sheet_min_y)[0]
    })
    let material_groups : Array[@moonclip.Paths64] = []
    for local_transform in run.transforms {
      let material : @moonclip.Paths64 = []
      for local_placement in run.layout.placements {
        if local_placement.instance_id == local_transform.instance_id {
          material.push(run.layout.contours[local_placement.contour_index])
        }
      }
      if !material.is_empty() {
        material_groups.push(material)
      }
    }
    material_groups.sort_by(fn(a, b) {
      let a_area = material_area2(a)
      let b_area = material_area2(b)
      if a_area != b_area {
        if a_area > b_area {
          -1
        } else {
          1
        }
      } else {
        0
      }
    })
    let all_materials = material_groups
    for region in problem.preoccupied {
      if region.sheet == sheet_index {
        let shifted = region.contours.map(fn(path) {
          translate_paths([path], -sheet_min_x, -sheet_min_y)[0]
        })
        all_materials.push(shifted)
      }
    }
    for region in problem.quality_regions {
      if region.sheet == sheet_index && region.kind is QualityKind::Forbidden {
        let shifted = region.contours.map(fn(path) {
          translate_paths([path], -sheet_min_x, -sheet_min_y)[0]
        })
        all_materials.push(shifted)
      }
    }
    let mut orthogonal = paths_are_orthogonal(usable)
    for material in all_materials {
      if !paths_are_orthogonal(material) {
        orthogonal = false
        break
      }
    }
    let unused = if orthogonal {
      orthogonal_unused(usable, all_materials)
    } else {
      let mut unused = usable
      for material in all_materials {
        unused = subtract_material_region(unused, material, config)
      }
      unused
    }
    let material_area = material_area2(usable)
    let mut hole_area2 = 0L
    for hole in run.spec.stock.holes {
      hole_area2 = checked_add(hole_area2, exact_area2(hole).abs())
    }
    let unused_area2 = material_area2(unused)
    let contour_indices : Array[Int32] = []
    for i in 0..
      compression_before_height {
      run.layout.compression.before_height
    } else {
      compression_before_height
    }
    compression_after_width += run.layout.compression.after_width
    compression_after_height = if run.layout.compression.after_height >
      compression_after_height {
      run.layout.compression.after_height
    } else {
      compression_after_height
    }
    if run.layout.height > max_height {
      max_height = run.layout.height
    }
    offset_x += round_away(run.layout.width * config.scale.to_double()).to_int64() +
      sheet_gap
  }
  if !runs.is_empty() {
    offset_x -= sheet_gap
  }
  let unplaced : Array[Int32] = []
  let unplaced_details : Array[UnplacedInstance] = []
  for i in 0.. value
      None => { digits: None, }
    },
  }
  { layout, transforms, }
}

///|
fn spacing_gap(
  problem : Problem,
  config : GeometryConfig,
  first : Int32,
  second : Int32,
) -> Int64 {
  for pair in problem.pair_gaps {
    if (pair.first == first && pair.second == second) ||
      (pair.first == second && pair.second == first) {
      return round_away(pair.gap * config.scale.to_double()).to_int64()
    }
  }
  let global = round_away(problem.gap * config.scale.to_double()).to_int64()
  let first_gap = match problem.parts[first].gap {
    Some(value) => round_away(value * config.scale.to_double()).to_int64()
    None => global
  }
  let second_gap = match problem.parts[second].gap {
    Some(value) => round_away(value * config.scale.to_double()).to_int64()
    None => global
  }
  if first_gap > second_gap {
    first_gap
  } else {
    second_gap
  }
}

///|
/// Computes one no-fit polygon for every ordered pair of distinct part types
/// and each unique moving rotation. Stationary geometry uses its canonical
/// orientation, so `stationary_degrees` is zero.
pub fn no_fit_polygons(
  problem : Problem,
) -> Array[NoFitPolygon] raise NestError {
  let config = json_config(problem.precision)
  let normalized = normalize_problem(problem, config)
  let rotations = rotation_angles(normalized.rotations)
  if rotations.is_empty() {
    raise PlacementFailed("rotations.step_degrees must be zero or divide 90")
  }
  let oriented = normalized.parts.mapi(fn(index, part) {
    orient_part(part, index, rotations)
  })
  let result : Array[NoFitPolygon] = []
  for moving_index in 0.. value
              None => { digits: None, }
            },
          })
        }
      }
    }
  }
  result
}

///|
/// Computes complete no-fit regions for every ordered pair of distinct part
/// types and every unique pair of moving and stationary rotations.
pub fn no_fit_regions(problem : Problem) -> Array[NoFitRegion] raise NestError {
  let config = json_config(problem.precision)
  let normalized = normalize_problem(problem, config)
  let rotations = rotation_angles(normalized.rotations)
  if rotations.is_empty() {
    raise PlacementFailed("rotations.step_degrees must be zero or divide 90")
  }
  let oriented = normalized.parts.mapi(fn(index, part) {
    orient_part(part, index, rotations)
  })
  let result : Array[NoFitRegion] = []
  for moving_index in 0.. value
                None => { digits: None, }
              },
            })
          }
        }
      }
    }
  }
  result
}

///|
/// Returns the unique orientations used by complete no-fit queries.
pub fn no_fit_orientations(
  problem : Problem,
  part : Int32,
) -> Array[(Int32, Bool)] raise NestError {
  let config = json_config(problem.precision)
  let normalized = normalize_problem(problem, config)
  if part < 0 || part >= normalized.parts.length() {
    raise JsonError("part index is out of range")
  }
  let rotations = rotation_angles(normalized.rotations)
  if rotations.is_empty() {
    raise PlacementFailed("rotations.step_degrees must be zero or divide 90")
  }
  orient_part(normalized.parts[part], part, rotations).map(fn(orientation) {
    (orientation.degrees, orientation.mirrored)
  })
}

///|
/// Computes one no-fit region for an explicit ordered part pair and rotation.
pub fn no_fit_region_for(
  problem : Problem,
  moving : Int32,
  stationary : Int32,
  moving_degrees : Int32,
  stationary_degrees : Int32,
  moving_mirrored? : Bool,
  stationary_mirrored? : Bool,
) -> NoFitRegion? raise NestError {
  let config = json_config(problem.precision)
  let normalized = normalize_problem(problem, config)
  if moving < 0 || moving >= normalized.parts.length() {
    raise JsonError("moving part index is out of range")
  }
  if stationary < 0 || stationary >= normalized.parts.length() {
    raise JsonError("stationary part index is out of range")
  }
  if moving == stationary {
    return None
  }
  if moving_degrees < 0 ||
    moving_degrees >= 360 ||
    stationary_degrees < 0 ||
    stationary_degrees >= 360 {
    raise JsonError("no-fit rotation must be between 0 and 359")
  }
  let moving_part = normalized.parts[moving]
  let stationary_part = normalized.parts[stationary]
  let moving_oriented = oriented_part_at(
    moving_part,
    moving,
    moving_degrees,
    moving_mirrored.unwrap_or(false),
  )
  let stationary_oriented = oriented_part_at(
    stationary_part,
    stationary,
    stationary_degrees,
    stationary_mirrored.unwrap_or(false),
  )
  let stationary_material = inflate_material(
    stationary_oriented.material,
    spacing_gap(normalized, config, moving, stationary),
    config,
    normalized.join,
  )
  let (contours, exact_contours) = no_fit_region_data(
    moving_oriented.material,
    stationary_material,
    config,
  )
  if contours.is_empty() {
    return None
  }
  Some({
    moving,
    stationary,
    moving_degrees,
    stationary_degrees,
    moving_mirrored: moving_oriented.mirrored,
    stationary_mirrored: stationary_oriented.mirrored,
    contours,
    exact_contours,
    precision: match normalized.precision {
      Some(value) => value
      None => { digits: None, }
    },
  })
}

///|
/// Classifies contour contact. Boundary-only contact is `Touch`.
pub fn contact(
  moving : @moonclip.Path64,
  stationary : @moonclip.Paths64,
  precision? : Precision,
) -> Result[Contact, @moonclip.ClipError] {
  let config = geometry_config(precision) catch {
    NestError::JsonError(message) =>
      return Err(
        @moonclip.ClipError::InvalidInput(
          {
            stage: @moonclip.Stage::NormalizePath,
            path_index: None,
            vertex_index: None,
          },
          message,
        ),
      )
    PlacementFailed(message) =>
      return Err(
        @moonclip.ClipError::InvalidInput(
          {
            stage: @moonclip.Stage::NormalizePath,
            path_index: None,
            vertex_index: None,
          },
          message,
        ),
      )
  }
  let moving = match
    @moonclip.normalize_path(moving, @moonclip.Closed, limits=config.limits) {
    Ok(path) => path
    Err(error) => return Err(error)
  }
  let normalized : @moonclip.Paths64 = []
  for path in stationary {
    match
      @moonclip.normalize_path(path, @moonclip.Closed, limits=config.limits) {
      Ok(path) => normalized.push(path)
      Err(error) => return Err(error)
    }
  }
  let overlap = paths_overlap([moving], normalized, config) catch {
    error =>
      return Err(
        @moonclip.ClipError::InvalidInput(
          {
            stage: @moonclip.Stage::BooleanOp,
            path_index: None,
            vertex_index: None,
          },
          match error {
            JsonError(message) | PlacementFailed(message) => message
          },
        ),
      )
  }
  let touch = if overlap {
    false
  } else {
    paths_touch([moving], normalized, config) catch {
      error =>
        return Err(
          @moonclip.ClipError::InvalidInput(
            {
              stage: @moonclip.Stage::BooleanOp,
              path_index: None,
              vertex_index: None,
            },
            match error {
              JsonError(message) | PlacementFailed(message) => message
            },
          ),
        )
    }
  }
  if overlap {
    Ok(Overlap)
  } else if touch {
    Ok(Touch)
  } else {
    Ok(Clear)
  }
}