 ;; notifications from the server.  (e.g. When an envelope trigger fires to
 ;; free a synth.)
 
-(defn mk-bitset [size]
+(defn mk-bitset
+  "Create a vector representation of a bitset"
+  [size]
   (vec (repeat size false)))
 
 (defonce allocator-bits
   {:node         (ref (mk-bitset MAX-NODES))
    :audio-buffer (ref (mk-bitset MAX-BUFFERS))
-   :audio-bus    (ref (mk-bitset MAX-NODES))
-   :control-bus  (ref (mk-bitset MAX-NODES))})
-
-(defonce allocator-limits
-  {:node         MAX-NODES
-   :audio-buffer MAX-BUFFERS
-   :audio-bus    MAX-AUDIO-BUS
-   :control-bus  MAX-CONTROL-BUS})
+   :audio-bus    (ref (mk-bitset MAX-AUDIO-BUS))
+   :control-bus  (ref (mk-bitset MAX-CONTROL-BUS))})
 
 (defn- fill-gaps
-  "Fill a given vector bs with size consecutive vals from idx"
+  "Returns a new vector similar to bs except filled with with size consecutive vals from idx
+
+  example: (fill with 3 from idx 1 for 2 vals)
+  (fill-gaps [1 0 0 0 1] 1 2 3) ;=> [1 3 3 0 1]"
   [bs idx size val]
   (loop [bs bs
          idx idx

  ([k] (alloc-id k 1 nil))
  ([k size] (alloc-id k size nil))
  ([k size action-fn]
     (let [bits  (get allocator-bits k)
           limit (get allocator-limits k)]
       (when-not bits
         (throw (Exception. (str "Unable to get allocator bits for keyword " k))))
       (when-not limit
         (throw (Exception. (str "Unable to get allocator limit for keyword " k))))
       (dosync
        (let [id (find-gap @bits size 0 0 limit)]
          (alter bits fill-gaps id size true)
          (when action-fn (execute-action-fn #(action-fn id) "alloc-id"))
          id)))))

(defn clear-ids
  "Clear all ids allocated for key."
  [k]
  (let [bits (get allocator-bits k)]
    (dosync
     (let [new-bitset (mk-bitset (count @bits))]
       (ref-set bits new-bitset)))
    :cleared))
