             [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)]

           kind (if (= -1 buf) :bus :buf)
           num  (if (= -1 buf) bus buf)
           s (mk-scope num kind keep-on-top WIDTH HEIGHT)]
       (swap! scopes* assoc (:id s) s)
       (scopes-start))))

(defn pscope
  "Creates a 'perminent' scope, i.e. one where the window is always kept on top of other OS windows. See scope."
  ([& args]
     (apply scope (concat args [:keep-on-top true]))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

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

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

(defn scopes-start
  []
  (dosync
   (when-not @scopes-running?*
     (start-scopes-runner)
     (ref-set scopes-running?* true))))

(defn scopes-stop
  []
  (dosync
   (stop-and-reset-pool! scope-pool*)
   (ref-set scopes-running?* false)))

(defn- start-bus-synth
  [bus buf]
  (bus->buf :target 0 :position :tail bus buf))

(defn- scope-bus
  "Set a bus to view in the scope."
  [s]
  (let [buf (buffer SCOPE-BUF-SIZE)
        bus-synth (start-bus-synth (:num s) buf)]
    (assoc s
      :size SCOPE-BUF-SIZE
      :bus-synth bus-synth
