        1 (fn [^afterglow.rhythm.Metronome metronome]
            (let [sync-handler (ClockSync. metronome (first result) (ref (ring-buffer max-clock-intervals))
                                           (ref (ring-buffer max-clock-intervals))
-                                          (ref {:master (get-in @clock-sources [(first result) :master])}))]
+                                          (ref {:master (get-in @clock-sources [(:device (first result)) :master])}))]
              (sync-start sync-handler)
              sync-handler))
 

     nil)))

(defn- add-synced-metronome
  [midi-clock-source metronome sync-fn]
  (swap! synced-metronomes #(assoc-in % [midi-clock-source metronome] sync-fn)))

(defn- remove-synced-metronome
  [midi-clock-source metronome]
  (swap! synced-metronomes #(update-in % [midi-clock-source] dissoc metronome)))

(defn- traktor-beat-phase-current
  "Checks whether our clock is being synced to ordinary MIDI clock, or

  midi-transfer-thread
  (atom nil))

(declare open-inputs-if-needed!)
(declare open-outputs-if-needed!)

(defn- handle-environment-changed
  "Called when we had an event posted to the MIDI event queue telling
  us that the environment has changed, i.e. a device has been added or
  removed. Update our notion of the environment state accordingly."
  []
  (timbre/info "MIDI Environment changed!")
  ;; TODO: look for any inputs or outputs that have disappeared,
  ;;       and notify any watchers. Remove them from listener lists,
  ;;       metronome sync lists, etc.
  ;;
  ;;       Also close them, if that now seems safe?
  (open-inputs-if-needed!)
  (open-outputs-if-needed!))

(defn- delegated-message-handler
  "Takes incoming MIDI events from the incoming queue on a thread with
