         }
     }
     
+    fileprivate static func leafNodeIndexToElementIndex(_ nodeIndex: Int, leafCount: Int, lastRowIndex: Int) -> Int {
+        assert(nodeIndex + 1 >= leafCount, "not actually a leaf (index of left child is a valid node")
+        var elementIndex = nodeIndex - lastRowIndex
+        if elementIndex < 0 {
+            elementIndex += leafCount
+        }
+        return elementIndex
+    }
+    
     init(boxes leafBoxes: [BoundingBox]) {
         // create a complete binary tree of bounding boxes where boxes[0] is the root and left child is 2*index+1 and right child is 2*index+2
         let boxes = UnsafeMutablePointer<BoundingBox>.allocate(capacity: 2*leafBoxes.count-1)
+        
+
+        self.elementCount = leafBoxes.count
+        
         self.inodeCount = leafBoxes.count-1
+        
+        var lastRowIndex = 0
+        while lastRowIndex < self.inodeCount {
+            lastRowIndex *= 2
+            lastRowIndex += 1
+        }
+        self.lastRowIndex = lastRowIndex
+
+        
         for i in 0..<leafBoxes.count {
-            boxes[i+self.inodeCount] = leafBoxes[i]
+            let nodeIndex = i+self.inodeCount
+            let elementIndex = BVH.leafNodeIndexToElementIndex(nodeIndex, leafCount: leafBoxes.count, lastRowIndex: lastRowIndex)
+            boxes[nodeIndex] = leafBoxes[elementIndex]
         }
         for i in stride(from: self.inodeCount-1, through: 0, by: -1) {
             boxes[i] = BoundingBox(first: boxes[2*i+1], second: boxes[2*i+2])

            let leaf1 = index1 >= inodecount
            let leaf2 = index2 >= inodecount
            if leaf1, leaf2 {
                if index1 < index2 {
                    callback(index1 - inodecount, index2 - inodecount)
                }
                else {
                    callback(index2 - inodecount, index1 - inodecount)
                }
            }
            else if leaf1 {
                intersects(index1: index1, index2: 2*index2+1, callback: callback)

            return .internal
        }
        else {
            return .leaf(elementIndex: BVH.leafNodeIndexToElementIndex(index, leafCount: self.bvh.takeUnretainedValue().elementCount, lastRowIndex: self.bvh.takeUnretainedValue().lastRowIndex ))
        }
    }
    
