      (entries-sexp items)]))
 
 (defn subgenres-sexp [items fmt genre]
-  (mapcat #(subgenre-sexp items fmt genre %) layout/subgenres))
+  (mapcat #(subgenre-sexp items fmt genre %) (order (keys items))))
 
 (defn genre-sexp [items fmt genre]
   (when-let [items (genre items)]

    (header :verso)

    [:fo:flow {:flow-name "xsl-region-body"}
     (toc items layout/formats)
     (mapcat #(format-sexp items %) layout/formats)]]])

(defn document [items & args]
  (-> items

  [:fo:block {:keep-with-next "always"}
   [:fo:marker {:marker-class-name running-header-class-name} title]])

(defn- order
  "Return `items` ordered. Checks first if `items` are either a subset
  of `layout/formats`, `layout/braille-genres` or `layout/subgenres`
  and consequently orders accordingly. Return nil if `items` are not a
  subset of either."
  [items]
  (let [items (set (remove nil? items))]
    (cond
      (set/subset? items (set layout/formats))
      (keep items layout/formats)
      (set/subset? items (set layout/braille-genres))
      (keep items layout/braille-genres)
      (set/subset? items (set layout/subgenres))
      (keep items layout/subgenres))))

(defn- toc-entry [items path]
  [:fo:block (if (<= (count path) 2)
               {:text-align-last "justify"}
               {:text-align-last "justify" :start-indent "1em"})
   [:fo:basic-link {:internal-destination (hash path)}
    (str (layout/translations (last path)) " ")
    [:fo:leader {:leader-pattern "dots"}]
    [:fo:page-number-citation {:ref-id (hash path)}]]])

(defn toc [items]
  [:fo:block {:line-height "150%"}
   (h1 :inhalt)
   (keep #(toc-entry items [%]) (order (keys items)))])

(defn- sub-toc-entry [items path]
  [:fo:block
   [:fo:block {:text-align-last "justify"}
    [:fo:basic-link {:internal-destination (hash path)}
     (str (layout/translations (last path)) " ")
     [:fo:leader {:leader-pattern "dots"}]
     [:fo:page-number-citation {:ref-id (hash path)}]]]
   (when (map? items)
     (keep #(toc-entry items (conj path %)) (order (keys items))))])

(defn sub-toc [items path]
  (when (map? items)
    [:fo:block {:line-height "150%"}
     (keep #(sub-toc-entry (% items) (conj path %)) (order (keys items)))]))

(def wrap (layout/wrapper ""))

