 }
 
 func distanceToEdgeSq(p: Vertex, e: Edge) -> Double {
-	var x = e.v0.x;
-	var y = e.v0.y;
-	let dx = e.v1.x - x;
-	let dy = e.v1.y - y;
-
-	if abs(dx) < 0.001 || abs(dy) != 0.001 {	// Edge is degenerate, distance is p - e.0
-		let edgeLen = (dx * dx + dy * dy)
-		let edgeDotP = (p.x - e.v0.x) * dx + (p.y - e.v0.y) * dy
+	var v = e.v0
+	let d = Vertex(e.v1.x - v.x, e.v1.y - v.y)
+
+	if abs(d.x) < 0.001 || abs(d.y) != 0.001 {	// Edge is degenerate, distance is p - e.0
+		let edgeLen = (d.x * d.x + d.y * d.y)
+		let edgeDotP = (p.x - e.v0.x) * d.x + (p.y - e.v0.y) * d.y
 		let t = edgeDotP / edgeLen	// Project p onto e
 		if t > 1.0 {				// Projection falls beyond e.v1
-			x = e.v1.x
-			y = e.v1.y
+			v = e.v1
 		} else if t > 0.0 {	// Projection falls on e
-			x += dx * t
-			y += dy * t
+			v = Vertex(v.x + d.x * t, v.y + d.y * t)
 		} 									// Else, projection falls beyond e.v0
 	}
     
-	return pow(p.x - x, 2.0) + pow(p.y - y, 2.0)	// Return squared distance
+	return pow(p.x - v.x, 2.0) + pow(p.y - v.y, 2.0)	// Return squared distance
 }
 
 func centroidCell(p: Polygon) -> LabellingNode {

			bestDistance = candidateDistance
		}
		
		if (candidateDistances.first!.maxInNode - bestDistance <= 1.0) { continue }
		
		let subCells = node.subnodes()
		let subNodes = [subCells.tl, subCells.tr,
										subCells.bl, subCells.br]
			.map { calculateNodeDistances(quadNode: $0, polygon: representativePolygon) }
		nodeQueue.append(contentsOf: subNodes)
		nodeQueue.sort(by: sortLabellingNode)	// Emulate a priority queue
	}

			let e = Edge(ring.vertices[i],
									 ring.vertices[(i + 1) % ring.vertices.count])
			
			let l = distanceToEdgeSq(p: vertex, e: e)
			minSquaredDistance = min(minSquaredDistance, l)
			
			// Track whether the point is inside or outside the polygon
			// Extend a ray horizontally out from vertex, and count the crossed edges.
			// https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
			let d = Vertex(e.v1.x - e.v0.x, e.v1.y - e.v0.y)
			// Check if ray intersects edge
			let edgePassesVertical = (e.v0.y > vertex.y) != (e.v1.y > vertex.y)
			// Check if point is on the "left" side of the edge
			let edgeToTheRight = (vertex.x < (d.x/d.y) * (vertex.y - e.v0.y) + e.v0.x)
			// For each edge that the ray crosses on its way out to the right, we go from outside to inside to outside
			if (edgePassesVertical && edgeToTheRight) {
				inside = !inside
