///|
priv struct GeometryConfig {
  digits : Int32?
  scale : Int64
  limits : @moonclip.Limits
}

///|
fn geometry_config(precision : Precision?) -> GeometryConfig raise NestError {
  let precision = match precision {
    Some(value) => value
    None => { digits: None, }
  }
  let effective = match precision.digits {
    Some(digits) => digits
    None => 3
  }
  if effective < 0 || effective > 6 {
    raise JsonError("precision.digits must be between 0 and 6")
  }
  let scale = match effective {
    0 => 1L
    1 => 10L
    2 => 100L
    3 => 1000L
    4 => 10000L
    5 => 100000L
    _ => 1000000L
  }
  { digits: precision.digits, scale, limits: Default::default(), }
}

///|
fn json_config(precision : Precision?) -> GeometryConfig raise NestError {
  geometry_config(precision)
}

///|
fn json_field(
  value : Json,
  name : String,
  _config : GeometryConfig,
) -> Json raise NestError {
  match value {
    Object(fields) =>
      match fields.get(name) {
        Some(field) => field
        None => raise JsonError("missing field '\{name}'")
      }
    _ => raise JsonError("expected an object with field '\{name}'")
  }
}

///|
fn json_optional_field(
  value : Json,
  name : String,
  _config : GeometryConfig,
) -> Json? raise NestError {
  match value {
    Object(fields) => fields.get(name)
    _ => raise JsonError("expected an object with optional field '\{name}'")
  }
}

///|
fn json_number(value : Double, config : GeometryConfig) -> Json raise NestError {
  let quantized = json_coordinate(value, "number", config)
  if config.digits is None {
    Json::number(quantized)
  } else {
    Json::number(quantized, repr=format_number(quantized, config))
  }
}

///|
fn json_nonnegative(
  value : Double,
  name : String,
  config : GeometryConfig,
) -> Double raise NestError {
  let quantized = json_coordinate(value, name, config)
  if quantized < 0.0 {
    raise JsonError("\{name} must be nonnegative")
  }
  quantized
}

///|
fn json_coordinate(
  value : Double,
  name : String,
  config : GeometryConfig,
) -> Double raise NestError {
  if value.is_nan() || value.is_inf() {
    raise JsonError("\{name} must be finite")
  }
  let scaled = value * config.scale.to_double()
  let bound = @moonclip.COORDINATE_LIMIT.to_double()
  if scaled < -bound || scaled > bound {
    raise JsonError("\{name} is outside the supported coordinate range")
  }
  round_away(scaled).to_int64().to_double() / config.scale.to_double()
}

///|
fn round_away(value : Double) -> Double {
  if value >= 0.0 {
    let whole = @double.floor(value)
    whole + (if value - whole >= 0.5 { 1.0 } else { 0.0 })
  } else {
    let whole = @double.ceil(value)
    whole - (if whole - value >= 0.5 { 1.0 } else { 0.0 })
  }
}

///|
fn json_integer(
  value : Json,
  name : String,
  _config : GeometryConfig,
) -> Int32 raise NestError {
  guard value is Number(number, ..) else {
    raise JsonError("\{name} must be an integer")
  }
  if number.is_nan() ||
    number.is_inf() ||
    number != @double.floor(number) ||
    number < -2147483648.0 ||
    number > 2147483647.0 {
    raise JsonError("\{name} must be an integer")
  }
  number.to_int()
}

///|
fn json_string(
  value : Json,
  name : String,
  _config : GeometryConfig,
) -> String raise NestError {
  guard value is String(text) else {
    raise JsonError("\{name} must be a string")
  }
  text
}

///|
fn json_bool(
  value : Json,
  name : String,
  _config : GeometryConfig,
) -> Bool raise NestError {
  match value {
    True => true
    False => false
    _ => raise JsonError("\{name} must be a boolean")
  }
}

///|
fn json_double(
  value : Json,
  name : String,
  config : GeometryConfig,
) -> Double raise NestError {
  guard value is Number(number, ..) else {
    raise JsonError("\{name} must be a number")
  }
  json_coordinate(number, name, config)
}

///|
fn json_array(
  value : Json,
  name : String,
  _config : GeometryConfig,
) -> Array[Json] raise NestError {
  guard value is [.. items] else { raise JsonError("\{name} must be an array") }
  items.to_owned()
}

///|
fn json_optional_array(
  value : Json,
  name : String,
  config : GeometryConfig,
) -> Array[Json] raise NestError {
  if value is Null {
    []
  } else {
    json_array(value, name, config)
  }
}

///|
fn json_path(
  value : Json,
  name : String,
  config : GeometryConfig,
) -> @moonclip.Path64 raise NestError {
  let points = json_array(value, name, config)
  if points.length() < 3 {
    raise JsonError("\{name} must contain at least three points")
  }
  let path = points.mapi(fn(index, point) raise NestError {
    guard point is { "x": x, "y": y, .. } else {
      raise JsonError("\{name}[\{index}] must be an object with x and y")
    }
    let x = json_scaled_integer(json_double(x, name, config), name, config)
    let y = json_scaled_integer(json_double(y, name, config), name, config)
    @moonclip.Point64::new(x, y)
  })
  for i in 1..
      if path.length() < 3 {
        raise JsonError("\{name} quantization collapsed the ring")
      } else {
        path
      }
    Err(error) => raise JsonError(error.message())
  }
}

///|
fn json_paths(
  value : Json,
  name : String,
  config : GeometryConfig,
) -> @moonclip.Paths64 raise NestError {
  json_array(value, name, config).mapi(fn(index, item) raise NestError {
    json_path(item, "\{name}[\{index}]", config)
  })
}

///|
fn json_scaled_integer(
  value : Double,
  name : String,
  config : GeometryConfig,
) -> Int64 raise NestError {
  let coordinate = json_coordinate(value, name, config)
  (coordinate * config.scale.to_double()).to_int64()
}

///|
fn parse_sheet(value : Json, config : GeometryConfig) -> Stock raise NestError {
  let outer = json_path(
    json_field(value, "contour", config),
    "sheet.contour",
    config,
  )
  let holes = json_paths(
    Json(
      json_optional_array(
        json_field(value, "holes", config),
        "sheet.holes",
        config,
      ),
    ),
    "sheet.holes",
    config,
  )
  validate_region([outer], holes, "sheet", config)
  { contour: outer, holes, }
}

///|
fn parse_sheets(
  value : Json,
  config : GeometryConfig,
) -> Array[SheetSpec]? raise NestError {
  let items = match json_optional_field(value, "sheets", config) {
    Some(Null) | None => return None
    Some(value) => json_array(value, "sheets", config)
  }
  if items.is_empty() {
    raise JsonError("sheets must contain at least one sheet")
  }
  let result : Array[SheetSpec] = []
  for i in 0.. 0.0
      Some(value) =>
        json_nonnegative(
          json_double(value, "\{name}.cost", config),
          "\{name}.cost",
          config,
        )
    }
    if id.is_empty() {
      raise JsonError("\{name}.id must not be empty")
    }
    if quantity < 1 {
      raise JsonError("\{name}.quantity must be at least 1")
    }
    result.push({ id, stock: parse_sheet(item, config), quantity, cost, })
  }
  Some(result)
}

