 
 (defn sort-by-qname [rdr wtr]
   (let [alns (sort-alignments-by-qname rdr)
-        hdr (replace-header (io/read-header rdr)
+        hdr (replace-header (into (sorted-map) (io/read-header rdr))
                             version
                             (name order-queryname))]
     (io/write-header wtr hdr)

  (format "%s/%s_%05d.sorted.cache" util/temp-dir prefix i))

(defn- find-head
  ([keyfn l]
     (reduce (fn [e1 e2]
               (condp = (compare e1 e2)
                 0 e1
                 1 e2
                 -1 e1))
             l)))

(defn- head
  [blocks ref-map]
  (find-head
         (fn [[idx1 b1] [idx2 b2]]
           (compare-key-pos ref-map b1 b2))
         (filter
          (fn [[_ b]] (not (nil? b)))
          (map-indexed vector blocks))))

(defn split-sam
  [rdr name-fn]
  (doall
   (map
    (fn [[i blks]]
      (let [f (name-fn i)
            hdr (io/read-header rdr)]
        (with-open [wtr (bam/writer f)]
          (io/write-header wtr hdr)
          (io/write-refs wtr hdr)
          (io/write-blocks wtr blks))
        f))
    (map-indexed vector (partition-all chunk-size (io/read-blocks rdr))))))

(defn merge-sam
  [wtr header name-fn n]
  (let [rdrs (map #(bam/reader (name-fn %) :ignore-index true) (range n))
        ref-map (apply merge
                       (map-indexed (fn [i val] {val i})
                                    (map :name (sam-util/make-refs header))))]
    (io/write-header wtr header)
    (io/write-refs wtr header)
    (loop [blocks-list (map #(io/read-blocks % {:mode :coordinate}) rdrs)]

        sorted-cache-name-fn (partial gen-sorted-cache-filename basename)
        splited-files (split-sam rdr cache-name-fn)
        num-splited (count splited-files)
        hdr (replace-header (into (sorted-map) (io/read-header rdr))
                            version
                            (name order-coordinate))]
    (doseq [idxs (partition-all util/num-cores (range num-splited))]
