Debian Codegraph @

samtools/padding.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* padding.c -- depad subcommand.
4
5 Copyright (C) 2011, 2012 Broad Institute.
6 Copyright (C) 2014-2016, 2019-2020 Genome Research Ltd.
7 Portions copyright (C) 2012, 2013 Peter Cock, The James Hutton Institute.
8
9 Author: Heng Li <[email protected]>
10
11 Permission is hereby granted, free of charge, to any person obtaining a copy
12 of this software and associated documentation files (the "Software"), to deal
13 in the Software without restriction, including without limitation the rights
14 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 copies of the Software, and to permit persons to whom the Software is
16 furnished to do so, subject to the following conditions:
17
18 The above copyright notice and this permission notice shall be included in
19 all copies or substantial portions of the Software.
20
21 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27 DEALINGS IN THE SOFTWARE. */
28
29 #include <config.h>
30
31 #include <string.h>
32 #include <assert.h>
33 #include <unistd.h>
34 #include <inttypes.h>
35 #include <htslib/kstring.h>
36 #include <htslib/sam.h>
37 #include <htslib/faidx.h>
38 #include "sam_opts.h"
39 #include "samtools.h"
40
41 #define bam_reg2bin(b,e) hts_reg2bin((b),(e), 14, 5)
42
43 static int replace_cigar(bam1_t *b, uint32_t n, uint32_t *cigar)
44 {
45 int diff = 0;
46 if (n != b->core.n_cigar) {
47 int o = b->core.l_qname + b->core.n_cigar * 4;
48 if (n > b->core.n_cigar) {
49 diff = (n - b->core.n_cigar) * 4;
50 if ((INT_MAX - b->l_data)/4 < (n - b->core.n_cigar)) {
51 fprintf(samtools_stderr, "[depad] ERROR: BAM record too big\n");
52 return -1;
53 }
54 if (b->l_data + diff > b->m_data) {
55 b->m_data = b->l_data + diff;
56 kroundup32(b->m_data);
57 uint8_t *tmp = (uint8_t*)realloc(b->data, b->m_data);
58 if (!tmp) {
59 fprintf(samtools_stderr, "[depad] ERROR: Memory allocation failure.\n");
60 return -1;
61 }
62 b->data = tmp;
63 }
64 } else {
65 diff = -(int)((b->core.n_cigar - n) * 4);
66 }
67 memmove(b->data + b->core.l_qname + n * 4, b->data + o, b->l_data - o);
68 b->core.n_cigar = n;
69 }
70
71 memcpy(b->data + b->core.l_qname, cigar, n * 4);
72 b->l_data += diff;
73
74 return 0;
75 }
76
77 #define write_cigar(_c, _n, _m, _v) do { \
78 if (_n == _m) { \
79 _m = _m? _m<<1 : 4; \
80 _c = (uint32_t*)realloc(_c, _m * 4); \
81 if (!(_c)) { \
82 fprintf(samtools_stderr, "[depad] ERROR: Memory allocation failure.\n"); \
83 return -1; \
84 } \
85 } \
86 _c[_n++] = (_v); \
87 } while (0)
88
89 static int unpad_seq(bam1_t *b, kstring_t *s)
90 {
91 // Returns 0 on success, -1 on an error
92 int k, j, i;
93 int length;
94 int cigar_n_warning = 0; /* Make this a global and limit to one CIGAR N warning? */
95 uint32_t *cigar = bam_get_cigar(b);
96 uint8_t *seq = bam_get_seq(b);
97
98 // b->core.l_qseq gives length of the SEQ entry (including soft clips, S)
99 // We need the padded length after alignment from the CIGAR (excluding
100 // soft clips S, but including pads from CIGAR D operations)
101 length = bam_cigar2rlen(b->core.n_cigar, cigar);
102 ks_resize(s, length);
103 for (k = 0, s->l = 0, j = 0; k < b->core.n_cigar; ++k) {
104 int op, ol;
105 op = bam_cigar_op(cigar[k]);
106 ol = bam_cigar_oplen(cigar[k]);
107 if (op == BAM_CMATCH || op == BAM_CEQUAL || op == BAM_CDIFF) {
108 for (i = 0; i < ol; ++i, ++j) s->s[s->l++] = bam_seqi(seq, j);
109 } else if (op == BAM_CSOFT_CLIP) {
110 j += ol;
111 } else if (op == BAM_CHARD_CLIP) {
112 /* do nothing */
113 } else if (op == BAM_CDEL) {
114 for (i = 0; i < ol; ++i) s->s[s->l++] = 0;
115 } else if (op == BAM_CREF_SKIP) {
116 /* Treat CIGAR N as D (not ideal, but better than ignoring it) */
117 for (i = 0; i < ol; ++i) s->s[s->l++] = 0;
118 if (0 == cigar_n_warning) {
119 cigar_n_warning = -1;
120 fprintf(samtools_stderr, "[depad] WARNING: CIGAR op N treated as op D in read %s\n", bam_get_qname(b));
121 }
122 } else {
123 fprintf(samtools_stderr, "[depad] ERROR: Didn't expect CIGAR op %c in read %s\n", BAM_CIGAR_STR[op], bam_get_qname(b));
124 return -1;
125 }
126 }
127 return length != s->l;
128 }
129
130 int load_unpadded_ref(faidx_t *fai, const char *ref_name, hts_pos_t ref_len, kstring_t *seq)
131 {
132 char base;
133 char *fai_ref = 0;
134 hts_pos_t fai_ref_len = 0, k;
135
136 fai_ref = fai_fetch64(fai, ref_name, &fai_ref_len);
137 if (fai_ref_len != ref_len) {
138 fprintf(samtools_stderr, "[depad] ERROR: FASTA sequence %s length %"PRIhts_pos", expected %"PRIhts_pos"\n", ref_name, fai_ref_len, ref_len);
139 free(fai_ref);
140 return -1;
141 }
142 ks_resize(seq, ref_len);
143 seq->l = 0;
144 for (k = 0; k < ref_len; ++k) {
145 base = fai_ref[k];
146 if (base == '-' || base == '*') {
147 // Map gaps to null to match unpad_seq function
148 seq->s[seq->l++] = 0;
149 } else {
150 int i = seq_nt16_table[(int)base];
151 if (i == 0 || i==16) { // Equals maps to 0, anything unexpected to 16
152 fprintf(samtools_stderr, "[depad] ERROR: Invalid character %c (ASCII %i) in FASTA sequence %s\n", base, (int)base, ref_name);
153 free(fai_ref);
154 return -1;
155 }
156 seq->s[seq->l++] = i;
157 }
158 }
159 assert(ref_len == seq->l);
160 free(fai_ref);
161 return 0;
162 }
163
164 hts_pos_t get_unpadded_len(faidx_t *fai, const char *ref_name, hts_pos_t padded_len)
165 {
166 char base;
167 char *fai_ref = 0;
168 hts_pos_t fai_ref_len = 0, k;
169 hts_pos_t bases=0, gaps=0;
170
171 fai_ref = fai_fetch64(fai, ref_name, &fai_ref_len);
172 if (fai_ref_len != padded_len) {
173 fprintf(samtools_stderr, "[depad] ERROR: FASTA sequence '%s' length %"PRIhts_pos", expected %"PRIhts_pos"\n", ref_name, fai_ref_len, padded_len);
174 free(fai_ref);
175 return -1;
176 }
177 for (k = 0; k < padded_len; ++k) {
178 //fprintf(samtools_stderr, "[depad] checking base %i of %i or %i\n", k+1, ref_len, strlen(fai_ref));
179 base = fai_ref[k];
180 if (base == '-' || base == '*') {
181 gaps += 1;
182 } else {
183 int i = seq_nt16_table[(int)base];
184 if (i == 0 || i==16) { // Equals maps to 0, anything unexpected to 16
185 fprintf(samtools_stderr, "[depad] ERROR: Invalid character %c (ASCII %i) in FASTA sequence '%s'\n", base, (int)base, ref_name);
186 free(fai_ref);
187 return -1;
188 }
189 bases += 1;
190 }
191 }
192 free(fai_ref);
193 assert (padded_len == bases + gaps);
194 return bases;
195 }
196
197 static inline int * update_posmap(int *posmap, kstring_t ref)
198 {
199 int i, k;
200 posmap = realloc(posmap, ref.m * sizeof(int));
201 for (i = k = 0; i < ref.l; ++i) {
202 posmap[i] = k;
203 if (ref.s[i]) ++k;
204 }
205 return posmap;
206 }
207
208 int bam_pad2unpad(samFile *in, samFile *out, sam_hdr_t *h, faidx_t *fai)
209 {
210 bam1_t *b = 0;
211 kstring_t r, q;
212 int r_tid = -1;
213 uint32_t *cigar2 = 0;
214 int ret = 0, *posmap = 0;
215 uint32_t n2 = 0, m2 = 0;
216
217 b = bam_init1();
218 if (!b) {
219 fprintf(samtools_stderr, "[depad] Couldn't allocate bam struct\n");
220 return -1;
221 }
222 r.l = r.m = q.l = q.m = 0; r.s = q.s = 0;
223 int read_ret;
224 while ((read_ret = sam_read1(in, h, b)) >= 0) { // read one alignment from `in'
225 // Cannot depad unmapped CRAM data
226 if (b->core.flag & BAM_FUNMAP)
227 goto next_seq;
228
229 uint32_t *cigar = bam_get_cigar(b);
230 n2 = 0;
231 if (b->core.pos == 0 && b->core.tid >= 0 && strcmp(bam_get_qname(b), sam_hdr_tid2name(h, b->core.tid)) == 0) {
232 // fprintf(samtools_stderr, "[depad] Found embedded reference '%s'\n", bam_get_qname(b));
233 r_tid = b->core.tid;
234 if (0!=unpad_seq(b, &r)) {
235 fprintf(samtools_stderr, "[depad] ERROR: Problem parsing SEQ and/or CIGAR in reference %s\n", bam_get_qname(b));
236 return -1;
237 };
238 if (sam_hdr_tid2len(h, r_tid) != r.l) {
239 fprintf(samtools_stderr, "[depad] ERROR: (Padded) length of '%s' is %"PRId64" in BAM header, but %zu in embedded reference\n", bam_get_qname(b), (int64_t) sam_hdr_tid2len(h, r_tid), r.l);
240 return -1;
241 }
242 if (fai) {
243 // Check the embedded reference matches the FASTA file
244 if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), &q)) {
245 fprintf(samtools_stderr, "[depad] ERROR: Failed to load embedded reference '%s' from FASTA\n", sam_hdr_tid2name(h, b->core.tid));
246 return -1;
247 }
248 assert(r.l == q.l);
249 int i;
250 for (i = 0; i < r.l; ++i) {
251 if (r.s[i] != q.s[i]) {
252 // Show gaps as ASCII 45
253 fprintf(samtools_stderr, "[depad] ERROR: Embedded sequence and reference FASTA don't match for %s base %i, '%c' vs '%c'\n",
254 sam_hdr_tid2name(h, b->core.tid), i+1,
255 r.s[i] ? seq_nt16_str[(int)r.s[i]] : 45,
256 q.s[i] ? seq_nt16_str[(int)q.s[i]] : 45);
257 return -1;
258 }
259 }
260 }
261 write_cigar(cigar2, n2, m2, bam_cigar_gen(b->core.l_qseq, BAM_CMATCH));
262 if (replace_cigar(b, n2, cigar2) < 0)
263 return -1;
264 posmap = update_posmap(posmap, r);
265 } else if (b->core.n_cigar > 0) {
266 int i, k, op;
267 if (b->core.tid < 0) {
268 fprintf(samtools_stderr, "[depad] ERROR: Read '%s' has CIGAR but no RNAME\n", bam_get_qname(b));
269 return -1;
270 } else if (b->core.tid == r_tid) {
271 ; // good case, reference available
272 //fprintf(samtools_stderr, "[depad] Have ref '%s' for read '%s'\n", h->target_name[b->core.tid], bam_get_qname(b));
273 } else if (fai) {
274 if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), &r)) {
275 fprintf(samtools_stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", sam_hdr_tid2name(h, b->core.tid));
276 return -1;
277 }
278 posmap = update_posmap(posmap, r);
279 r_tid = b->core.tid;
280 // fprintf(samtools_stderr, "[depad] Loaded %s from FASTA file\n", h->target_name[b->core.tid]);
281 } else {
282 fprintf(samtools_stderr, "[depad] ERROR: Missing %s embedded reference sequence (and no FASTA file)\n", sam_hdr_tid2name(h, b->core.tid));
283 return -1;
284 }
285 if (0!=unpad_seq(b, &q)) {
286 fprintf(samtools_stderr, "[depad] ERROR: Problem parsing SEQ and/or CIGAR in read %s\n", bam_get_qname(b));
287 return -1;
288 };
289 if (bam_cigar_op(cigar[0]) == BAM_CSOFT_CLIP) {
290 write_cigar(cigar2, n2, m2, cigar[0]);
291 } else if (bam_cigar_op(cigar[0]) == BAM_CHARD_CLIP) {
292 write_cigar(cigar2, n2, m2, cigar[0]);
293 if (b->core.n_cigar > 2 && bam_cigar_op(cigar[1]) == BAM_CSOFT_CLIP) {
294 write_cigar(cigar2, n2, m2, cigar[1]);
295 }
296 }
297 /* Determine CIGAR operator for each base in the aligned read */
298 for (i = 0, k = b->core.pos; i < q.l; ++i, ++k)
299 q.s[i] = q.s[i]? (r.s[k]? BAM_CMATCH : BAM_CINS) : (r.s[k]? BAM_CDEL : BAM_CPAD);
300 /* Include any pads if starts with an insert */
301 if (q.s[0] == BAM_CINS) {
302 for (k = 0; k+1 < b->core.pos && !r.s[b->core.pos - k - 1]; ++k);
303 if (k) write_cigar(cigar2, n2, m2, bam_cigar_gen(k, BAM_CPAD));
304 k = 0;
305 } else if (q.s[0] == BAM_CPAD) {
306 // Join 'k' CPAD to our first cigar op CPAD too.
307 for (k = 0; k+1 < b->core.pos && !r.s[b->core.pos - k - 1]; ++k);
308 } else {
309 k = 0;
310 }
311 /* Count consecutive CIGAR operators to turn into a CIGAR string */
312 for (i = 1, k++, op = q.s[0]; i < q.l; ++i) {
313 if (op != q.s[i]) {
314 write_cigar(cigar2, n2, m2, bam_cigar_gen(k, op));
315 op = q.s[i]; k = 1;
316 } else ++k;
317 }
318 write_cigar(cigar2, n2, m2, bam_cigar_gen(k, op));
319 if (bam_cigar_op(cigar[b->core.n_cigar-1]) == BAM_CSOFT_CLIP) {
320 write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-1]);
321 } else if (bam_cigar_op(cigar[b->core.n_cigar-1]) == BAM_CHARD_CLIP) {
322 if (b->core.n_cigar > 2 && bam_cigar_op(cigar[b->core.n_cigar-2]) == BAM_CSOFT_CLIP) {
323 write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-2]);
324 }
325 write_cigar(cigar2, n2, m2, cigar[b->core.n_cigar-1]);
326 }
327 /* Remove redundant P operators between M/X/=/D operators, e.g. 5M2P10M -> 15M */
328 int pre_op, post_op;
329 for (i = 2; i < n2; ++i)
330 if (bam_cigar_op(cigar2[i-1]) == BAM_CPAD) {
331 pre_op = bam_cigar_op(cigar2[i-2]);
332 post_op = bam_cigar_op(cigar2[i]);
333 /* Note don't need to check for X/= as code above will use M only */
334 if ((pre_op == BAM_CMATCH || pre_op == BAM_CDEL) && (post_op == BAM_CMATCH || post_op == BAM_CDEL)) {
335 /* This is a redundant P operator */
336 cigar2[i-1] = 0; // i.e. 0M
337 /* If had same operator either side, combine them in post_op */
338 if (pre_op == post_op) {
339 /* If CIGAR M, could treat as simple integers since BAM_CMATCH is zero*/
340 cigar2[i] = bam_cigar_gen(bam_cigar_oplen(cigar2[i-2]) + bam_cigar_oplen(cigar2[i]), post_op);
341 cigar2[i-2] = 0; // i.e. 0M
342 }
343 }
344 }
345 /* Remove the zero'd operators (0M) */
346 for (i = k = 0; i < n2; ++i)
347 if (cigar2[i]) cigar2[k++] = cigar2[i];
348 n2 = k;
349 if (replace_cigar(b, n2, cigar2) < 0)
350 return -1;
351 }
352 /* Even unmapped reads can have a POS value, e.g. if their mate was mapped */
353 if (b->core.pos != -1) b->core.pos = posmap[b->core.pos];
354 if (b->core.mtid < 0 || b->core.mpos < 0) {
355 /* Nice case, no mate to worry about*/
356 // fprintf(samtools_stderr, "[depad] Read '%s' mate not mapped\n", bam_get_qname(b));
357 /* TODO - Warning if FLAG says mate should be mapped? */
358 /* Clean up funny input where mate position is given but mate reference is missing: */
359 b->core.mtid = -1;
360 b->core.mpos = -1;
361 } else if (b->core.mtid == b->core.tid) {
362 /* Nice case, same reference */
363 // fprintf(samtools_stderr, "[depad] Read '%s' mate mapped to same ref\n", bam_get_qname(b));
364 b->core.mpos = posmap[b->core.mpos];
365 } else {
366 /* Nasty case, Must load alternative posmap */
367 // fprintf(samtools_stderr, "[depad] Loading reference '%s' temporarily\n", h->target_name[b->core.mtid]);
368 if (!fai) {
369 fprintf(samtools_stderr, "[depad] ERROR: Needed reference %s sequence for mate (and no FASTA file)\n", sam_hdr_tid2name(h, b->core.mtid));
370 return -1;
371 }
372 /* Temporarily load the other reference sequence */
373 if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.mtid), sam_hdr_tid2len(h, b->core.mtid), &r)) {
374 fprintf(samtools_stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", sam_hdr_tid2name(h, b->core.mtid));
375 return -1;
376 }
377 posmap = update_posmap(posmap, r);
378 b->core.mpos = posmap[b->core.mpos];
379 /* Restore the reference and posmap*/
380 if (load_unpadded_ref(fai, sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), &r)) {
381 fprintf(samtools_stderr, "[depad] ERROR: Failed to load '%s' from reference FASTA\n", sam_hdr_tid2name(h, b->core.tid));
382 return -1;
383 }
384 posmap = update_posmap(posmap, r);
385 }
386 /* Most reads will have been moved so safest to always recalculate the BIN value */
387 b->core.bin = bam_reg2bin(b->core.pos, bam_endpos(b));
388
389 next_seq:
390 if (sam_write1(out, h, b) < 0) {
391 print_error_errno("depad", "error writing to output");
392 return -1;
393 }
394 }
395 if (read_ret < -1) {
396 fprintf(samtools_stderr, "[depad] truncated file.\n");
397 ret = 1;
398 }
399 free(r.s); free(q.s); free(posmap);
400 free(cigar2);
401 bam_destroy1(b);
402 return ret;
403 }
404
405 sam_hdr_t * fix_header(sam_hdr_t *old, faidx_t *fai)
406 {
407 int i = 0, ret = 0;
408 hts_pos_t unpadded_len = 0;
409 sam_hdr_t *header = sam_hdr_dup(old);
410 if (!header)
411 return NULL;
412
413 int nref = sam_hdr_nref(old);
414 char len_buf[64];
415
416 for (i = 0; i < nref; ++i) {
417 unpadded_len = get_unpadded_len(fai, sam_hdr_tid2name(old, i), sam_hdr_tid2len(old, i));
418 if (unpadded_len < 0) {
419 fprintf(samtools_stderr, "[depad] ERROR getting unpadded length of '%s', padded length %"PRIhts_pos"\n", sam_hdr_tid2name(old, i), (hts_pos_t) sam_hdr_tid2len(old, i));
420 } else if (unpadded_len > sam_hdr_tid2len(old, i)) {
421 fprintf(samtools_stderr, "[depad] New unpadded length of '%s' is larger than the padded length (%"PRIhts_pos" > %"PRIhts_pos")\n",
422 sam_hdr_tid2name(old, i), unpadded_len,
423 (hts_pos_t) sam_hdr_tid2len(old, i));
424 ret = 1;
425 } else {
426 sprintf(len_buf, "%"PRIhts_pos"", unpadded_len);
427 if ((ret |= sam_hdr_update_line(header, "SQ", "SN", sam_hdr_tid2name(header, i), "LN", len_buf, NULL)))
428 fprintf(samtools_stderr, "[depad] Error updating length of '%s' from %"PRIhts_pos" to %"PRIhts_pos"\n",
429 sam_hdr_tid2name(header, i),
430 (hts_pos_t) sam_hdr_tid2len(header, i),
431 unpadded_len);
432 //fprintf(samtools_stderr, "[depad] Recalculating '%s' length %i -> %i\n", old->target_name[i], old->target_len[i], header->target_len[i]);
433 }
434 }
435
436 if (ret) {
437 sam_hdr_destroy(header);
438 return NULL;
439 }
440
441 return header;
442 }
443
444 static int usage(int is_long_help);
445
446 int main_pad2unpad(int argc, char *argv[])
447 {
448 samFile *in = 0, *out = 0;
449 sam_hdr_t *h = 0, *h_fix = 0;
450 faidx_t *fai = 0;
451 int c, compress_level = -1, is_long_help = 0, no_pg = 0;
452 char in_mode[5], out_mode[6], *fn_out = 0, *fn_fai = 0, *fn_out_idx = NULL;
453 int ret=0;
454 char *arg_list = NULL;
455 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
456
457 static const struct option lopts[] = {
458 SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 'T', '-'),
459 {"no-PG", no_argument, NULL, 1},
460 { NULL, 0, NULL, 0 }
461 };
462
463 /* parse command-line options */
464 strcpy(in_mode, "r"); strcpy(out_mode, "w");
465 while ((c = getopt_long(argc, argv, "SCso:u1T:?", lopts, NULL)) >= 0) {
466 switch (c) {
467 case 'S': break;
468 case 'C': hts_parse_format(&ga.out, "cram"); break;
469 case 's': assert(compress_level == -1); hts_parse_format(&ga.out, "sam"); break;
470 case 'o': fn_out = strdup(optarg); break;
471 case 'u':
472 compress_level = 0;
473 if (ga.out.format == unknown_format)
474 hts_parse_format(&ga.out, "bam");
475 break;
476 case '1':
477 compress_level = 1;
478 if (ga.out.format == unknown_format)
479 hts_parse_format(&ga.out, "bam");
480 break;
481 case 1: no_pg = 1; break;
482 case '?': is_long_help = 1; break;
483 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
484 fprintf(samtools_stderr, "[bam_fillmd] unrecognized option '-%c'\n\n", c);
485 return usage(is_long_help);
486 }
487 }
488 if (argc == optind) return usage(is_long_help);
489
490 strcat(out_mode, "h");
491 if (compress_level >= 0) {
492 char tmp[2];
493 tmp[0] = compress_level + '0'; tmp[1] = '\0';
494 strcat(out_mode, tmp);
495 }
496
497 // Load FASTA reference (also needed for SAM -> BAM if missing header)
498 if (ga.reference) {
499 fn_fai = fai_path(ga.reference);
500 fai = fai_load3(ga.reference, fn_fai, NULL, FAI_CREATE);
501 }
502 // open file handlers
503 if ((in = sam_open_format(argv[optind], in_mode, &ga.in)) == 0) {
504 print_error_errno("depad", "failed to open \"%s\" for reading", argv[optind]);
505 ret = 1;
506 goto depad_end;
507 }
508 if (fn_fai && hts_set_fai_filename(in, fn_fai) != 0) {
509 fprintf(samtools_stderr, "[depad] failed to load reference file \"%s\".\n", fn_fai);
510 ret = 1;
511 goto depad_end;
512 }
513 if ((h = sam_hdr_read(in)) == 0) {
514 fprintf(samtools_stderr, "[depad] failed to read the header from \"%s\".\n", argv[optind]);
515 ret = 1;
516 goto depad_end;
517 }
518 if (fai) {
519 if (!(h_fix = fix_header(h, fai))){
520 fprintf(samtools_stderr, "[depad] failed to fix the header from\n");
521 ret = 1;
522 goto depad_end;
523 }
524 } else {
525 fprintf(samtools_stderr, "[depad] Warning - reference lengths will not be corrected without FASTA reference\n");
526 h_fix = h;
527 }
528 char wmode[2];
529 strcat(out_mode, sam_open_mode(wmode, fn_out, NULL)==0 ? wmode : "b");
530 if ((out = sam_open_format(fn_out? fn_out : "-", out_mode, &ga.out)) == 0) {
531 print_error_errno("depad", "failed to open \"%s\" for writing", fn_out? fn_out : "standard output");
532 ret = 1;
533 goto depad_end;
534 }
535
536 // Reference-based CRAM won't work unless we also create a new reference.
537 // We could embed this, but for now we take the easy option.
538 if (ga.out.format == cram)
539 hts_set_opt(out, CRAM_OPT_NO_REF, 1);
540
541 if (!no_pg) {
542 if(!(arg_list = stringify_argv(argc+1, argv-1))) {
543 fprintf(samtools_stderr, "[depad] failed to create arg_list\n");
544 ret = 1;
545 goto depad_end;
546 }
547
548 if (sam_hdr_add_pg(h_fix, "samtools",
549 "VN", samtools_version(),
550 arg_list ? "CL": NULL,
551 arg_list ? arg_list : NULL,
552 NULL)) {
553 fprintf(samtools_stderr, "[depad] failed to add PG line to header\n");
554 ret = 1;
555 goto depad_end;
556 }
557 }
558
559 if (sam_hdr_write(out, h_fix) != 0) {
560 fprintf(samtools_stderr, "[depad] failed to write header.\n");
561 ret = 1;
562 goto depad_end;
563 }
564 if (ga.write_index) {
565 if (!(fn_out_idx = auto_index(out, fn_out, h_fix))) {
566 ret = 1;
567 goto depad_end;
568 }
569 }
570
571 // Do the depad
572 if (bam_pad2unpad(in, out, h, fai) != 0) ret = 1;
573
574 if (ga.write_index) {
575 if (sam_idx_save(out) < 0) {
576 print_error_errno("depad", "writing index failed");
577 ret = 1;
578 }
579 }
580
581 depad_end:
582 // close files, free and return
583 free(arg_list);
584 if (fai) fai_destroy(fai);
585 if (h) sam_hdr_destroy(h);
586 if (h_fix && h_fix != h) sam_hdr_destroy(h_fix);
587 if (in) sam_close(in);
588 if (out && sam_close(out) < 0) {
589 fprintf(samtools_stderr, "[depad] error on closing output file.\n");
590 ret = 1;
591 }
592 free(fn_fai); free(fn_out);
593 if (fn_out_idx)
594 free(fn_out_idx);
595 sam_global_args_free(&ga);
596 return ret;
597 }
598
599 static int usage(int is_long_help)
600 {
601 fprintf(samtools_stderr, "\n");
602 fprintf(samtools_stderr, "Usage: samtools depad <in.bam>\n\n");
603 fprintf(samtools_stderr, "Options:\n");
604 fprintf(samtools_stderr, " -s Output is SAM (default is BAM)\n");
605 fprintf(samtools_stderr, " -S Input is SAM (default is BAM)\n");
606 fprintf(samtools_stderr, " -u Uncompressed BAM output (can't use with -s)\n");
607 fprintf(samtools_stderr, " -1 Fast compression BAM output (can't use with -s)\n");
608 fprintf(samtools_stderr, " -T, --reference FILE\n");
609 fprintf(samtools_stderr, " Padded reference sequence file [null]\n");
610 fprintf(samtools_stderr, " -o FILE Output file name [samtools_stdout]\n");
611 fprintf(samtools_stderr, " --no-PG do not add a PG line\n");
612 fprintf(samtools_stderr, " -? Longer help\n");
613 sam_global_opt_help(samtools_stderr, "-...--..");
614
615 if (is_long_help)
616 fprintf(samtools_stderr,
617 "Notes:\n"
618 "\n"
619 "1. Requires embedded reference sequences (before the reads for that reference),\n"
620 " or ideally a FASTA file of the padded reference sequences (via a -T option).\n"
621 "\n"
622 "2. Input padded alignment reads' CIGAR strings must not use P or I operators.\n"
623 "\n");
624 return 1;
625 }