Added notes on how the package is tested.
[samtools.git] / bam.h
1 /* The MIT License
2
3    Copyright (c) 2008 Genome Research Ltd (GRL).
4
5    Permission is hereby granted, free of charge, to any person obtaining
6    a copy of this software and associated documentation files (the
7    "Software"), to deal in the Software without restriction, including
8    without limitation the rights to use, copy, modify, merge, publish,
9    distribute, sublicense, and/or sell copies of the Software, and to
10    permit persons to whom the Software is furnished to do so, subject to
11    the following conditions:
12
13    The above copyright notice and this permission notice shall be
14    included in all copies or substantial portions of the Software.
15
16    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20    BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21    ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23    SOFTWARE.
24 */
25
26 /* Contact: Heng Li <lh3@sanger.ac.uk> */
27
28 #ifndef BAM_BAM_H
29 #define BAM_BAM_H
30
31 /*!
32   @header
33
34   BAM library provides I/O and various operations on manipulating files
35   in the BAM (Binary Alignment/Mapping) or SAM (Sequence Alignment/Map)
36   format. It now supports importing from or exporting to TAM, sorting,
37   merging, generating pileup, and quickly retrieval of reads overlapped
38   with a specified region.
39
40   @copyright Genome Research Ltd.
41  */
42
43 #include <stdint.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <stdio.h>
47
48 #ifndef BAM_LITE
49 #define BAM_VIRTUAL_OFFSET16
50 #include "bgzf.h"
51 /*! @abstract BAM file handler */
52 typedef BGZF *bamFile;
53 #define bam_open(fn, mode) bgzf_open(fn, mode)
54 #define bam_dopen(fd, mode) bgzf_fdopen(fd, mode)
55 #define bam_close(fp) bgzf_close(fp)
56 #define bam_read(fp, buf, size) bgzf_read(fp, buf, size)
57 #define bam_write(fp, buf, size) bgzf_write(fp, buf, size)
58 #define bam_tell(fp) bgzf_tell(fp)
59 #define bam_seek(fp, pos, dir) bgzf_seek(fp, pos, dir)
60 #else
61 #define BAM_TRUE_OFFSET
62 #include <zlib.h>
63 typedef gzFile bamFile;
64 #define bam_open(fn, mode) gzopen(fn, mode)
65 #define bam_dopen(fd, mode) gzdopen(fd, mode)
66 #define bam_close(fp) gzclose(fp)
67 #define bam_read(fp, buf, size) gzread(fp, buf, size)
68 /* no bam_write/bam_tell/bam_seek() here */
69 #endif
70
71 /*! @typedef
72   @abstract Structure for the alignment header.
73   @field n_targets   number of reference sequences
74   @field target_name names of the reference sequences
75   @field target_len  lengths of the referene sequences
76   @field dict        header dictionary
77   @field hash        hash table for fast name lookup
78   @field rg2lib      hash table for @RG-ID -> LB lookup
79   @field l_text      length of the plain text in the header
80   @field text        plain text
81
82   @discussion Field hash points to null by default. It is a private
83   member.
84  */
85 typedef struct {
86         int32_t n_targets;
87         char **target_name;
88         uint32_t *target_len;
89         void *dict, *hash, *rg2lib;
90         size_t l_text, n_text;
91         char *text;
92 } bam_header_t;
93
94 /*! @abstract the read is paired in sequencing, no matter whether it is mapped in a pair */
95 #define BAM_FPAIRED        1
96 /*! @abstract the read is mapped in a proper pair */
97 #define BAM_FPROPER_PAIR   2
98 /*! @abstract the read itself is unmapped; conflictive with BAM_FPROPER_PAIR */
99 #define BAM_FUNMAP         4
100 /*! @abstract the mate is unmapped */
101 #define BAM_FMUNMAP        8
102 /*! @abstract the read is mapped to the reverse strand */
103 #define BAM_FREVERSE      16
104 /*! @abstract the mate is mapped to the reverse strand */
105 #define BAM_FMREVERSE     32
106 /*! @abstract this is read1 */
107 #define BAM_FREAD1        64
108 /*! @abstract this is read2 */
109 #define BAM_FREAD2       128
110 /*! @abstract not primary alignment */
111 #define BAM_FSECONDARY   256
112 /*! @abstract QC failure */
113 #define BAM_FQCFAIL      512
114 /*! @abstract optical or PCR duplicate */
115 #define BAM_FDUP        1024
116
117 #define BAM_OFDEC          0
118 #define BAM_OFHEX          1
119 #define BAM_OFSTR          2
120
121 /*! @abstract defautl mask for pileup */
122 #define BAM_DEF_MASK (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP)
123
124 #define BAM_CORE_SIZE   sizeof(bam1_core_t)
125
126 /**
127  * Describing how CIGAR operation/length is packed in a 32-bit integer.
128  */
129 #define BAM_CIGAR_SHIFT 4
130 #define BAM_CIGAR_MASK  ((1 << BAM_CIGAR_SHIFT) - 1)
131
132 /*
133   CIGAR operations.
134  */
135 /*! @abstract CIGAR: match */
136 #define BAM_CMATCH      0
137 /*! @abstract CIGAR: insertion to the reference */
138 #define BAM_CINS        1
139 /*! @abstract CIGAR: deletion from the reference */
140 #define BAM_CDEL        2
141 /*! @abstract CIGAR: skip on the reference (e.g. spliced alignment) */
142 #define BAM_CREF_SKIP   3
143 /*! @abstract CIGAR: clip on the read with clipped sequence present in qseq */
144 #define BAM_CSOFT_CLIP  4
145 /*! @abstract CIGAR: clip on the read with clipped sequence trimmed off */
146 #define BAM_CHARD_CLIP  5
147 /*! @abstract CIGAR: padding */
148 #define BAM_CPAD        6
149
150 /*! @typedef
151   @abstract Structure for core alignment information.
152   @field  tid     chromosome ID, defined by bam_header_t
153   @field  pos     0-based leftmost coordinate
154   @field  strand  strand; 0 for forward and 1 otherwise
155   @field  bin     bin calculated by bam_reg2bin()
156   @field  qual    mapping quality
157   @field  l_qname length of the query name
158   @field  flag    bitwise flag
159   @field  n_cigar number of CIGAR operations
160   @field  l_qseq  length of the query sequence (read)
161  */
162 typedef struct {
163         int32_t tid;
164         int32_t pos;
165         uint32_t bin:16, qual:8, l_qname:8;
166         uint32_t flag:16, n_cigar:16;
167         int32_t l_qseq;
168         int32_t mtid;
169         int32_t mpos;
170         int32_t isize;
171 } bam1_core_t;
172
173 /*! @typedef
174   @abstract Structure for one alignment.
175   @field  core       core information about the alignment
176   @field  l_aux      length of auxiliary data
177   @field  data_len   current length of bam1_t::data
178   @field  m_data     maximum length of bam1_t::data
179   @field  data       all variable-length data, concatenated; structure: cigar-qname-seq-qual-aux
180
181   @discussion Notes:
182  
183    1. qname is zero tailing and core.l_qname includes the tailing '\0'.
184    2. l_qseq is calculated from the total length of an alignment block
185       on reading or from CIGAR.
186  */
187 typedef struct {
188         bam1_core_t core;
189         int l_aux, data_len, m_data;
190         uint8_t *data;
191 } bam1_t;
192
193 typedef struct __bam_iter_t *bam_iter_t;
194
195 #define bam1_strand(b) (((b)->core.flag&BAM_FREVERSE) != 0)
196 #define bam1_mstrand(b) (((b)->core.flag&BAM_FMREVERSE) != 0)
197
198 /*! @function
199   @abstract  Get the CIGAR array
200   @param  b  pointer to an alignment
201   @return    pointer to the CIGAR array
202
203   @discussion In the CIGAR array, each element is a 32-bit integer. The
204   lower 4 bits gives a CIGAR operation and the higher 28 bits keep the
205   length of a CIGAR.
206  */
207 #define bam1_cigar(b) ((uint32_t*)((b)->data + (b)->core.l_qname))
208
209 /*! @function
210   @abstract  Get the name of the query
211   @param  b  pointer to an alignment
212   @return    pointer to the name string, null terminated
213  */
214 #define bam1_qname(b) ((char*)((b)->data))
215
216 /*! @function
217   @abstract  Get query sequence
218   @param  b  pointer to an alignment
219   @return    pointer to sequence
220
221   @discussion Each base is encoded in 4 bits: 1 for A, 2 for C, 4 for G,
222   8 for T and 15 for N. Two bases are packed in one byte with the base
223   at the higher 4 bits having smaller coordinate on the read. It is
224   recommended to use bam1_seqi() macro to get the base.
225  */
226 #define bam1_seq(b) ((b)->data + (b)->core.n_cigar*4 + (b)->core.l_qname)
227
228 /*! @function
229   @abstract  Get query quality
230   @param  b  pointer to an alignment
231   @return    pointer to quality string
232  */
233 #define bam1_qual(b) ((b)->data + (b)->core.n_cigar*4 + (b)->core.l_qname + ((b)->core.l_qseq + 1)/2)
234
235 /*! @function
236   @abstract  Get a base on read
237   @param  s  Query sequence returned by bam1_seq()
238   @param  i  The i-th position, 0-based
239   @return    4-bit integer representing the base.
240  */
241 #define bam1_seqi(s, i) ((s)[(i)/2] >> 4*(1-(i)%2) & 0xf)
242
243 /*! @function
244   @abstract  Get query sequence and quality
245   @param  b  pointer to an alignment
246   @return    pointer to the concatenated auxiliary data
247  */
248 #define bam1_aux(b) ((b)->data + (b)->core.n_cigar*4 + (b)->core.l_qname + (b)->core.l_qseq + ((b)->core.l_qseq + 1)/2)
249
250 #ifndef kroundup32
251 /*! @function
252   @abstract  Round an integer to the next closest power-2 integer.
253   @param  x  integer to be rounded (in place)
254   @discussion x will be modified.
255  */
256 #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))
257 #endif
258
259 /*!
260   @abstract Whether the machine is big-endian; modified only in
261   bam_header_init().
262  */
263 extern int bam_is_be;
264
265 /*! @abstract Table for converting a nucleotide character to the 4-bit encoding. */
266 extern unsigned char bam_nt16_table[256];
267
268 /*! @abstract Table for converting a 4-bit encoded nucleotide to a letter. */
269 extern char *bam_nt16_rev_table;
270
271 extern char bam_nt16_nt4_table[];
272
273 #ifdef __cplusplus
274 extern "C" {
275 #endif
276
277         /*********************
278          * Low-level SAM I/O *
279          *********************/
280
281         /*! @abstract TAM file handler */
282         typedef struct __tamFile_t *tamFile;
283
284         /*!
285           @abstract   Open a SAM file for reading, either uncompressed or compressed by gzip/zlib.
286           @param  fn  SAM file name
287           @return     SAM file handler
288          */
289         tamFile sam_open(const char *fn);
290
291         /*!
292           @abstract   Close a SAM file handler
293           @param  fp  SAM file handler
294          */
295         void sam_close(tamFile fp);
296
297         /*!
298           @abstract      Read one alignment from a SAM file handler
299           @param  fp     SAM file handler
300           @param  header header information (ordered names of chromosomes)
301           @param  b      read alignment; all members in b will be updated
302           @return        0 if successful; otherwise negative
303          */
304         int sam_read1(tamFile fp, bam_header_t *header, bam1_t *b);
305
306         /*!
307           @abstract       Read header information from a TAB-delimited list file.
308           @param  fn_list file name for the list
309           @return         a pointer to the header structure
310
311           @discussion Each line in this file consists of chromosome name and
312           the length of chromosome.
313          */
314         bam_header_t *sam_header_read2(const char *fn_list);
315
316         /*!
317           @abstract       Read header from a SAM file (if present)
318           @param  fp      SAM file handler
319           @return         pointer to header struct; 0 if no @SQ lines available
320          */
321         bam_header_t *sam_header_read(tamFile fp);
322
323         /*!
324           @abstract       Parse @SQ lines a update a header struct
325           @param  h       pointer to the header struct to be updated
326           @return         number of target sequences
327
328           @discussion bam_header_t::{n_targets,target_len,target_name} will
329           be destroyed in the first place.
330          */
331         int sam_header_parse(bam_header_t *h);
332         int32_t bam_get_tid(const bam_header_t *header, const char *seq_name);
333
334         /*!
335           @abstract       Parse @RG lines a update a header struct
336           @param  h       pointer to the header struct to be updated
337           @return         number of @RG lines
338
339           @discussion bam_header_t::rg2lib will be destroyed in the first
340           place.
341          */
342         int sam_header_parse_rg(bam_header_t *h);
343
344 #define sam_write1(header, b) bam_view1(header, b)
345
346
347         /********************************
348          * APIs for string dictionaries *
349          ********************************/
350
351         int bam_strmap_put(void *strmap, const char *rg, const char *lib);
352         const char *bam_strmap_get(const void *strmap, const char *rg);
353         void *bam_strmap_dup(const void*);
354         void *bam_strmap_init();
355         void bam_strmap_destroy(void *strmap);
356
357
358         /*********************
359          * Low-level BAM I/O *
360          *********************/
361
362         /*!
363           @abstract Initialize a header structure.
364           @return   the pointer to the header structure
365
366           @discussion This function also modifies the global variable
367           bam_is_be.
368          */
369         bam_header_t *bam_header_init();
370
371         /*!
372           @abstract        Destroy a header structure.
373           @param  header  pointer to the header
374          */
375         void bam_header_destroy(bam_header_t *header);
376
377         /*!
378           @abstract   Read a header structure from BAM.
379           @param  fp  BAM file handler, opened by bam_open()
380           @return     pointer to the header structure
381
382           @discussion The file position indicator must be placed at the
383           beginning of the file. Upon success, the position indicator will
384           be set at the start of the first alignment.
385          */
386         bam_header_t *bam_header_read(bamFile fp);
387
388         /*!
389           @abstract      Write a header structure to BAM.
390           @param  fp     BAM file handler
391           @param  header pointer to the header structure
392           @return        always 0 currently
393          */
394         int bam_header_write(bamFile fp, const bam_header_t *header);
395
396         /*!
397           @abstract   Read an alignment from BAM.
398           @param  fp  BAM file handler
399           @param  b   read alignment; all members are updated.
400           @return     number of bytes read from the file
401
402           @discussion The file position indicator must be
403           placed right before an alignment. Upon success, this function
404           will set the position indicator to the start of the next
405           alignment. This function is not affected by the machine
406           endianness.
407          */
408         int bam_read1(bamFile fp, bam1_t *b);
409
410         /*!
411           @abstract Write an alignment to BAM.
412           @param  fp       BAM file handler
413           @param  c        pointer to the bam1_core_t structure
414           @param  data_len total length of variable size data related to
415                            the alignment
416           @param  data     pointer to the concatenated data
417           @return          number of bytes written to the file
418
419           @discussion This function is not affected by the machine
420           endianness.
421          */
422         int bam_write1_core(bamFile fp, const bam1_core_t *c, int data_len, uint8_t *data);
423
424         /*!
425           @abstract   Write an alignment to BAM.
426           @param  fp  BAM file handler
427           @param  b   alignment to write
428           @return     number of bytes written to the file
429
430           @abstract It is equivalent to:
431             bam_write1_core(fp, &b->core, b->data_len, b->data)
432          */
433         int bam_write1(bamFile fp, const bam1_t *b);
434
435         /*! @function
436           @abstract  Initiate a pointer to bam1_t struct
437          */
438 #define bam_init1() ((bam1_t*)calloc(1, sizeof(bam1_t)))
439
440         /*! @function
441           @abstract  Free the memory allocated for an alignment.
442           @param  b  pointer to an alignment
443          */
444 #define bam_destroy1(b) do {                                    \
445                 if (b) { free((b)->data); free(b); }    \
446         } while (0)
447
448         /*!
449           @abstract       Format a BAM record in the SAM format
450           @param  header  pointer to the header structure
451           @param  b       alignment to print
452           @return         a pointer to the SAM string
453          */
454         char *bam_format1(const bam_header_t *header, const bam1_t *b);
455
456         char *bam_format1_core(const bam_header_t *header, const bam1_t *b, int of);
457
458         const char *bam_get_library(bam_header_t *header, const bam1_t *b);
459
460
461         /***************
462          * pileup APIs *
463          ***************/
464
465         /*! @typedef
466           @abstract Structure for one alignment covering the pileup position.
467           @field  b      pointer to the alignment
468           @field  qpos   position of the read base at the pileup site, 0-based
469           @field  indel  indel length; 0 for no indel, positive for ins and negative for del
470           @field  is_del 1 iff the base on the padded read is a deletion
471           @field  level  the level of the read in the "viewer" mode
472
473           @discussion See also bam_plbuf_push() and bam_lplbuf_push(). The
474           difference between the two functions is that the former does not
475           set bam_pileup1_t::level, while the later does. Level helps the
476           implementation of alignment viewers, but calculating this has some
477           overhead.
478          */
479         typedef struct {
480                 bam1_t *b;
481                 int32_t qpos;
482                 int indel, level;
483                 uint32_t is_del:1, is_head:1, is_tail:1;
484         } bam_pileup1_t;
485
486         typedef int (*bam_plp_auto_f)(void *data, bam1_t *b);
487
488         struct __bam_plp_t;
489         typedef struct __bam_plp_t *bam_plp_t;
490
491         bam_plp_t bam_plp_init(bam_plp_auto_f func, void *data);
492         int bam_plp_push(bam_plp_t iter, const bam1_t *b);
493         const bam_pileup1_t *bam_plp_next(bam_plp_t iter, int *_tid, int *_pos, int *_n_plp);
494         const bam_pileup1_t *bam_plp_auto(bam_plp_t iter, int *_tid, int *_pos, int *_n_plp);
495         void bam_plp_set_mask(bam_plp_t iter, int mask);
496         void bam_plp_reset(bam_plp_t iter);
497         void bam_plp_destroy(bam_plp_t iter);
498
499         struct __bam_mplp_t;
500         typedef struct __bam_mplp_t *bam_mplp_t;
501
502         bam_mplp_t bam_mplp_init(int n, bam_plp_auto_f func, void **data);
503         void bam_mplp_destroy(bam_mplp_t iter);
504         int bam_mplp_auto(bam_mplp_t iter, int *_tid, int *_pos, int *n_plp, const bam_pileup1_t **plp);
505
506         /*! @typedef
507           @abstract    Type of function to be called by bam_plbuf_push().
508           @param  tid  chromosome ID as is defined in the header
509           @param  pos  start coordinate of the alignment, 0-based
510           @param  n    number of elements in pl array
511           @param  pl   array of alignments
512           @param  data user provided data
513           @discussion  See also bam_plbuf_push(), bam_plbuf_init() and bam_pileup1_t.
514          */
515         typedef int (*bam_pileup_f)(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pl, void *data);
516
517         typedef struct {
518                 bam_plp_t iter;
519                 bam_pileup_f func;
520                 void *data;
521         } bam_plbuf_t;
522
523         void bam_plbuf_set_mask(bam_plbuf_t *buf, int mask);
524         void bam_plbuf_reset(bam_plbuf_t *buf);
525         bam_plbuf_t *bam_plbuf_init(bam_pileup_f func, void *data);
526         void bam_plbuf_destroy(bam_plbuf_t *buf);
527         int bam_plbuf_push(const bam1_t *b, bam_plbuf_t *buf);
528
529         int bam_pileup_file(bamFile fp, int mask, bam_pileup_f func, void *func_data);
530
531         struct __bam_lplbuf_t;
532         typedef struct __bam_lplbuf_t bam_lplbuf_t;
533
534         void bam_lplbuf_reset(bam_lplbuf_t *buf);
535
536         /*! @abstract  bam_plbuf_init() equivalent with level calculated. */
537         bam_lplbuf_t *bam_lplbuf_init(bam_pileup_f func, void *data);
538
539         /*! @abstract  bam_plbuf_destroy() equivalent with level calculated. */
540         void bam_lplbuf_destroy(bam_lplbuf_t *tv);
541
542         /*! @abstract  bam_plbuf_push() equivalent with level calculated. */
543         int bam_lplbuf_push(const bam1_t *b, bam_lplbuf_t *buf);
544
545
546         /*********************
547          * BAM indexing APIs *
548          *********************/
549
550         struct __bam_index_t;
551         typedef struct __bam_index_t bam_index_t;
552
553         /*!
554           @abstract   Build index for a BAM file.
555           @discussion Index file "fn.bai" will be created.
556           @param  fn  name of the BAM file
557           @return     always 0 currently
558          */
559         int bam_index_build(const char *fn);
560
561         /*!
562           @abstract   Load index from file "fn.bai".
563           @param  fn  name of the BAM file (NOT the index file)
564           @return     pointer to the index structure
565          */
566         bam_index_t *bam_index_load(const char *fn);
567
568         /*!
569           @abstract    Destroy an index structure.
570           @param  idx  pointer to the index structure
571          */
572         void bam_index_destroy(bam_index_t *idx);
573
574         /*! @typedef
575           @abstract      Type of function to be called by bam_fetch().
576           @param  b     the alignment
577           @param  data  user provided data
578          */
579         typedef int (*bam_fetch_f)(const bam1_t *b, void *data);
580
581         /*!
582           @abstract Retrieve the alignments that are overlapped with the
583           specified region.
584
585           @discussion A user defined function will be called for each
586           retrieved alignment ordered by its start position.
587
588           @param  fp    BAM file handler
589           @param  idx   pointer to the alignment index
590           @param  tid   chromosome ID as is defined in the header
591           @param  beg   start coordinate, 0-based
592           @param  end   end coordinate, 0-based
593           @param  data  user provided data (will be transferred to func)
594           @param  func  user defined function
595          */
596         int bam_fetch(bamFile fp, const bam_index_t *idx, int tid, int beg, int end, void *data, bam_fetch_f func);
597
598         bam_iter_t bam_iter_query(const bam_index_t *idx, int tid, int beg, int end);
599         int bam_iter_read(bamFile fp, bam_iter_t iter, bam1_t *b);
600         void bam_iter_destroy(bam_iter_t iter);
601
602         /*!
603           @abstract       Parse a region in the format: "chr2:100,000-200,000".
604           @discussion     bam_header_t::hash will be initialized if empty.
605           @param  header  pointer to the header structure
606           @param  str     string to be parsed
607           @param  ref_id  the returned chromosome ID
608           @param  begin   the returned start coordinate
609           @param  end     the returned end coordinate
610           @return         0 on success; -1 on failure
611          */
612         int bam_parse_region(bam_header_t *header, const char *str, int *ref_id, int *begin, int *end);
613
614
615         /**************************
616          * APIs for optional tags *
617          **************************/
618
619         /*!
620           @abstract       Retrieve data of a tag
621           @param  b       pointer to an alignment struct
622           @param  tag     two-character tag to be retrieved
623
624           @return  pointer to the type and data. The first character is the
625           type that can be 'iIsScCdfAZH'.
626
627           @discussion  Use bam_aux2?() series to convert the returned data to
628           the corresponding type.
629         */
630         uint8_t *bam_aux_get(const bam1_t *b, const char tag[2]);
631
632         int32_t bam_aux2i(const uint8_t *s);
633         float bam_aux2f(const uint8_t *s);
634         double bam_aux2d(const uint8_t *s);
635         char bam_aux2A(const uint8_t *s);
636         char *bam_aux2Z(const uint8_t *s);
637
638         int bam_aux_del(bam1_t *b, uint8_t *s);
639         void bam_aux_append(bam1_t *b, const char tag[2], char type, int len, uint8_t *data);
640         uint8_t *bam_aux_get_core(bam1_t *b, const char tag[2]); // an alias of bam_aux_get()
641
642
643         /*****************
644          * Miscellaneous *
645          *****************/
646
647         /*!  
648           @abstract Calculate the rightmost coordinate of an alignment on the
649           reference genome.
650
651           @param  c      pointer to the bam1_core_t structure
652           @param  cigar  the corresponding CIGAR array (from bam1_t::cigar)
653           @return        the rightmost coordinate, 0-based
654         */
655         uint32_t bam_calend(const bam1_core_t *c, const uint32_t *cigar);
656
657         /*!
658           @abstract      Calculate the length of the query sequence from CIGAR.
659           @param  c      pointer to the bam1_core_t structure
660           @param  cigar  the corresponding CIGAR array (from bam1_t::cigar)
661           @return        length of the query sequence
662         */
663         int32_t bam_cigar2qlen(const bam1_core_t *c, const uint32_t *cigar);
664
665 #ifdef __cplusplus
666 }
667 #endif
668
669 /*!
670   @abstract    Calculate the minimum bin that contains a region [beg,end).
671   @param  beg  start of the region, 0-based
672   @param  end  end of the region, 0-based
673   @return      bin
674  */
675 static inline int bam_reg2bin(uint32_t beg, uint32_t end)
676 {
677         --end;
678         if (beg>>14 == end>>14) return 4681 + (beg>>14);
679         if (beg>>17 == end>>17) return  585 + (beg>>17);
680         if (beg>>20 == end>>20) return   73 + (beg>>20);
681         if (beg>>23 == end>>23) return    9 + (beg>>23);
682         if (beg>>26 == end>>26) return    1 + (beg>>26);
683         return 0;
684 }
685
686 /*!
687   @abstract     Copy an alignment
688   @param  bdst  destination alignment struct
689   @param  bsrc  source alignment struct
690   @return       pointer to the destination alignment struct
691  */
692 static inline bam1_t *bam_copy1(bam1_t *bdst, const bam1_t *bsrc)
693 {
694         uint8_t *data = bdst->data;
695         int m_data = bdst->m_data;   // backup data and m_data
696         if (m_data < bsrc->m_data) { // double the capacity
697                 m_data = bsrc->m_data; kroundup32(m_data);
698                 data = (uint8_t*)realloc(data, m_data);
699         }
700         memcpy(data, bsrc->data, bsrc->data_len); // copy var-len data
701         *bdst = *bsrc; // copy the rest
702         // restore the backup
703         bdst->m_data = m_data;
704         bdst->data = data;
705         return bdst;
706 }
707
708 /*!
709   @abstract     Duplicate an alignment
710   @param  src   source alignment struct
711   @return       pointer to the destination alignment struct
712  */
713 static inline bam1_t *bam_dup1(const bam1_t *src)
714 {
715         bam1_t *b;
716         b = bam_init1();
717         *b = *src;
718         b->m_data = b->data_len;
719         b->data = (uint8_t*)calloc(b->data_len, 1);
720         memcpy(b->data, src->data, b->data_len);
721         return b;
722 }
723
724 #endif