///|
fn parse_rules(
  value : Json,
  quantity : Int32,
  config : GeometryConfig,
) -> PartRules raise NestError {
  let rules = match json_optional_field(value, "rules", config) {
    Some(Null) | None => return PartRules::default()
    Some(value) => value
  }
  let rotations = match json_optional_field(rules, "rotations", config) {
    Some(Null) | None => None
    Some(value) => {
      let items = json_array(value, "rules.rotations", config)
      let result : Array[Int32] = []
      for i in 0..= 360 {
          raise JsonError("rules.rotations angles must be between 0 and 359")
        }
        if !result.contains(angle) {
          result.push(angle)
        }
      }
      Some(result)
    }
  }
  let mirror = match json_optional_field(rules, "mirror", config) {
    Some(Null) | None => false
    Some(value) => json_bool(value, "rules.mirror", config)
  }
  let priority = match json_optional_field(rules, "priority", config) {
    Some(Null) | None => 0
    Some(value) => json_integer(value, "rules.priority", config)
  }
  let sheets = match json_optional_field(rules, "sheets", config) {
    Some(Null) | None => None
    Some(value) => {
      let items = json_array(value, "rules.sheets", config)
      let result : Array[Int32] = []
      for i in 0.. 0
    Some(value) => json_integer(value, "rules.min_quantity", config)
  }
  if min_quantity < 0 || min_quantity > quantity {
    raise JsonError("rules.min_quantity must be between zero and quantity")
  }
  let group = match json_optional_field(rules, "group", config) {
    Some(Null) | None => None
    Some(value) => Some(json_string(value, "rules.group", config))
  }
  let label = match json_optional_field(rules, "label", config) {
    Some(Null) | None => None
    Some(value) => Some(json_string(value, "rules.label", config))
  }
  let metadata = match json_optional_field(rules, "metadata", config) {
    Some(Null) | None => []
    Some(Object(fields)) => {
      let result : Array[(String, String)] = []
      for (key, value) in fields {
        result.push((key, json_string(value, "rules.metadata.\{key}", config)))
      }
      result.sort_by(fn(a, b) {
        if a.0 < b.0 {
          -1
        } else if a.0 > b.0 {
          1
        } else {
          0
        }
      })
      result
    }
    Some(_) => raise JsonError("rules.metadata must be an object")
  }
  let grain_degrees = match
    json_optional_field(rules, "grain_degrees", config) {
    Some(Null) | None => None
    Some(value) => {
      let angle = json_integer(value, "rules.grain_degrees", config)
      if angle < 0 || angle >= 360 {
        raise JsonError("rules.grain_degrees must be between 0 and 359")
      }
      Some(angle)
    }
  }
  let grain_tolerance_degrees = match
    json_optional_field(rules, "grain_tolerance_degrees", config) {
    Some(Null) | None => 0
    Some(value) => json_integer(value, "rules.grain_tolerance_degrees", config)
  }
  if grain_tolerance_degrees < 0 || grain_tolerance_degrees > 180 {
    raise JsonError("rules.grain_tolerance_degrees must be between 0 and 180")
  }
  let rotation_setup_cost = match
    json_optional_field(rules, "rotation_setup_cost", config) {
    Some(Null) | None => 0.0
    Some(value) =>
      json_nonnegative(
        json_double(value, "rules.rotation_setup_cost", config),
        "rules.rotation_setup_cost",
        config,
      )
  }
  let edge_clearance = match
    json_optional_field(rules, "edge_clearance", config) {
    Some(Null) | None => 0.0
    Some(value) =>
      json_nonnegative(
        json_double(value, "rules.edge_clearance", config),
        "rules.edge_clearance",
        config,
      )
  }
  {
    rotations,
    mirror,
    priority,
    sheets,
    min_quantity,
    group,
    label,
    metadata,
    grain_degrees,
    grain_tolerance_degrees,
    rotation_setup_cost,
    edge_clearance,
  }
}

///|
fn parse_part(
  value : Json,
  index : Int32,
  config : GeometryConfig,
) -> Part raise NestError {
  let name = "parts[\{index}]"
  let id = json_string(json_field(value, "id", config), "\{name}.id", config)
  let quantity = json_integer(
    json_field(value, "quantity", config),
    "\{name}.quantity",
    config,
  )
  let contours = json_paths(
    json_field(value, "contours", config),
    "\{name}.contours",
    config,
  )
  let holes = json_paths(
    Json(
      json_optional_array(
        json_field(value, "holes", config),
        "\{name}.holes",
        config,
      ),
    ),
    "\{name}.holes",
    config,
  )
  let gap = match json_optional_field(value, "gap", config) {
    Some(Null) | None => None
    Some(value) =>
      Some(
        json_nonnegative(
          json_double(value, "\{name}.gap", config),
          "\{name}.gap",
          config,
        ),
      )
  }
  let rules = parse_rules(value, quantity, config)
  let part = { id, quantity, contours, holes, gap, rules, }
  validate_region(part.contours, part.holes, name, config)
  part
}

///|
fn json_rotations(
  value : Json,
  config : GeometryConfig,
) -> RotationPolicy raise NestError {
  let field = match value {
    { "rotations": { "step_degrees": step, .. }, .. } => step
    { "rotations": Null, .. } => { "step_degrees": 5 }
    _ => raise JsonError("rotations must be an object with step_degrees")
  }
  { step_degrees: json_integer(field, "rotations.step_degrees", config), }
}

///|
fn parse_margin(
  value : Json,
  config : GeometryConfig,
) -> (Double, SheetMargin?) raise NestError {
  match value {
    Number(_, ..) =>
      (
        json_nonnegative(json_double(value, "margin", config), "margin", config),
        None,
      )
    Object(_) => {
      let top = json_nonnegative(
        json_double(json_field(value, "top", config), "margin.top", config),
        "margin.top",
        config,
      )
      let right = json_nonnegative(
        json_double(json_field(value, "right", config), "margin.right", config),
        "margin.right",
        config,
      )
      let bottom = json_nonnegative(
        json_double(
          json_field(value, "bottom", config),
          "margin.bottom",
          config,
        ),
        "margin.bottom",
        config,
      )
      let left = json_nonnegative(
        json_double(json_field(value, "left", config), "margin.left", config),
        "margin.left",
        config,
      )
      (0.0, Some({ top, right, bottom, left, }))
    }
    _ => raise JsonError("margin must be a number or an edge margin object")
  }
}

///|
fn parse_join(value : Json, config : GeometryConfig) -> GapJoin raise NestError {
  match json_optional_field(value, "join", config) {
    Some(Null) | None => GapJoin::Miter
    Some(value) =>
      match json_string(value, "join", config) {
        "round" => GapJoin::Round
        "bevel" => GapJoin::Bevel
        "miter" => GapJoin::Miter
        "square" => GapJoin::Square
        _ => raise JsonError("join must be round, bevel, miter, or square")
      }
  }
}

///|
fn parse_pair_gaps(
  value : Json,
  config : GeometryConfig,
  part_count : Int32,
) -> Array[PairGap] raise NestError {
  let items = match json_optional_field(value, "pair_gaps", config) {
    Some(Null) | None => []
    Some(value) => json_array(value, "pair_gaps", config)
  }
  let result : Array[PairGap] = []
  for i in 0..= part_count || second < 0 || second >= part_count {
      raise JsonError("\{name} references an unknown part")
    }
    if first == second {
      raise JsonError("\{name} must reference two distinct parts")
    }
    if result.any(fn(existing) {
        (existing.first == first && existing.second == second) ||
        (existing.first == second && existing.second == first)
      }) {
      raise JsonError("\{name} duplicates a pair gap")
    }
    result.push({ first, second, gap, })
  }
  result
}

///|
fn format_diagnostic(diagnostic : GeometryDiagnostic) -> String {
  "\{diagnostic.subject}.\{diagnostic.ring}[\{diagnostic.contour_index}]: \{diagnostic.message}"
}

///|
fn segments_intersect(
  a : @moonclip.Point64,
  b : @moonclip.Point64,
  c : @moonclip.Point64,
  d : @moonclip.Point64,
) -> Bool {
  let ab_c = cross_value(a, b, c)
  let ab_d = cross_value(a, b, d)
  let cd_a = cross_value(c, d, a)
  let cd_b = cross_value(c, d, b)
  if ab_c == 0L && point_on_segment_value(c, a, b) {
    return true
  }
  if ab_d == 0L && point_on_segment_value(d, a, b) {
    return true
  }
  if cd_a == 0L && point_on_segment_value(a, c, d) {
    return true
  }
  if cd_b == 0L && point_on_segment_value(b, c, d) {
    return true
  }
  ((ab_c > 0L && ab_d < 0L) || (ab_c < 0L && ab_d > 0L)) &&
  ((cd_a > 0L && cd_b < 0L) || (cd_a < 0L && cd_b > 0L))
}

