 
 (defn start!
   "Remove all scheduled events and start the clock."
-  [clock]
-  (let [{:keys [context started]} @clock]
-    (when-not started
-      (swap! clock assoc :events [])
-      (let [clock-node (doto (.createScriptProcessor context 256 1 1)
-                         (.connect (.-destination context))
-                         (aset "onaudioprocess" #(tick! clock)))]
-        (swap! clock assoc :clock-node clock-node :started true)
-        clock))))
+  [clock-atom]
+  (swap! clock-atom
+         (fn [{:keys [context started] :as clock}]
+           (if started
+             clock
+             (let [clock-node (doto (.createScriptProcessor context 256 1 1)
+                                (.connect (.-destination context))
+                                (aset "onaudioprocess" #(tick! clock-atom)))]
+               (assoc clock
+                      :started    true
+                      :events     []
+                      :clock-node clock-node))))))
 
 (defn stop!
   "Stops the clock."
-  [clock]
-  (let [{:keys [started clock-node]} @clock]
-    (when started
-      (.disconnect clock-node)
-      (swap! clock assoc :started false :clock-node nil)
-      clock)))
+  [clock-atom]
+  (swap! clock-atom
+         (fn [{:keys [started clock-node] :as clock}]
+           (if started
+             (do
+               (.disconnect clock-node)
+               (-> clock (assoc :started false) (dissoc :clock-node)))
+             clock))))

(declare execute! schedule*)

(defn- tick!
  "This function is ran periodically, and at each tick it executes
   events for which `currentTime` is included in their tolerance interval."
  [clock]
  (let [{:keys [events]} @clock
        current-time (current-time clock)
        execute-now? #(<= (:earliest-time %) current-time)
        now (take-while execute-now? events)]
    (doseq [event now] (execute! event))
    (swap! clock assoc :events (drop-while execute-now? (:events @clock))
                       :current-time current-time)))

(defn- index-by-time
  "Does a binary search to find the index of the first event whose deadline is

(declare repeat!)

(defn- execute!
  [{:keys [action clock-id latest-time repeat-time] :as event}]
  (let [clock @(get *clocks* clock-id)]
    (when (< (current-time clock) latest-time)
      (action))
    (when repeat-time
