             [clojure.set :as set]))
 
 (def SCOPE-BUF-SIZE 4096)
-(def FPS 10)
-(def scopes* (atom {}))
-(def scope-pool* (atom nil))
-(def scopes-running?* (atom false))
+(def FPS 25)
+(def scopes* (ref {}))
+(def scope-pool* (agent (make-pool)))
+(def scopes-running?* (ref false))
 (def WIDTH 600)
 (def HEIGHT 400)
 (def X-PADDING 5)
 (def Y-PADDING 10)
 
-(defn- update-scope [s]
+(defn- update-scope-data [s]
   (let [{:keys [buf size width height panel y-array x-array panel]} s
         frames (buffer-data buf)
         step (int (/ (buffer-size buf) width))
         y-scale (/ (- height (* 2 Y-PADDING)) -2)
         y-shift (+ (/ height 2) Y-PADDING)]
-    (dotimes [x width]
-      (aset ^ints y-array x
-            (int (+ y-shift
-                    (* y-scale
-                       (aget ^floats frames (unchecked-multiply x step)))))))
+    (if-not (empty? frames)
+      (dotimes [x width]
+        (aset ^ints y-array x
+              (int (+ y-shift
+                      (* y-scale
+                         (aget ^floats frames (unchecked-multiply x step))))))))
+
     (.repaint panel)))
 
 (defn- update-scopes []
-  (doall (map update-scope (vals @scopes*))))
+  (doall (map update-scope-data (vals @scopes*))))
 
 (defn- paint-scope [g id]
   (if-let [scope (get @scopes* id)]

         (.show)
         (.setAlwaysOnTop keep-on-top)))))

(defn- create-pool-if-necessary []
  (if-not @scope-pool* (reset! scope-pool* (make-pool))))


(defn- start-scopes-runner
  []
  (periodic update-scopes (/ 1000 FPS) 0 @scope-pool*))

(defn scopes-start
  []
  (if-not @scopes-running?*
    (do
      (create-pool-if-necessary)
      (start-scopes-runner)
      (reset! scopes-running?* true))))

;;  (.cancel (:runner @scope*) true)
(defn scopes-stop
  []
  (stop-and-reset-pool! scope-pool*)
  (reset! scopes-running?* false))


(defn- scope-bus
  "Set a bus to view in the scope."
  [s]
  (let [buf (buffer SCOPE-BUF-SIZE)
        _ (wait-for-buffer buf)
        bus-synth (bus->buf :target 0 :position :tail (:num s) buf)]
    (assoc s
      :size SCOPE-BUF-SIZE
      :bus-synth bus-synth

   (java.awt.geom Rectangle2D$Float Path2D$Float)
   (javax.swing JFrame JPanel))
  (:use
   [overtone event util time-utils deps]
   [overtone.sc core synth ugen buffer node]
   [overtone.studio.util]
   clojure.stacktrace)