///|
fn path_self_intersects(path : @moonclip.Path64) -> Bool {
  if path.length() < 4 {
    return false
  }
  for i in 0.. Bool {
  if first.is_empty() || second.is_empty() {
    return false
  }
  for i in 0.. Bool raise NestError {
  if outer.is_empty() || inner.is_empty() {
    return false
  }
  match @moonclip.point_in_polygon(inner[0], outer, limits=Default::default()) {
    Ok(@moonclip.Inside) => true
    Ok(@moonclip.OnBoundary) | Ok(@moonclip.Outside) => false
    Err(error) => raise JsonError(error.message())
  }
}

///|
fn region_diagnostics(
  contours : @moonclip.Paths64,
  holes : @moonclip.Paths64,
  name : String,
  config : GeometryConfig,
) -> Array[GeometryDiagnostic] raise NestError {
  let result : Array[GeometryDiagnostic] = []
  for (ring_name, paths) in [("contour", contours), ("hole", holes)] {
    for i in 0.. @moonclip.COORDINATE_LIMIT ||
          point.y < -@moonclip.COORDINATE_LIMIT ||
          point.y > @moonclip.COORDINATE_LIMIT {
          result.push({
            subject: name,
            ring: ring_name,
            contour_index: i,
            issue: GeometryIssue::CoordinateRange,
            message: "coordinate is outside the supported integer range",
          })
          coordinate_ok = false
          break
        }
      }
      if !coordinate_ok {
        continue
      }
      if path.length() < 3 {
        result.push({
          subject: name,
          ring: ring_name,
          contour_index: i,
          issue: GeometryIssue::ZeroArea,
          message: "ring must contain at least three distinct points",
        })
        continue
      }
      let mut duplicate = false
      for j in 1.. Array[FixedPlacement] raise NestError {
  let items = match json_optional_field(value, "fixed", config) {
    Some(Null) | None => []
    Some(value) => json_array(value, "fixed", config)
  }
  let result : Array[FixedPlacement] = []
  for i in 0.. false
      Some(value) => json_bool(value, "\{name}.mirrored", config)
    }
    let translation_x = json_scaled_integer(
      json_double(json_field(item, "x", config), "\{name}.x", config),
      "\{name}.x",
      config,
    )
    let translation_y = json_scaled_integer(
      json_double(json_field(item, "y", config), "\{name}.y", config),
      "\{name}.y",
      config,
    )
    if part < 0 || part >= part_count {
      raise JsonError("\{name}.part references an unknown part")
    }
    if sheet < 0 {
      raise JsonError("\{name}.sheet must be nonnegative")
    }
    result.push({
      part,
      sheet,
      rotation_degrees,
      mirrored,
      translation_x,
      translation_y,
    })
  }
  result
}

///|
fn parse_preoccupied(
  value : Json,
  config : GeometryConfig,
) -> Array[PreoccupiedRegion] raise NestError {
  let items = match json_optional_field(value, "preoccupied", config) {
    Some(Null) | None => []
    Some(value) => json_array(value, "preoccupied", config)
  }
  let result : Array[PreoccupiedRegion] = []
  for i in 0.. Array[QualityRegion] raise NestError {
  let items = match json_optional_field(value, "quality_regions", config) {
    Some(Null) | None => []
    Some(value) => json_array(value, "quality_regions", config)
  }
  let result : Array[QualityRegion] = []
  for i in 0.. QualityKind::Forbidden
      "restricted" => QualityKind::PartRestricted
      "high_value" => QualityKind::HighValue
      "defect" => QualityKind::Defect
      _ => raise JsonError("\{name}.kind is invalid")
    }
    let contours = json_paths(
      json_field(item, "contours", config),
      "\{name}.contours",
      config,
    )
    if contours.is_empty() {
      raise JsonError("\{name}.contours must not be empty")
    }
    let parts = match json_optional_field(item, "parts", config) {
      Some(Null) | None => []
      Some(value) => {
        let values = json_array(value, "\{name}.parts", config)
        let result : Array[Int32] = []
        for j in 0..= part_count {
            raise JsonError("\{name}.parts references an unknown part")
          }
          if !result.contains(part) {
            result.push(part)
          }
        }
        result
      }
    }
    if kind is QualityKind::PartRestricted && parts.is_empty() {
      raise JsonError("\{name}.parts must not be empty for a restricted region")
    }
    let weight = match json_optional_field(item, "weight", config) {
      Some(Null) | None => 1.0
      Some(value) =>
        json_nonnegative(
          json_double(value, "\{name}.weight", config),
          "\{name}.weight",
          config,
        )
    }
    result.push({ sheet, kind, contours, parts, weight, })
  }
  result
}

///|
fn parse_strategies(
  value : Json,
  config : GeometryConfig,
) -> Array[SearchStrategy]? raise NestError {
  let items = match json_optional_field(value, "strategies", config) {
    Some(Null) | None => return None
    Some(value) => json_array(value, "strategies", config)
  }
  if items.is_empty() {
    raise JsonError("strategies must contain at least one strategy")
  }
  let result : Array[SearchStrategy] = []
  for i in 0.. PartOrder::Area
      Some(value) =>
        match json_string(value, "\{name}.order", config) {
          "area" => PartOrder::Area
          "longest_side" => PartOrder::LongestSide
          "perimeter" => PartOrder::Perimeter
          "bounds_area" => PartOrder::BoundsArea
          _ => raise JsonError("\{name}.order is invalid")
        }
    }
    let gravity = match json_optional_field(item, "gravity", config) {
      Some(Null) | None => Gravity::LeftBottom
      Some(value) =>
        match json_string(value, "\{name}.gravity", config) {
          "left_bottom" => Gravity::LeftBottom
          "right_bottom" => Gravity::RightBottom
          "left_top" => Gravity::LeftTop
          "right_top" => Gravity::RightTop
          _ => raise JsonError("\{name}.gravity is invalid")
        }
    }
    let scoring = match json_optional_field(item, "scoring", config) {
      Some(Null) | None => CandidateScoring::Distance
      Some(value) =>
        match json_string(value, "\{name}.scoring", config) {
          "distance" => CandidateScoring::Distance
          "bounds_area" => CandidateScoring::BoundsArea
          "utilization" => CandidateScoring::Utilization
          "future_space" => CandidateScoring::FutureSpace
          "composite" => CandidateScoring::Composite
          _ => raise JsonError("\{name}.scoring is invalid")
        }
    }
    result.push({ order, gravity, scoring, })
  }
  Some(result)
}

///|
fn parse_budget(
  value : Json,
  config : GeometryConfig,
) -> SearchBudget raise NestError {
  let budget = match json_optional_field(value, "budget", config) {
    Some(Null) | None => return SearchBudget::default()
    Some(value) => value
  }
  let max_nodes = match json_optional_field(budget, "max_nodes", config) {
    Some(Null) | None => 0
    Some(value) => json_integer(value, "budget.max_nodes", config)
  }
  let max_backtracks = match
    json_optional_field(budget, "max_backtracks", config) {
    Some(Null) | None => 0
    Some(value) => json_integer(value, "budget.max_backtracks", config)
  }
  let beam_width = match json_optional_field(budget, "beam_width", config) {
    Some(Null) | None => 1
    Some(value) => json_integer(value, "budget.beam_width", config)
  }
  let workers = match json_optional_field(budget, "workers", config) {
    Some(Null) | None => 1
    Some(value) => json_integer(value, "budget.workers", config)
  }
  let max_milliseconds = match
    json_optional_field(budget, "max_milliseconds", config) {
    Some(Null) | None => 0L
    Some(value) =>
      json_integer(value, "budget.max_milliseconds", config).to_int64()
  }
  let max_candidates = match
    json_optional_field(budget, "max_candidates", config) {
    Some(Null) | None => 0
    Some(value) => json_integer(value, "budget.max_candidates", config)
  }
  if max_nodes < 0 ||
    max_backtracks < 0 ||
    beam_width < 1 ||
    workers < 1 ||
    max_milliseconds < 0L ||
    max_candidates < 0 {
    raise JsonError(
      "budget limits must be nonnegative and beam_width/workers must be at least one",
    )
  }
  {
    max_nodes,
    max_backtracks,
    beam_width,
    workers,
    max_milliseconds,
    max_candidates,
  }
}

