         CGContextScaleCTM(cgContext, 1.0, -1.0)
     }
     
-    func pointColor(p:NSPoint) -> NSColor {
-        
-        let data = CGBitmapContextGetData(cgContext)
-        let dataType = UnsafePointer<UInt8>(data)
+    private func _pointColor(p:NSPoint, pixelBuffer:UnsafePointer<UInt8>) -> NSColor {
+        
         let offset = 4 * ((Int(self.width) * Int(p.y) + Int(p.x)))
         
-        let r = dataType[offset]
-        let g = dataType[offset+1]
-        let b = dataType[offset+2]
-        let a = dataType[offset+3]
+        let r = pixelBuffer[offset]
+        let g = pixelBuffer[offset+1]
+        let b = pixelBuffer[offset+2]
+        let a = pixelBuffer[offset+3]
         
         return NSColor(
             calibratedRed: CGFloat(Double(r)/255.0),

            alpha: CGFloat(Double(a)/255.0))
    }
    
    func setPointColor(p:NSPoint, color:NSColor) {
        let data = CGBitmapContextGetData(cgContext)
        let dataType = UnsafeMutablePointer<UInt8>(data)
        let offset = 4 * ((Int(self.width) * Int(p.y) + Int(p.x)))
        
        guard let normalizedColor = color.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) else {
            print("-- cannot normalize color \(color)")
            return
        }
        
        dataType[offset] = UInt8(normalizedColor.redComponent * 255.0)
        dataType[offset+1] = UInt8(normalizedColor.greenComponent * 255.0)
        dataType[offset+2] = UInt8(normalizedColor.blueComponent * 255.0)
        dataType[offset+3] = UInt8(normalizedColor.alphaComponent * 255.0)
    }
    
    subscript(x:Int, y:Int) -> NSColor {

    func fill(p:NSPoint, color newColor:NSColor) {
        // floodFillScanlineStack from http://lodev.org/cgtutor/floodfill.html
        
        let pixelBuffer = UnsafeMutablePointer<UInt8>(CGBitmapContextGetData(cgContext))
        
        let oldColor = _pointColor(p, pixelBuffer:pixelBuffer)
        
        if oldColor == newColor { return }
        
        guard let newColorNormalized = newColor.colorUsingColorSpaceName(NSCalibratedRGBColorSpace) else {
            print("-- cannot normalize color \(newColor)")
            return
        }
        
        var stack : [NSPoint] = [p]
        
        while let pp = stack.popLast() {
            
            var x1 = pp.x
            
            while(x1 >= 0 && _pointColor(P(x1, pp.y), pixelBuffer:pixelBuffer) == oldColor) {
                x1--
            }
            
