 
 (defn to-random-nearby [it] 
     (let [{:keys [x y]} it]        
-        (assoc it :x (+ (rand-center 5) x) 
-                  :y (+ (rand-center 5) y))))
+        (assoc it :x (+ (rand-center 10) x) 
+                  :y (+ (rand-center 10) y))))
 
-(defn center-of-points [ps] 
-    {:x (mean (map :x ps))
-     :y (mean (map :y ps))})
+(defn mean-hash [xs xs-keys]    
+    (reduce 
+        (fn [coll k] (assoc coll k (mean (map k xs)))) 
+        {} xs-keys))
+
+(defn center-of-points [ps]
+    (mean-hash ps [:x :y]))
+
+(defn average-velocity [cs]
+    (mean-hash (map :velocity cs) [:r :angle]))
 
 (defn to-point-fn [f] (fn [a b] 
     (assoc a :x (f (:x a) (:x b))


(def add-point (to-point-fn +))
(def subtract-point (to-point-fn -))

(defn abs-point [a] 
    assoc a :x (Math/abs (:x a))
            :y (Math/abs (:y a)))

(defn move-towards [r start end]
    (let [angle (:angle (cartesian->polar (subtract-point start end)))
          diff (polar->cartesian {:angle angle :r r})]
        (subtract-point start diff)))

(defn move-critters! [] 
    (let [{:keys [width height critters]} @app-state
          critter-target (center-of-points critters)
          move-towards-target #(move-towards 10 % critter-target)
          next-critters (map move-towards-target critters)]
        (swap! app-state assoc :critters next-critters)))

(defn app-loop! [] 
    (js/setTimeout (fn [] 
        (move-critters!)
        (app-loop!)) 
    100))


(defn translate [x y] (str "translate(" x "px," y "px)"))

(defn module-critter [critter] 
    (let [{:keys [x y]} critter]
        [:g.module-critter 
            {:style {:transition "transform 500ms"
                     :transform (translate x y)}}
            [:circle {:r 20 :style {:fill "brown"}}]]))