///|
fn parse_machine(
  value : Json,
  config : GeometryConfig,
) -> MachineSpec? raise NestError {
  match json_optional_field(value, "machine", config) {
    Some(Null) | None => None
    Some(value) => {
      let id = match json_optional_field(value, "id", config) {
        Some(Null) | None => "machine-0"
        Some(value) => json_string(value, "machine.id", config)
      }
      let max_width = json_nonnegative(
        json_double(
          json_field(value, "max_width", config),
          "machine.max_width",
          config,
        ),
        "machine.max_width",
        config,
      )
      let max_height = json_nonnegative(
        json_double(
          json_field(value, "max_height", config),
          "machine.max_height",
          config,
        ),
        "machine.max_height",
        config,
      )
      if max_width <= 0.0 || max_height <= 0.0 {
        raise JsonError("machine dimensions must be positive")
      }
      Some({ id, max_width, max_height, })
    }
  }
}

///|
fn parse_cutting(
  value : Json,
  config : GeometryConfig,
) -> CuttingConfig? raise NestError {
  match json_optional_field(value, "cutting", config) {
    Some(Null) | None => None
    Some(value) => {
      let defaults = CuttingConfig::default()
      let number = fn(name : String, fallback : Double) raise NestError {
        match json_optional_field(value, name, config) {
          Some(Null) | None => fallback
          Some(item) =>
            json_nonnegative(
              json_double(item, "cutting.\{name}", config),
              "cutting.\{name}",
              config,
            )
        }
      }
      Some({
        rapid_weight: number("rapid_weight", defaults.rapid_weight),
        cut_weight: number("cut_weight", defaults.cut_weight),
        pierce_weight: number("pierce_weight", defaults.pierce_weight),
        pierce_cost: number("pierce_cost", defaults.pierce_cost),
        safe_height: number("safe_height", defaults.safe_height),
        lead_in: number("lead_in", defaults.lead_in),
        lead_out: number("lead_out", defaults.lead_out),
      })
    }
  }
}

///|
fn parse_production(
  value : Json,
  config : GeometryConfig,
  part_count : Int32,
) -> ProductionConfig? raise NestError {
  match json_optional_field(value, "production", config) {
    Some(Null) | None => None
    Some(value) => {
      let machine_items = match json_optional_field(value, "machines", config) {
        Some(Null) | None => []
        Some(items) => json_array(items, "production.machines", config)
      }
      let machines = machine_items.mapi(fn(index, item) raise NestError {
        let name = "production.machines[\{index}]"
        let available = match
          json_optional_field(item, "available_minute", config) {
          Some(Null) | None => 0
          Some(available) =>
            json_integer(available, "\{name}.available_minute", config)
        }
        if available < 0 {
          raise JsonError("\{name}.available_minute must be nonnegative")
        }
        {
          id: json_string(json_field(item, "id", config), "\{name}.id", config),
          available_minute: available,
        }
      })
      let job_items = match json_optional_field(value, "jobs", config) {
        Some(Null) | None => []
        Some(items) => json_array(items, "production.jobs", config)
      }
      let jobs = job_items.mapi(fn(index, item) raise NestError {
        let name = "production.jobs[\{index}]"
        let part = json_integer(
          json_field(item, "part", config),
          "\{name}.part",
          config,
        )
        let quantity = json_integer(
          json_field(item, "quantity", config),
          "\{name}.quantity",
          config,
        )
        let due_minute = json_integer(
          json_field(item, "due_minute", config),
          "\{name}.due_minute",
          config,
        )
        let duration_minutes = json_integer(
          json_field(item, "duration_minutes", config),
          "\{name}.duration_minutes",
          config,
        )
        let setup_minutes = match
          json_optional_field(item, "setup_minutes", config) {
          Some(Null) | None => 0
          Some(setup) => json_integer(setup, "\{name}.setup_minutes", config)
        }
        if part < 0 || part >= part_count {
          raise JsonError("\{name}.part references an unknown part")
        }
        if quantity < 1 ||
          due_minute < 0 ||
          duration_minutes < 0 ||
          setup_minutes < 0 {
          raise JsonError("\{name} contains invalid quantity or time values")
        }
        {
          id: json_string(json_field(item, "id", config), "\{name}.id", config),
          part,
          quantity,
          due_minute,
          priority: match json_optional_field(item, "priority", config) {
            Some(Null) | None => 0
            Some(priority) => json_integer(priority, "\{name}.priority", config)
          },
          setup_group: match json_optional_field(item, "setup_group", config) {
            Some(Null) | None => ""
            Some(group) => json_string(group, "\{name}.setup_group", config)
          },
          duration_minutes,
          setup_minutes,
        }
      })
      let due_weight = match json_optional_field(value, "due_weight", config) {
        Some(Null) | None => 1.0
        Some(weight) =>
          json_nonnegative(
            json_double(weight, "production.due_weight", config),
            "production.due_weight",
            config,
          )
      }
      let setup_weight = match
        json_optional_field(value, "setup_weight", config) {
        Some(Null) | None => 1.0
        Some(weight) =>
          json_nonnegative(
            json_double(weight, "production.setup_weight", config),
            "production.setup_weight",
            config,
          )
      }
      Some({ machines, jobs, due_weight, setup_weight, })
    }
  }
}

///|
fn parse_suites(
  value : Json,
  config : GeometryConfig,
  part_count : Int32,
) -> Array[SuiteSpec] raise NestError {
  let items = match json_optional_field(value, "suites", config) {
    Some(Null) | None => []
    Some(value) => json_array(value, "suites", config)
  }
  let result : Array[SuiteSpec] = []
  for i in 0..= part_count {
      raise JsonError("\{name}.outer references an unknown part")
    }
    let inner : Array[Int32] = []
    for j in 0..= part_count || part == outer {
        raise JsonError("\{name}.inner contains an invalid part")
      }
      if !inner.contains(part) {
        inner.push(part)
      }
    }
    if inner.is_empty() {
      raise JsonError("\{name}.inner must not be empty")
    }
    result.push({ id, outer, inner, })
  }
  result
}

///|
fn validate_region(
  contours : @moonclip.Paths64,
  holes : @moonclip.Paths64,
  name : String,
  config : GeometryConfig,
) -> Unit raise NestError {
  if contours.is_empty() {
    raise JsonError("\{name}.contours must not be empty")
  }
  let diagnostics = region_diagnostics(contours, holes, name, config)
  if diagnostics.length() > 0 {
    raise JsonError(format_diagnostic(diagnostics[0]))
  }
  match @moonclip.validate_paths(contours, limits=config.limits) {
    Err(error) => raise JsonError(error.message())
    Ok(_) => ()
  }
  match @moonclip.validate_paths(holes, limits=config.limits) {
    Err(error) => raise JsonError(error.message())
    Ok(_) => ()
  }
  for i in 0.. paths
    Err(error) => raise JsonError(error.message())
  }
  let material = match
    @moonclip.boolean_op(
      outer,
      holes,
      @moonclip.Difference,
      fill_rule=@moonclip.NonZero,
      limits=config.limits,
    ) {
    Ok(paths) => paths
    Err(error) => raise JsonError(error.message())
  }
  if material_area2(material) == 0L {
    raise JsonError("\{name} has no material after subtracting holes")
  }
}

///|
fn format_number(value : Double, config : GeometryConfig) -> String {
  let scaled = round_away(value * config.scale.to_double())
  let negative = scaled < 0.0
  let absolute = if negative { -scaled } else { scaled }
  let integer = absolute.to_int64()
  let whole = integer / config.scale
  let fraction = integer % config.scale
  let digits = match config.digits {
    Some(digits) => digits
    None => 0
  }
  let sign = if negative && integer != 0L { "-" } else { "" }
  if digits == 0 || fraction == 0L {
    "\{sign}\{whole}"
  } else {
    let mut text = fraction.to_string()
    while text.length() < digits {
      text = "0\{text}"
    }
    "\{sign}\{whole}.\{text}"
  }
}

///|
fn normalize_closed(
  path : @moonclip.Path64,
  config : GeometryConfig,
) -> @moonclip.Path64 raise NestError {
  match @moonclip.normalize_path(path, @moonclip.Closed, limits=config.limits) {
    Ok(path) => path
    Err(error) => raise JsonError(error.message())
  }
}

