                  lidx*))
       :largest-seen (max win-end largest-seen))))
 
+(defn- finish-linear-index
+  "Optimizes the linear index for safety. This seems unnecessary, but samtools
+  does this process."
+  [linear-index]
+  (let [{lidx :index, largest-lidx-seen :largest-seen} linear-index]
+   (loop [i 0
+          lidx* []
+          last-non-zero 0]
+     (if (<= i largest-lidx-seen)
+       (let [l (long (nth lidx i))]
+         (if (zero? l)
+           (recur (inc i) (conj lidx* last-non-zero) last-non-zero)
+           (recur (inc i) (conj lidx* l) l)))
+       lidx*))))
+
 (defn- init-index-status []
   {:meta-data    (init-meta-data)
    :bin-index    (init-bin-index)

(defn pos->lidx-offset
  [pos]
  (bit-shift-right (if (<= pos 0) 0 (dec pos)) bam-lidx-shift))

(defn- optimize-lidx
  "Optimizes the linear index for safety. This seems unnecessary, but samtools
  does this process."
  [lidx largest-lidx-seen]
  (loop [i 0
         lidx* []
         last-non-zero 0]
    (if (<= i largest-lidx-seen)
      (let [l (long (nth lidx i))]
        (if (zero? l)
          (recur (inc i) (conj lidx* last-non-zero) last-non-zero)
          (recur (inc i) (conj lidx* l) l)))
      lidx*)))

(defn- init-meta-data []
  {:first-offset  -1

  (lsb/write-long w (:aligned-alns meta-data))
  (lsb/write-long w (:unaligned-alns meta-data)))

(defn- finish-index
  [refs index]
  (loop [[f & r] refs
         index index]
    (if f
      (let [rname (:name f)]
        (recur r (-> index
                     (update-in [rname :bins] finish-bin-index)
                     (update-in [rname :lidx] finish-linear-index))))
      index)))

(defn- write-index*!
  [wtr refs alns]
  ;; magic
  (lsb/write-bytes wtr (.getBytes bai-magic))
  ;; n_ref
  (lsb/write-int wtr (count refs))
  (let [indices (make-index1 refs alns)] ; TODO: parallelize
    (doseq [ref refs]
      (let [index (get indices (:name ref))
            n-bin (count (:bins index))]
