           {}
           (partition 2 1 nodeseq)))
 
-(defn prolog
-  [g]
-  (println "digraph {
-     rankdir=LR;
-     node[shape=\"plaintext\"];
-     edge[arrowhead=\"none\"];"))
-
-(defn rank
-  [nodes]
+(defn emit-rank
+  [[r nodes]]
   (println "subgraph {\nrank=same;")
   (doseq [n nodes]
     (println (str (:id n) " [label=\"" (:label n) "\"];")))
   (println "}"))
 
-(defn dependencies
+(defn emit-dependencies
   [g]
   (doseq [n (nodes g)
-        trg (next-nodes g n)]
+          trg (next-nodes g n)]
     (println (str (:id n) "->" (:id trg) ";"))))
-
-(defn epilog
-  [g]
-  (println "}"))
-
-(defn ranks-in [g] (set (map :level (nodes g))))
 
 (defn emit-dot
   [g]
-  (prolog g)
-  (doseq [r (ranks-in g)]
-    (rank (filter #(= r (:level %)) (nodes g))))
-  (dependencies g)
-  (epilog g))
+  (println "digraph {
+     rankdir=LR;
+     node[shape=\"plaintext\"];
+     edge[arrowhead=\"none\"];")
+  (doall (map emit-rank (sort (group-by :level (keys g)))))
+  (emit-dependencies g)
+  (println "}"))
 
 (defn -main [& args]
   (doseq [f args]

  (:require (clojure [string :as str]))
  (:gen-class))

(def id-sequence (atom 0))
(defn get-id! [] (str "node" (dosync (swap! id-sequence inc))))

(defn make-node [t l] {:id (get-id!) :level t :label l})

(defn add-node [g n] (if (g n) g (assoc g n {:next #{} :prev #{}})))


     (update-in [n1 :next] conj n2)
     (update-in [n2 :prev] conj n1)))

(defn next-nodes [g n] (get-in g [n :next]))
(defn prev-nodes [g n] (get-in g [n :prev]))
(defn nodes [g] (keys g))

(defn split-lines [str] (filter (comp not empty?) (str/split str #"\n")))

(defn nodify
  [line]
  (let [stars (count (take-while #(= \* %) line))]
    (if (> stars 0) (make-node stars (clojure.string/trim (subs line stars))))))

(defn insert-root [nodes] (conj nodes (make-node 0 "Utility")))

