# `BAM.Header`
[🔗](https://github.com/baoulo/bam-elixir/blob/v0.1.0/lib/bam/header.ex#L1)

BAM header and reference dictionary.

The BAM text section is a SAM header. This module keeps that text, including
trailing NUL padding, and parses `@HD`, `@SQ`, `@RG`, `@PG`, `@CO`, and any
other `@` line it does not recognise. Unknown lines stay in `:lines` so a
writer can emit them again.

The binary reference dictionary is authoritative for `ref_id`. When the text
also contains `@SQ` lines, strict decoding checks that the names and lengths
agree, in order. A missing `@SQ` list is kept as an empty parsed list and
the binary dictionary still stands.

# `line`

```elixir
@type line() :: %{type: binary(), fields: [{binary(), binary()}], raw: binary()}
```

# `ref_entry`

```elixir
@type ref_entry() :: %{name: binary(), length: non_neg_integer()}
```

# `t`

```elixir
@type t() :: %BAM.Header{
  grouping: binary() | nil,
  lines: [line()],
  name_index: %{optional(binary()) =&gt; non_neg_integer()},
  raw_text: binary(),
  references: [ref_entry()],
  sort_order: binary() | nil,
  subsorting: binary() | nil,
  version: binary() | nil
}
```

# `decode_bam`

```elixir
@spec decode_bam(binary(), BAM.Limits.t(), :strict | :permissive) ::
  {:ok, t(), non_neg_integer()}
  | {:incomplete, :header}
  | {:error, BAM.Error.t()}
```

Decodes a BAM header from the front of an uncompressed buffer.

Returns `{:incomplete, _}` when the buffer does not yet contain the header
the length fields describe. The caller reads another BGZF member and tries
again. A length that already exceeds a cap is an error, not an incomplete
read.

# `encode_bam`

```elixir
@spec encode_bam(t()) :: {:ok, binary()} | {:error, BAM.Error.t()}
```

Encodes a header as the uncompressed BAM preface: magic, text, and the
reference dictionary.

# `format_text`

```elixir
@spec format_text(t()) :: binary()
```

SAM header text, without the BAM NUL padding.

# `new`

```elixir
@spec new([ref_entry()], keyword()) :: {:ok, t()} | {:error, BAM.Error.t()}
```

Builds a header from reference maps `%{name: name, length: length}` and
optional SAM text lines.

The generated text contains `@HD` and one `@SQ` per reference, then any
extra lines passed in `:lines`.

# `parse_text`

```elixir
@spec parse_text(binary(), :strict | :permissive) ::
  {:ok, t()} | {:error, BAM.Error.t()}
```

Parses SAM header text. The result has no binary dictionary until
`references_from_sq/1` copies `@SQ` lines into `:references`.

# `ref_id`

```elixir
@spec ref_id(t(), binary()) :: {:ok, non_neg_integer()} | {:error, BAM.Error.t()}
```

Reference id for `name`, or an error when the dictionary has no such name.

# `ref_name`

```elixir
@spec ref_name(t(), integer()) :: binary() | nil
```

Reference name for a `ref_id`, or `nil` when the id is `-1` or out of range.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