///|
fn normalize_region(
  contours : @moonclip.Paths64,
  holes : @moonclip.Paths64,
  config : GeometryConfig,
) -> @moonclip.Paths64 raise NestError {
  let contours = contours.map(fn(path) raise NestError {
    normalize_closed(path, config)
  })
  let holes = holes.map(fn(path) raise NestError {
    normalize_closed(path, config)
  })
  if !paths_are_orthogonal(contours) || !paths_are_orthogonal(holes) {
    let result : @moonclip.Paths64 = []
    for path in contours {
      result.push(if exact_area2(path) > 0L { path } else { reversed(path) })
    }
    for path in holes {
      result.push(if exact_area2(path) < 0L { path } else { reversed(path) })
    }
    return result
  }
  let outer = match
    @moonclip.boolean_op(
      contours,
      [],
      @moonclip.Union,
      fill_rule=@moonclip.NonZero,
      limits=config.limits,
    ) {
    Ok(paths) => paths
    Err(error) => raise JsonError(error.message())
  }
  match
    @moonclip.boolean_op(
      outer,
      holes,
      @moonclip.Difference,
      fill_rule=@moonclip.NonZero,
      limits=config.limits,
    ) {
    Ok(paths) => paths
    Err(error) => raise JsonError(error.message())
  }
}

///|
fn validate_machine_envelope(
  machine : MachineSpec,
  stocks : Array[Stock],
  config : GeometryConfig,
) -> Unit raise NestError {
  for stock in stocks {
    let (min_x, min_y, max_x, max_y) = paths_bounds([stock.contour])
    let width = (max_x - min_x).to_double() / config.scale.to_double()
    let height = (max_y - min_y).to_double() / config.scale.to_double()
    if width > machine.max_width || height > machine.max_height {
      raise PlacementFailed("sheet exceeds machine envelope \{machine.id}")
    }
  }
}

///|
fn normalize_problem(
  problem : Problem,
  config : GeometryConfig,
) -> Problem raise NestError {
  let sheet = normalize_stock(problem.sheet, config)
  let sheets = match problem.sheets {
    Some(specs) =>
      Some(
        specs.map(fn(spec) raise NestError {
          {
            id: spec.id,
            stock: normalize_stock(spec.stock, config),
            quantity: spec.quantity,
            cost: spec.cost,
          }
        }),
      )
    None => None
  }
  let parts = problem.parts.map(fn(part) raise NestError {
    {
      id: part.id,
      quantity: part.quantity,
      contours: normalize_region(part.contours, part.holes, config),
      holes: [],
      gap: part.gap,
      rules: part.rules,
    }
  })
  match problem.machine {
    Some(machine) => {
      let stocks = match sheets {
        Some(specs) => specs.map(fn(spec) { spec.stock })
        None => [sheet]
      }
      validate_machine_envelope(machine, stocks, config)
    }
    None => ()
  }
  {
    sheet,
    sheets,
    parts,
    gap: problem.gap,
    margin: problem.margin,
    sheet_margin: problem.sheet_margin,
    pair_gaps: problem.pair_gaps,
    hole_clearance: problem.hole_clearance,
    join: problem.join,
    fixed: problem.fixed,
    preoccupied: problem.preoccupied,
    quality_regions: problem.quality_regions,
    strategies: problem.strategies,
    budget: problem.budget,
    suites: problem.suites,
    precision: problem.precision,
    rotations: problem.rotations,
    machine: problem.machine,
    cutting: problem.cutting,
    production: problem.production,
  }
}

///|
fn normalize_stock(
  stock : Stock,
  config : GeometryConfig,
) -> Stock raise NestError {
  let contour = normalize_closed(stock.contour, config)
  let holes = stock.holes.map(fn(path) raise NestError {
    normalize_closed(path, config)
  })
  validate_region([contour], holes, "sheet", config)
  { contour, holes, }
}

///|
fn exact_area2(path : @moonclip.Path64) -> Int64 {
  if path.length() < 3 {
    return 0L
  }
  let mut previous = path[path.length() - 1]
  let mut sum = 0N
  for current in path {
    sum = sum +
      @bigint.BigInt::from_int64(previous.x) *
      @bigint.BigInt::from_int64(current.y) -
      @bigint.BigInt::from_int64(previous.y) *
      @bigint.BigInt::from_int64(current.x)
    previous = current
  }
  let sign = sum.compare_int(0)
  let magnitude = sum.abs()
  if magnitude.compare_int64(9223372036854775807L) > 0 {
    abort("polygon area exceeds Int64")
  }
  let value = if sign < 0 { magnitude.neg() } else { magnitude }
  value.to_int64()
}

///|
fn material_area2(paths : @moonclip.Paths64) -> Int64 {
  let mut sum = 0L
  for path in paths {
    let area = exact_area2(path)
    let next = sum + area
    if (area > 0L && next < sum) || (area < 0L && next > sum) {
      abort("combined polygon area exceeds Int64")
    }
    sum = next
  }
  sum
}

///|
fn paths_bounds(paths : @moonclip.Paths64) -> (Int64, Int64, Int64, Int64) {
  let mut min_x = paths[0][0].x
  let mut min_y = paths[0][0].y
  let mut max_x = min_x
  let mut max_y = min_y
  for path in paths {
    for point in path {
      min_x = if point.x < min_x { point.x } else { min_x }
      min_y = if point.y < min_y { point.y } else { min_y }
      max_x = if point.x > max_x { point.x } else { max_x }
      max_y = if point.y > max_y { point.y } else { max_y }
    }
  }
  (min_x, min_y, max_x, max_y)
}

///|
fn convex_overlap(a : @moonclip.Path64, b : @moonclip.Path64) -> Bool {
  for first in [a, b] {
    for i in 0.. a_max { projection } else { a_max }
      }
      for point in b {
        let projection = point.x * axis_x + point.y * axis_y
        b_min = if projection < b_min { projection } else { b_min }
        b_max = if projection > b_max { projection } else { b_max }
      }
      if a_max <= b_min || b_max <= a_min {
        return false
      }
    }
  }
  true
}

///|
/// Exact positive-area Boolean predicate on normalized integer regions.
/// Orthogonal cells and convex separating-axis tests are final decisions, not
/// broad-phase filters; boundary-only contact returns false.
fn paths_overlap(
  a : @moonclip.Paths64,
  b : @moonclip.Paths64,
  config : GeometryConfig,
) -> Bool raise NestError {
  if a.is_empty() || b.is_empty() {
    return false
  }
  let (a_min_x, a_min_y, a_max_x, a_max_y) = paths_bounds(a)
  let (b_min_x, b_min_y, b_max_x, b_max_y) = paths_bounds(b)
  if a_max_x <= b_min_x ||
    b_max_x <= a_min_x ||
    a_max_y <= b_min_y ||
    b_max_y <= a_min_y {
    return false
  }
  if paths_are_orthogonal(a) && paths_are_orthogonal(b) {
    return orthogonal_overlap(a, b)
  }
  let a_pieces = convex_decomposition(a, config)
  let b_pieces = convex_decomposition(b, config)
  for a_piece in a_pieces {
    for b_piece in b_pieces {
      if convex_overlap(a_piece, b_piece) {
        return true
      }
    }
  }
  false
}

///|
fn paths_touch(
  a : @moonclip.Paths64,
  b : @moonclip.Paths64,
  config : GeometryConfig,
) -> Bool raise NestError {
  let intersection = match
    @moonclip.boolean_op(
      a,
      b,
      @moonclip.Intersection,
      fill_rule=@moonclip.NonZero,
      limits=config.limits,
    ) {
    Ok(paths) => paths
    Err(error) => raise JsonError(error.message())
  }
  !intersection.is_empty()
}

///|
fn translate_paths(
  paths : @moonclip.Paths64,
  dx : Int64,
  dy : Int64,
) -> @moonclip.Paths64 {
  paths.map(fn(path) {
    path.map(fn(point) { @moonclip.Point64::new(point.x + dx, point.y + dy) })
  })
}

///|
fn reversed(path : @moonclip.Path64) -> @moonclip.Path64 {
  let result : @moonclip.Path64 = []
  let mut index = path.length()
  while index > 0 {
    index -= 1
    result.push(path[index])
  }
  result
}

