 ;; =============================================================================
 ;; The Ned Flanders function
 
-(defn neighborinos [idx image-data color]
+(defn neighborinos [idx image-data doc-width doc-height color]
   (let [left   (dec idx)
         right  (inc idx)
-        top    (- idx 64)
-        bottom (+ idx 64)
+        top    (- idx doc-width)
+        bottom (+ idx doc-width)
         result [left right top bottom]
-        valid-result (filter #(and (>= % 0) (< % 4096)) result)]
+        total-pixel-count (* doc-width doc-height)
+        valid-result (filter #(and (>= % 0) (< % total-pixel-count)) result)]
     (filter #(= (nth image-data %) color) valid-result)))
 
 

      (let [current (first to-connect)
            connected (conj connected current)
            to-connect (disj to-connect current)
            candidates (set (neighborinos current image-data color))
            to-connect (sets/union to-connect (sets/difference candidates connected))]
        (recur connected to-connect)))))


(defn visit-pixels-for-fill-tool [doc-x doc-y image-data]
  (let [[orig-x orig-y] (get-in @guistate/transient-state [:mouse-down-pos])
        idx (geometry/flatten-to-index orig-x orig-y 64)
        color (nth image-data idx)
        fill-target (flood idx image-data color)]
    (doseq [i fill-target]
      (visit-pixel i))))


                  zoom-factor (get-in @app [:zoom-factor])
                  [doc-x doc-y] (geometry/screen-to-doc x y zoom-factor)
                  doc-width (get-in @app [:main-app :canvas-width])
                  doc-height (get-in @app [:main-app :canvas-height])
                  paint-tool (get-in @app [:tools :paint-tool])]

                  (when (= event-type "mousedown")
