let item_to_raw () =
    let name = "sam_item_to_raw" in
    let raw_queue = Dequeue.create () in
    let raw_items_count = ref 0 in
    let reference_sequence_dictionary = ref [| |] in
    let reference_sequence_dictionary_to_output = ref 0 in
    let rec next stopped =
      dbg "raw_items_count: %d refdict-to-out: %d   raw_queue: %d  "
        !raw_items_count
        !reference_sequence_dictionary_to_output
        (Dequeue.length raw_queue);
      begin match !reference_sequence_dictionary_to_output with
      | 0 ->
        begin match Dequeue.is_empty raw_queue with
        | true when stopped -> `end_of_stream
        | true (* when not stopped *) -> `not_ready
        | false ->
          incr raw_items_count;
          begin match Dequeue.dequeue_exn raw_queue `front with
          | `comment c ->
            dbg "comment"`output (Ok (`comment c))
          | `header_line (version, sorting, rest) ->
            dbg "header";
            `output (Ok (`header ("HD",
                                ("VN", version)
                                :: ("SO",
                                    match sorting with
                                    | `unknown -> "unknown"
                                    | `unsorted -> "unsorted"
                                    | `queryname -> "queryname"
                                    | `coordinate -> "coordinate")
                                :: rest)))
          | `reference_sequence_dictionary rsd ->
            dbg "reference_sequence_dictionary %d" (Array.length rsd);
            reference_sequence_dictionary := rsd;
            reference_sequence_dictionary_to_output := Array.length rsd;
            next stopped
          | `header ("SQ", _) ->
            dbg "skipping SQ line";
          (* we simply skip this one *)
            next stopped
          | `header h ->
            dbg "header %s" (fst h);
            `output (Ok (`header h))
          | `alignment al ->
            dbg "alignment";
            downgrade_alignment al |> (fun x -> `output x)
          end
        end
      | n ->
        let o =
          !reference_sequence_dictionary.(
            Array.length !reference_sequence_dictionary - n) in
        reference_sequence_dictionary_to_output := n - 1;
        `output (Ok (`header ("SQ", reference_sequence_to_header o)))
      end
    in
    Biocaml_transform.make ~name ~feed:(Dequeue.enqueue raw_queue `back) ()
      ~next