///|
fn cross_value(
  a : @moonclip.Point64,
  b : @moonclip.Point64,
  c : @moonclip.Point64,
) -> Int64 {
  (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
}

///|
fn point_on_segment_value(
  point : @moonclip.Point64,
  start : @moonclip.Point64,
  finish : @moonclip.Point64,
) -> Bool {
  cross_value(start, finish, point) == 0L &&
  point.x >= (if start.x < finish.x { start.x } else { finish.x }) &&
  point.x <= (if start.x > finish.x { start.x } else { finish.x }) &&
  point.y >= (if start.y < finish.y { start.y } else { finish.y }) &&
  point.y <= (if start.y > finish.y { start.y } else { finish.y })
}

///|
fn remove_collinear(path : @moonclip.Path64) -> @moonclip.Path64 {
  let result = path.copy()
  let mut changed = true
  while changed && result.length() > 3 {
    changed = false
    let mut index = 0
    while index < result.length() {
      let previous = result[(index + result.length() - 1) % result.length()]
      let current = result[index]
      let next = result[(index + 1) % result.length()]
      if cross_value(previous, current, next) == 0L &&
        point_on_segment_value(current, previous, next) {
        ignore(result.remove(index))
        changed = true
      } else {
        index += 1
      }
    }
  }
  result
}

///|
type DoublePoint = (Double, Double)

///|
type DoublePath = Array[DoublePoint]

///|
type DoublePaths = Array[DoublePath]

///|
priv struct UnionBoundarySegment {
  start : DoublePoint
  finish : DoublePoint
}

///|
priv struct NormalizedUnion {
  contours : @moonclip.Paths64
  exact_contours : DoublePaths
}

///|
fn union_point_key(point : DoublePoint) -> @moonclip.Point64 {
  @moonclip.Point64::new(
    @double.round(point.0).to_int64(),
    @double.round(point.1).to_int64(),
  )
}

///|
fn union_exact_key(point : DoublePoint, origin : DoublePoint) -> (Int64, Int64) {
  (
    @double.round((point.0 - origin.0) * 1000000.0).to_int64(),
    @double.round((point.1 - origin.1) * 1000000.0).to_int64(),
  )
}

///|
fn cross_double(
  first_x : Double,
  first_y : Double,
  second_x : Double,
  second_y : Double,
) -> Double {
  first_x * second_y - first_y * second_x
}

///|
fn union_covers_right(
  polygons : DoublePaths,
  start : DoublePoint,
  finish : DoublePoint,
  source_index : Int32,
) -> Bool {
  let middle = ((start.0 + finish.0) / 2.0, (start.1 + finish.1) / 2.0)
  let delta_x = finish.0 - start.0
  let delta_y = finish.1 - start.1
  let mut polygon_index = 0
  while polygon_index < polygons.length() {
    if polygon_index == source_index {
      polygon_index += 1
      continue
    }
    let path = polygons[polygon_index]
    let mut inside = true
    let mut strictly_inside = true
    let mut boundary_covers_right = false
    let mut edge_index = 0
    while edge_index < path.length() {
      let edge_start = path[edge_index]
      let edge_finish = path[(edge_index + 1) % path.length()]
      let side = cross_double(
        edge_finish.0 - edge_start.0,
        edge_finish.1 - edge_start.1,
        middle.0 - edge_start.0,
        middle.1 - edge_start.1,
      )
      if side < -0.00000001 {
        inside = false
        break
      }
      if side <= 0.00000001 {
        strictly_inside = false
        let other_x = edge_finish.0 - edge_start.0
        let other_y = edge_finish.1 - edge_start.1
        if cross_double(delta_x, delta_y, other_x, other_y).abs() <= 0.00000001 &&
          delta_x * other_x + delta_y * other_y < 0.0 {
          boundary_covers_right = true
        }
      }
      edge_index += 1
    }
    if inside && (strictly_inside || boundary_covers_right) {
      return true
    }
    polygon_index += 1
  }
  false
}

///|
fn union_edge_parameters(
  start : DoublePoint,
  finish : DoublePoint,
  edges : Array[(DoublePoint, DoublePoint)],
) -> Array[Double] {
  let delta_x = finish.0 - start.0
  let delta_y = finish.1 - start.1
  let parameters : Array[Double] = [0.0, 1.0]
  for (other_start, other_finish) in edges {
    let other_x = other_finish.0 - other_start.0
    let other_y = other_finish.1 - other_start.1
    let relative_x = other_start.0 - start.0
    let relative_y = other_start.1 - start.1
    let denominator = cross_double(delta_x, delta_y, other_x, other_y)
    if denominator.abs() > 0.000000000001 {
      let along = cross_double(relative_x, relative_y, other_x, other_y) /
        denominator
      let other_along = cross_double(relative_x, relative_y, delta_x, delta_y) /
        denominator
      if along > 0.000000000001 &&
        along < 0.999999999999 &&
        other_along >= -0.000000000001 &&
        other_along <= 1.000000000001 {
        parameters.push(along)
      }
    } else if cross_double(relative_x, relative_y, delta_x, delta_y).abs() <=
      0.000000001 {
      let length_squared = delta_x * delta_x + delta_y * delta_y
      let first = (relative_x * delta_x + relative_y * delta_y) / length_squared
      let other_relative_x = other_finish.0 - start.0
      let other_relative_y = other_finish.1 - start.1
      let second = (other_relative_x * delta_x + other_relative_y * delta_y) /
        length_squared
      if first > 0.000000000001 && first < 0.999999999999 {
        parameters.push(first)
      }
      if second > 0.000000000001 && second < 0.999999999999 {
        parameters.push(second)
      }
    }
  }
  parameters.sort_by(fn(first, second) {
    if first < second {
      -1
    } else if first > second {
      1
    } else {
      0
    }
  })
  let unique : Array[Double] = []
  for parameter in parameters {
    if unique.is_empty() ||
      (parameter - unique[unique.length() - 1]).abs() > 0.000000001 {
      unique.push(parameter)
    }
  }
  unique
}

///|
fn exact_double_int(value : Double) -> Int64? {
  if value.is_nan() ||
    value.is_inf() ||
    value != @double.floor(value) ||
    value.abs() > 9007199254740991.0 {
    None
  } else {
    Some(value.to_int64())
  }
}

///|
fn double_orient(
  first : DoublePoint,
  second : DoublePoint,
  third : DoublePoint,
) -> Int32 {
  let first_x = exact_double_int(first.0)
  let first_y = exact_double_int(first.1)
  let second_x = exact_double_int(second.0)
  let second_y = exact_double_int(second.1)
  let third_x = exact_double_int(third.0)
  let third_y = exact_double_int(third.1)
  match (first_x, first_y, second_x, second_y, third_x, third_y) {
    (
      Some(first_x),
      Some(first_y),
      Some(second_x),
      Some(second_y),
      Some(third_x),
      Some(third_y),
    ) => {
      let determinant = (
          @bigint.BigInt::from_int64(second_x) -
          @bigint.BigInt::from_int64(first_x)
        ) *
        (
          @bigint.BigInt::from_int64(third_y) -
          @bigint.BigInt::from_int64(first_y)
        ) -
        (
          @bigint.BigInt::from_int64(second_y) -
          @bigint.BigInt::from_int64(first_y)
        ) *
        (
          @bigint.BigInt::from_int64(third_x) -
          @bigint.BigInt::from_int64(first_x)
        )
      determinant.compare_int(0)
    }
    _ => {
      let determinant = cross_double(
        second.0 - first.0,
        second.1 - first.1,
        third.0 - first.0,
        third.1 - first.1,
      )
      if determinant < 0.0 {
        -1
      } else if determinant > 0.0 {
        1
      } else {
        0
      }
    }
  }
}

///|
fn double_area2(path : DoublePath) -> Double {
  let mut area = 0.0
  if path.is_empty() {
    return area
  }
  let origin = path[0]
  let mut previous = path[path.length() - 1]
  let mut exact = true
  let mut exact_sum = 0N
  for current in path {
    match
      (
        exact_double_int(previous.0 - origin.0),
        exact_double_int(previous.1 - origin.1),
        exact_double_int(current.0 - origin.0),
        exact_double_int(current.1 - origin.1),
      ) {
      (Some(previous_x), Some(previous_y), Some(current_x), Some(current_y)) =>
        exact_sum = exact_sum +
          @bigint.BigInt::from_int64(previous_x) *
          @bigint.BigInt::from_int64(current_y) -
          @bigint.BigInt::from_int64(previous_y) *
          @bigint.BigInt::from_int64(current_x)
      _ => {
        exact = false
        break
      }
    }
    previous = current
  }
  if exact {
    let sign = exact_sum.compare_int(0)
    let magnitude = exact_sum.abs()
    if magnitude.compare_int64(9223372036854775807L) > 0 {
      abort("polygon area exceeds Int64")
    }
    let value = if sign < 0 { magnitude.neg() } else { magnitude }
    return value.to_int64().to_double()
  }
  previous = path[path.length() - 1]
  for current in path {
    area += (previous.0 - origin.0) * (current.1 - origin.1) -
      (previous.1 - origin.1) * (current.0 - origin.0)
    previous = current
  }
  area
}

///|
fn reverse_double_path(path : DoublePath) -> DoublePath {
  let result : DoublePath = []
  let mut index = path.length()
  while index > 0 {
    index -= 1
    result.push(path[index])
  }
  result
}

///|
fn remove_collinear_double(path : DoublePath) -> DoublePath {
  let result = path.copy()
  let mut changed = true
  while changed && result.length() > 3 {
    changed = false
    let mut index = 0
    while index < result.length() {
      let previous = result[(index + result.length() - 1) % result.length()]
      let current = result[index]
      let next = result[(index + 1) % result.length()]
      if double_orient(previous, current, next) == 0 &&
        current.0 >= (if previous.0 < next.0 { previous.0 } else { next.0 }) &&
        current.0 <= (if previous.0 > next.0 { previous.0 } else { next.0 }) &&
        current.1 >= (if previous.1 < next.1 { previous.1 } else { next.1 }) &&
        current.1 <= (if previous.1 > next.1 { previous.1 } else { next.1 }) {
        ignore(result.remove(index))
        changed = true
      } else {
        index += 1
      }
    }
  }
  result
}

///|
fn normalize_double_convex_union_data(
  paths : DoublePaths,
) -> NormalizedUnion raise NestError {
  let polygons : DoublePaths = []
  for path in paths {
    let area = double_area2(path)
    if area.abs() <= 0.000000001 {
      continue
    }
    if area < 0.0 {
      polygons.push(reverse_double_path(path))
    } else {
      polygons.push(path)
    }
  }
  if polygons.is_empty() {
    return { contours: [], exact_contours: [], }
  }
  let key_origin = polygons[0][0]
  let edges : Array[(Int32, DoublePoint, DoublePoint)] = []
  for path_index in 0.. 1 &&
        union_exact_key(current.finish, key_origin) ==
        union_exact_key(ring[0], key_origin) {
        closed = true
        break
      }
      let incoming_x = current.finish.0 - current.start.0
      let incoming_y = current.finish.1 - current.start.1
      let reverse_angle = @math.atan2(-incoming_y, -incoming_x)
      let mut next_index = -1
      let mut next_angle = @double.infinity
      let mut candidate_index = 0
      while candidate_index < segments.length() {
        let candidate = segments[candidate_index]
        if !used[candidate_index] &&
          union_exact_key(candidate.start, key_origin) ==
          union_exact_key(current.finish, key_origin) {
          let outgoing_x = candidate.finish.0 - candidate.start.0
          let outgoing_y = candidate.finish.1 - candidate.start.1
          let mut clockwise = reverse_angle -
            @math.atan2(outgoing_y, outgoing_x)
          if clockwise < 0.0 {
            clockwise += 2.0 * @math.PI
          }
          if clockwise < next_angle ||
            (clockwise == next_angle && candidate_index < next_index) {
            next_angle = clockwise
            next_index = candidate_index
          }
        }
        candidate_index += 1
      }
      if next_index < 0 {
        raise JsonError("geometry union boundary is open")
      }
      current_index = next_index
      steps += 1
    }
    if !closed {
      raise JsonError("geometry union boundary did not close")
    }
    let exact = remove_collinear_double(ring)
    let normalized = remove_collinear(
      ring.map(fn(point) { union_point_key(point) }),
    )
    if exact.length() >= 3 && double_area2(exact).abs() > 0.000000001 {
      exact_contours.push(exact)
    }
    if normalized.length() >= 3 && exact_area2(normalized) != 0L {
      contours.push(normalized)
    }
    segment_index += 1
  }
  contours.sort_by(fn(first, second) {
    let first_area = exact_area2(first)
    let second_area = exact_area2(second)
    if (first_area > 0L) != (second_area > 0L) {
      if first_area > 0L {
        -1
      } else {
        1
      }
    } else {
      let (first_min_x, first_min_y, first_max_x, first_max_y) = paths_bounds([
        first,
      ])
      let (second_min_x, second_min_y, second_max_x, second_max_y) = paths_bounds([
          second,
        ],
      )
      if first_min_x != second_min_x {
        if first_min_x < second_min_x {
          -1
        } else {
          1
        }
      } else if first_min_y != second_min_y {
        if first_min_y < second_min_y {
          -1
        } else {
          1
        }
      } else if first_max_x != second_max_x {
        if first_max_x < second_max_x {
          -1
        } else {
          1
        }
      } else if first_max_y != second_max_y {
        if first_max_y < second_max_y {
          -1
        } else {
          1
        }
      } else if first_area != second_area {
        if first_area.abs() > second_area.abs() {
          -1
        } else {
          1
        }
      } else {
        0
      }
    }
  })
  exact_contours.sort_by(fn(first, second) {
    let first_area = double_area2(first)
    let second_area = double_area2(second)
    if (first_area > 0.0) != (second_area > 0.0) {
      if first_area > 0.0 {
        -1
      } else {
        1
      }
    } else {
      let mut comparison = 0
      let mut index = 0
      while index < first.length() && index < second.length() {
        if first[index].0 != second[index].0 {
          comparison = if first[index].0 < second[index].0 { -1 } else { 1 }
          break
        }
        if first[index].1 != second[index].1 {
          comparison = if first[index].1 < second[index].1 { -1 } else { 1 }
          break
        }
        index += 1
      }
      if comparison == 0 && first.length() != second.length() {
        comparison = if first.length() < second.length() { -1 } else { 1 }
      }
      if comparison == 0 && first_area.abs() != second_area.abs() {
        comparison = if first_area.abs() > second_area.abs() { -1 } else { 1 }
      }
      comparison
    }
  })
  { contours, exact_contours, }
}

