             layer.removeFromSuperlayer()
         }
         layers.removeAll()
+        imageCache.removeAll()
         index = 0
         imageView.image = image
         setTransformAnimated(CGAffineTransformIdentity)

            builder.minSegment = 8.0 / xform.a
        }
    }
    // Transient properties for handlePinch
    var anchor = CGPoint.zero
    var delta = CGPoint.zero

    
    @IBAction func undo() {
        index -= 1
        if let (i, image) = imageCache.last {
            assert(i <= index)
            print("using cache", i, index)
            imageView.image = image
            renderLayers(i..<index)
        } else {
            imageView.image = image
            renderLayers(0..<index)
        }
        if let (i,_) = imageCache.last where i == index{
            print("uncaching", index)
            imageCache.removeLast()
        }
        updateUI()
    }

    @IBAction func redo() {
        renderLayers(index...index)
        index += 1
        if index % cycle == 0 {
            print("caching", index)
            imageCache.append((index, imageView.image))
        }
        updateUI()
    }
    
