       (move-indicator-to i))))
 
 (defn add-new-branch [branch]
-  (let [new-branch-morph (branch-morph 
-                          5 (+ 5 (* branch-height @branch-count)) 
+    (let [new-branch-morph (branch-morph 
+                          5 (+ 5 (* branch-height (dec @branch-count))) 
                          (- diagram-width 0) branch-height branch)]
-    (swap! branch-count inc)
-    (add-morph history-view "wrapper" new-branch-morph)
-    (set-extent history-view "wrapper" {:x diagram-width :y (+ 10 (* branch-height @branch-count))})
-    (switch-to-branch branch)
-    (.log js/console (morphic/dict->js @history-view))))
+      (add-morph history-view "wrapper" new-branch-morph)
+      (set-extent history-view "wrapper" {:x (+ diagram-width 10) :y (+ 10 (* branch-height @branch-count))})
+      (switch-to-branch branch))
+    (.log js/console (morphic/dict->js @history-view)))
 
 ;; snapshot the state when it is changed:
 


(defn revert-to [i]
  (prn "request revert: " i)
  (let [index (* (dec (count @(@current-branch :coll))) (/ i 100))]
    (when-let [state (when (>= index 1) (nth-history index))]
      (prn "revert to: " index)
      (reset! app-state state)

(def app-state (atom nil))

;; global atom referencing the total history graph
(def app-history (atom [@app-state]))


(defn init-history [init-state]
  (reset! app-state init-state)
  (reset! app-history [init-state])
  (reset! (@current-branch :data) @app-history)
  (add-morph history-view (@current-branch :id) history-indicator))

(def branch-count (atom 1))

(defn generate-uuid []
  @branch-count)

;; global atom referencing the branch that we currently operate on
(def current-branch (atom {:id (generate-uuid) :data (atom @app-history)}))

;; ffd
(def history-view)

(defn switch-to-branch [branch]
  (prn "old branch id: " (@current-branch :id))
  (prn "new branch id: "  (branch :id))
  (remove-morph history-view (@current-branch :id) "indexMorph")
  (set-fill history-view (@current-branch :id) "lightgrey")
  (set-fill history-view (branch :id) "green")
  (add-morph history-view (branch :id) history-indicator)
  (reset! current-branch branch))

(defn nth-history 
  ([i] 
    (nth-history i @current-branch))
  ([i {:keys [_ data]}]
    ;; lookup in unrolled linked list
    (if (< i (dec (count @data))) 
      (nth @data i)
      (when-let [cont ((last @data) :cont)]
        (nth-history (- i (dec (count @data))) cont)
        nil))))

(defn len [unrolled-list]
  (+ -1 (count unrolled-list) 
    (when-let [end (last unrolled-list)]
      (when-let [n (end :cont)] (len n)))))

(def history-indicator
  {:id "indexMorph"
