         (recur (inc i))))
     @new-lidx))
 
-(defn- write-null-content
-  [w]
-  (lsb/write-long w 0))
-
 (defn- write-bin
   [w bin]
-  {:pre (< (:bin-num bin) max-bins)}
-  ;; bin
-  (lsb/write-int w (:bin-num bin))
+  (lsb/write-int w (:idx bin))
   ;; chunks
   (lsb/write-int w (count (:chunks bin)))
   (doseq [c (:chunks bin)]

(defn writer
  [f refs]
  (->BAIWriter (DataOutputStream. (FileOutputStream. (file f)))
               (writer-status refs)
               f))

(defn write-index
  [^BAIWriter wtr alns]
  (try
    (let [w (.writer wtr)
          s (.status wtr)]
      ;; magic
      (lsb/write-bytes w (.getBytes bai-magic))
      ;; n_ref
      (lsb/write-int w (count (:refs s)))
      ;; TODO this is new implementation
      (pprint (make-index (:refs s) alns))
      (doseq [aln alns] (write-index* w s aln))
      ;; Write data about last ref
      (write-ref! w s)
      (write-no-coordinate-alns-count w @(:meta s)))
    (catch Exception e (do
                         (let [f (file (.f wtr))]
                           (when (.exists f)

              (swap! meta assoc :first-offset (:beg (:chunk (:meta aln)))))
            (if (< (bgzf-util/compare (:last-offset @meta)
                                      (:end (:chunk (:meta aln)))) 1)
              (swap! meta assoc :last-offset (:end (:chunk (:meta aln)))))))
      ;; bins
      (let [chunk-beg (:beg (:chunk (:meta aln)))
            chunk-end (:end (:chunk (:meta aln)))]
        (let [bin-idx (sam-util/compute-bin aln)
              bin (if (nil? (nth @bins bin-idx))
                    (do
                      (swap! bins assoc bin-idx {:idx bin-idx, :chunks nil})
                      (swap! bins-seen inc)
                      (nth @bins bin-idx))
                    (nth @bins bin-idx))]
          ;; chunk
          (if (seq (:chunks bin))
            (if (bgzf-util/same-or-adjacent-blocks? (:end (last (:chunks bin)))
                                                    chunk-beg)
              (let [last-idx (dec (count (:chunks bin)))
                    last-chunk (last (:chunks bin))
                    new-chunks (assoc (:chunks bin) last-idx (assoc last-chunk :end chunk-end))
                    new-bin (assoc bin :chunks new-chunks)]
                (swap! bins assoc bin-idx new-bin))
              (let [new-bin (update-in bin [:chunks] conj (:chunk (:meta aln)))]
                (swap! bins assoc bin-idx new-bin)))
            (let [new-bin (assoc bin :chunks (vector (:chunk (:meta aln))))]
              (swap! bins assoc bin-idx new-bin))))
        ;; lenear index
        (let [aln-beg (:pos aln)
              aln-end (+ aln-beg (cgr/count-ref (:cigar aln)))
