Merge commit 'upstream/0.1.15'
[samtools.git] / sam.c
1 #include <string.h>
2 #include <unistd.h>
3 #include "faidx.h"
4 #include "sam.h"
5
6 #define TYPE_BAM  1
7 #define TYPE_READ 2
8
9 bam_header_t *bam_header_dup(const bam_header_t *h0)
10 {
11         bam_header_t *h;
12         int i;
13         h = bam_header_init();
14         *h = *h0;
15         h->hash = h->dict = h->rg2lib = 0;
16         h->text = (char*)calloc(h->l_text + 1, 1);
17         memcpy(h->text, h0->text, h->l_text);
18         h->target_len = (uint32_t*)calloc(h->n_targets, 4);
19         h->target_name = (char**)calloc(h->n_targets, sizeof(void*));
20         for (i = 0; i < h->n_targets; ++i) {
21                 h->target_len[i] = h0->target_len[i];
22                 h->target_name[i] = strdup(h0->target_name[i]);
23         }
24         return h;
25 }
26 static void append_header_text(bam_header_t *header, char* text, int len)
27 {
28         int x = header->l_text + 1;
29         int y = header->l_text + len + 1; // 1 byte null
30         if (text == 0) return;
31         kroundup32(x); 
32         kroundup32(y);
33         if (x < y) header->text = (char*)realloc(header->text, y);
34         strncpy(header->text + header->l_text, text, len); // we cannot use strcpy() here.
35         header->l_text += len;
36         header->text[header->l_text] = 0;
37 }
38
39 samfile_t *samopen(const char *fn, const char *mode, const void *aux)
40 {
41         samfile_t *fp;
42         fp = (samfile_t*)calloc(1, sizeof(samfile_t));
43         if (strchr(mode, 'r')) { // read
44                 fp->type |= TYPE_READ;
45                 if (strchr(mode, 'b')) { // binary
46                         fp->type |= TYPE_BAM;
47                         fp->x.bam = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
48                         if (fp->x.bam == 0) goto open_err_ret;
49                         fp->header = bam_header_read(fp->x.bam);
50                 } else { // text
51                         fp->x.tamr = sam_open(fn);
52                         if (fp->x.tamr == 0) goto open_err_ret;
53                         fp->header = sam_header_read(fp->x.tamr);
54                         if (fp->header->n_targets == 0) { // no @SQ fields
55                                 if (aux) { // check if aux is present
56                                         bam_header_t *textheader = fp->header;
57                                         fp->header = sam_header_read2((const char*)aux);
58                                         if (fp->header == 0) goto open_err_ret;
59                                         append_header_text(fp->header, textheader->text, textheader->l_text);
60                                         bam_header_destroy(textheader);
61                                 }
62                                 if (fp->header->n_targets == 0 && bam_verbose >= 1)
63                                         fprintf(stderr, "[samopen] no @SQ lines in the header.\n");
64                         } else if (bam_verbose >= 2) fprintf(stderr, "[samopen] SAM header is present: %d sequences.\n", fp->header->n_targets);
65                 }
66         } else if (strchr(mode, 'w')) { // write
67                 fp->header = bam_header_dup((const bam_header_t*)aux);
68                 if (strchr(mode, 'b')) { // binary
69                         char bmode[3];
70                         int i, compress_level = -1;
71                         for (i = 0; mode[i]; ++i) if (mode[i] >= '0' && mode[i] <= '9') break;
72                         if (mode[i]) compress_level = mode[i] - '0';
73                         if (strchr(mode, 'u')) compress_level = 0;
74                         bmode[0] = 'w'; bmode[1] = compress_level < 0? 0 : compress_level + '0'; bmode[2] = 0;
75                         fp->type |= TYPE_BAM;
76                         fp->x.bam = strcmp(fn, "-")? bam_open(fn, bmode) : bam_dopen(fileno(stdout), bmode);
77                         if (fp->x.bam == 0) goto open_err_ret;
78                         bam_header_write(fp->x.bam, fp->header);
79                 } else { // text
80                         // open file
81                         fp->x.tamw = strcmp(fn, "-")? fopen(fn, "w") : stdout;
82                         if (fp->x.tamr == 0) goto open_err_ret;
83                         if (strchr(mode, 'X')) fp->type |= BAM_OFSTR<<2;
84                         else if (strchr(mode, 'x')) fp->type |= BAM_OFHEX<<2;
85                         else fp->type |= BAM_OFDEC<<2;
86                         // write header
87                         if (strchr(mode, 'h')) {
88                                 int i;
89                                 bam_header_t *alt;
90                                 // parse the header text 
91                                 alt = bam_header_init();
92                                 alt->l_text = fp->header->l_text; alt->text = fp->header->text;
93                                 sam_header_parse(alt);
94                                 alt->l_text = 0; alt->text = 0;
95                                 // check if there are @SQ lines in the header
96                                 fwrite(fp->header->text, 1, fp->header->l_text, fp->x.tamw); // FIXME: better to skip the trailing NULL
97                                 if (alt->n_targets) { // then write the header text without dumping ->target_{name,len}
98                                         if (alt->n_targets != fp->header->n_targets && bam_verbose >= 1)
99                                                 fprintf(stderr, "[samopen] inconsistent number of target sequences. Output the text header.\n");
100                                 } else { // then dump ->target_{name,len}
101                                         for (i = 0; i < fp->header->n_targets; ++i)
102                                                 fprintf(fp->x.tamw, "@SQ\tSN:%s\tLN:%d\n", fp->header->target_name[i], fp->header->target_len[i]);
103                                 }
104                                 bam_header_destroy(alt);
105                         }
106                 }
107         }
108         return fp;
109
110 open_err_ret:
111         free(fp);
112         return 0;
113 }
114
115 void samclose(samfile_t *fp)
116 {
117         if (fp == 0) return;
118         if (fp->header) bam_header_destroy(fp->header);
119         if (fp->type & TYPE_BAM) bam_close(fp->x.bam);
120         else if (fp->type & TYPE_READ) sam_close(fp->x.tamr);
121         else fclose(fp->x.tamw);
122         free(fp);
123 }
124
125 int samread(samfile_t *fp, bam1_t *b)
126 {
127         if (fp == 0 || !(fp->type & TYPE_READ)) return -1; // not open for reading
128         if (fp->type & TYPE_BAM) return bam_read1(fp->x.bam, b);
129         else return sam_read1(fp->x.tamr, fp->header, b);
130 }
131
132 int samwrite(samfile_t *fp, const bam1_t *b)
133 {
134         if (fp == 0 || (fp->type & TYPE_READ)) return -1; // not open for writing
135         if (fp->type & TYPE_BAM) return bam_write1(fp->x.bam, b);
136         else {
137                 char *s = bam_format1_core(fp->header, b, fp->type>>2&3);
138                 int l = strlen(s);
139                 fputs(s, fp->x.tamw); fputc('\n', fp->x.tamw);
140                 free(s);
141                 return l + 1;
142         }
143 }
144
145 int sampileup(samfile_t *fp, int mask, bam_pileup_f func, void *func_data)
146 {
147         bam_plbuf_t *buf;
148         int ret;
149         bam1_t *b;
150         b = bam_init1();
151         buf = bam_plbuf_init(func, func_data);
152         bam_plbuf_set_mask(buf, mask);
153         while ((ret = samread(fp, b)) >= 0)
154                 bam_plbuf_push(b, buf);
155         bam_plbuf_push(0, buf);
156         bam_plbuf_destroy(buf);
157         bam_destroy1(b);
158         return 0;
159 }
160
161 char *samfaipath(const char *fn_ref)
162 {
163         char *fn_list = 0;
164         if (fn_ref == 0) return 0;
165         fn_list = calloc(strlen(fn_ref) + 5, 1);
166         strcat(strcpy(fn_list, fn_ref), ".fai");
167         if (access(fn_list, R_OK) == -1) { // fn_list is unreadable
168                 if (access(fn_ref, R_OK) == -1) {
169                         fprintf(stderr, "[samfaipath] fail to read file %s.\n", fn_ref);
170                 } else {
171                         if (bam_verbose >= 3) fprintf(stderr, "[samfaipath] build FASTA index...\n");
172                         if (fai_build(fn_ref) == -1) {
173                                 fprintf(stderr, "[samfaipath] fail to build FASTA index.\n");
174                                 free(fn_list); fn_list = 0;
175                         }
176                 }
177         }
178         return fn_list;
179 }