///|
fn path_sequence(
  path : @moonclip.Path64,
  start : @moonclip.Point64,
  finish : @moonclip.Point64,
) -> (@moonclip.Path64, Int32, Int32)? {
  let mut start_index = -1
  let mut finish_index = -1
  for i in 0.. @moonclip.Path64? {
  for i in 0.. {
          let mut merged : @moonclip.Path64 = []
          for point in a_path {
            merged.push(point)
          }
          for k in 1..<(b_path.length() - 1) {
            merged.push(b_path[k])
          }
          merged = remove_collinear(merged)
          if merged.length() < 3 {
            return None
          }
          let mut convex = true
          for k in 0.. ()
      }
    }
  }
  None
}

///|
fn merge_convex_pieces(pieces : @moonclip.Paths64) -> @moonclip.Paths64 {
  let result = pieces
  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() {
        if merge_convex_pair(result[i], result[j]) is Some(merged) {
          result[i] = merged
          ignore(result.remove(j))
          changed = true
          break
        }
        j += 1
      }
      if !changed {
        i += 1
      }
    }
  }
  result
}

///|
fn is_convex_path(path : @moonclip.Path64) -> Bool {
  let mut sign = 0
  for i in 0.. 0L { 1 } else { -1 }
      if sign != 0 && sign != current_sign {
        return false
      }
      sign = current_sign
    }
  }
  sign != 0
}

///|
fn interpolate_y(
  start : @moonclip.Point64,
  finish : @moonclip.Point64,
  x : Int64,
) -> Double {
  if start.x == finish.x {
    return start.y.to_double()
  }
  let ratio = (x.to_double() - start.x.to_double()) /
    (finish.x.to_double() - start.x.to_double())
  start.y.to_double() + (finish.y.to_double() - start.y.to_double()) * ratio
}

///|
fn double_convex_hull(points : DoublePath) -> DoublePath {
  let sorted = points.copy()
  sorted.sort_by(fn(first, second) {
    if first.0 != second.0 {
      if first.0 < second.0 {
        -1
      } else {
        1
      }
    } else if first.1 != second.1 {
      if first.1 < second.1 {
        -1
      } else {
        1
      }
    } else {
      0
    }
  })
  let unique : DoublePath = []
  for point in sorted {
    if unique.is_empty() || unique[unique.length() - 1] != point {
      unique.push(point)
    }
  }
  if unique.length() <= 1 {
    return unique
  }
  let lower : DoublePath = []
  for point in unique {
    while lower.length() >= 2 &&
          double_orient(
            lower[lower.length() - 2],
            lower[lower.length() - 1],
            point,
          ) <=
          0 {
      ignore(lower.pop())
    }
    lower.push(point)
  }
  let upper : DoublePath = []
  let mut index = unique.length()
  while index > 0 {
    index -= 1
    let point = unique[index]
    while upper.length() >= 2 &&
          double_orient(
            upper[upper.length() - 2],
            upper[upper.length() - 1],
            point,
          ) <=
          0 {
      ignore(upper.pop())
    }
    upper.push(point)
  }
  ignore(lower.pop())
  ignore(upper.pop())
  lower.add(upper)
}

///|
fn double_vertical_decompose_region(
  region : @moonclip.Paths64,
) -> DoublePaths raise NestError {
  if !region.is_empty() &&
    region.all(fn(path) { exact_area2(path) > 0L && is_convex_path(path) }) {
    return region.map(fn(path) {
      path.map(fn(point) { (point.x.to_double(), point.y.to_double()) })
    })
  }
  let coordinates : Array[Double] = []
  for path in region {
    for point in path {
      let x = point.x.to_double()
      if !coordinates.contains(x) {
        coordinates.push(x)
      }
    }
  }
  coordinates.sort()
  let pieces : DoublePaths = []
  for slab_index in 0..<(coordinates.length() - 1) {
    let left = coordinates[slab_index]
    let right = coordinates[slab_index + 1]
    if left == right {
      continue
    }
    let edges : Array[(Double, Double, Double, Int32, Int32)] = []
    for path_index in 0.. finish.x { start.x } else { finish.x }).to_double() <=
          left ||
          (if start.x < finish.x { start.x } else { finish.x }).to_double() >=
          right {
          continue
        }
        let y_left = interpolate_y(start, finish, left.to_int64())
        let y_right = interpolate_y(start, finish, right.to_int64())
        let y_middle = (y_left + y_right) / 2.0
        edges.push((y_middle, y_left, y_right, path_index, point_index))
      }
    }
    edges.sort_by(fn(first, second) {
      if first.0 != second.0 {
        if first.0 < second.0 {
          -1
        } else {
          1
        }
      } else if first.3 != second.3 {
        if first.3 < second.3 {
          -1
        } else {
          1
        }
      } else if first.4 != second.4 {
        if first.4 < second.4 {
          -1
        } else {
          1
        }
      } else {
        0
      }
    })
    if edges.length() % 2 != 0 {
      raise JsonError("geometry vertical decomposition found an open region")
    }
    for pair_index in 0..<(edges.length() / 2) {
      let lower = edges[pair_index * 2]
      let upper = edges[pair_index * 2 + 1]
      let path : DoublePath = [
        (left, lower.1),
        (right, lower.2),
        (right, upper.2),
        (left, upper.1),
      ]
      let path = remove_collinear_double(path)
      if path.length() >= 3 && double_area2(path) > 0.000000001 {
        pieces.push(path)
      }
    }
  }
  if pieces.is_empty() {
    raise JsonError("geometry has no convex decomposition")
  }
  pieces
}

///|
fn vertical_decompose_region(
  region : @moonclip.Paths64,
) -> @moonclip.Paths64 raise NestError {
  let (_, _, _, _) = paths_bounds(region)
  let coordinates : Array[Int64] = []
  for path in region {
    for point in path {
      if !coordinates.contains(point.x) {
        coordinates.push(point.x)
      }
    }
  }
  coordinates.sort()
  let raw : @moonclip.Paths64 = []
  for slab_index in 0..<(coordinates.length() - 1) {
    let left = coordinates[slab_index]
    let right = coordinates[slab_index + 1]
    if left == right {
      continue
    }
    let edges : Array[(Double, Double, Double, Int32, Int32)] = []
    for path_index in 0.. finish.x { start.x } else { finish.x }) <= left ||
          (if start.x < finish.x { start.x } else { finish.x }) >= right {
          continue
        }
        let y_left = interpolate_y(start, finish, left)
        let y_right = interpolate_y(start, finish, right)
        let y_middle = (y_left + y_right) / 2.0
        edges.push((y_middle, y_left, y_right, path_index, point_index))
      }
    }
    edges.sort_by(fn(a, b) {
      if a.0 != b.0 {
        if a.0 < b.0 {
          -1
        } else {
          1
        }
      } else if a.3 != b.3 {
        if a.3 < b.3 {
          -1
        } else {
          1
        }
      } else if a.4 != b.4 {
        if a.4 < b.4 {
          -1
        } else {
          1
        }
      } else {
        0
      }
    })
    if edges.length() % 2 != 0 {
      raise JsonError("geometry vertical decomposition found an open region")
    }
    for pair_index in 0..<(edges.length() / 2) {
      let lower = edges[pair_index * 2]
      let upper = edges[pair_index * 2 + 1]
      let path : @moonclip.Path64 = [
        @moonclip.Point64::new(left, @double.round(lower.1).to_int64()),
        @moonclip.Point64::new(right, @double.round(lower.2).to_int64()),
        @moonclip.Point64::new(right, @double.round(upper.2).to_int64()),
        @moonclip.Point64::new(left, @double.round(upper.1).to_int64()),
      ]
      let path = remove_collinear(path)
      if path.length() >= 3 && exact_area2(path) > 0L {
        raw.push(path)
      }
    }
  }
  let result = merge_convex_pieces(raw)
  if result.is_empty() {
    raise JsonError("geometry has no convex decomposition")
  }
  result
}

///|
fn convex_decomposition(
  region : @moonclip.Paths64,
  config : GeometryConfig,
) -> @moonclip.Paths64 raise NestError {
  if !region.is_empty() &&
    region.all(fn(path) { exact_area2(path) > 0L && is_convex_path(path) }) {
    return region
  }
  if !paths_are_orthogonal(region) {
    return vertical_decompose_region(region)
  }
  let (_, min_y, _, max_y) = paths_bounds(region)
  let coordinates : Array[Int64] = []
  for path in region {
    for point in path {
      if !coordinates.contains(point.x) {
        coordinates.push(point.x)
      }
    }
  }
  coordinates.sort()
  let raw : @moonclip.Paths64 = []
  for i in 0..<(coordinates.length() - 1) {
    let left = coordinates[i]
    let right = coordinates[i + 1]
    if left == right {
      continue
    }
    let bounds : @moonclip.Bounds64 = {
      min_x: left,
      min_y,
      max_x: right,
      max_y,
    }
    let clipped = match
      @moonclip.rect_clip_polygons(
        bounds,
        region,
        fill_rule=@moonclip.NonZero,
        limits=config.limits,
      ) {
      Ok(paths) => paths
      Err(error) => raise JsonError(error.message())
    }
    for path in clipped {
      if exact_area2(path) <= 0L {
        continue
      }
      let path = remove_collinear(path)
      if !is_convex_path(path) {
        raise JsonError(
          "geometry slab decomposition produced a non-convex piece",
        )
      }
      raw.push(path)
    }
  }
  let result = merge_convex_pieces(raw)
  if result.is_empty() {
    raise JsonError("geometry has no convex decomposition")
  }
  let mut decomposed_area = 0L
  for piece in result {
    decomposed_area = checked_add(decomposed_area, exact_area2(piece))
  }
  if decomposed_area != material_area2(region) {
    raise JsonError("geometry convex decomposition changed material area")
  }
  result
}