Debian Codegraph @

samtools/bam_split.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam_split.c -- split subcommand.
4
5 Copyright (C) 2013-2016,2018-2019,2023,2024 Genome Research Ltd.
6
7 Author: Martin Pollard <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 DEALINGS IN THE SOFTWARE. */
26
27 #include <config.h>
28
29 #include <string.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdbool.h>
33 #include <limits.h>
34 #include <unistd.h>
35 #include <regex.h>
36 #include <assert.h>
37 #include <htslib/sam.h>
38 #include <htslib/khash.h>
39 #include <htslib/kstring.h>
40 #include <htslib/cram.h>
41 #include "htslib/thread_pool.h"
42 #include "sam_opts.h"
43 #include "samtools.h"
44
45
46 KHASH_MAP_INIT_STR(c2i, int)
47
48 struct parsed_opts {
49 const char *merged_input_name;
50 const char *unaccounted_header_name;
51 const char *unaccounted_name;
52 const char *output_format_string;
53 const char *tag;
54 long max_split;
55 bool verbose;
56 int no_pg;
57 int zero_pad;
58 sam_global_args ga;
59 };
60
61 #define DEFAULT_MAX_SPLIT 100
62
63 typedef struct parsed_opts parsed_opts_t;
64
65 struct state {
66 samFile* merged_input_file;
67 sam_hdr_t* merged_input_header;
68 samFile* unaccounted_file;
69 sam_hdr_t* unaccounted_header;
70 char *unaccounted_idx_fn;
71 size_t output_count;
72 char **tag_vals;
73 char **index_file_name;
74 char **output_file_name;
75 samFile **output_file;
76 sam_hdr_t **output_header;
77 kh_c2i_t* tag_val_hash;
78 htsThreadPool p;
79 int write_index;
80 };
81
82 typedef struct state state_t;
83
84 static int cleanup_state(state_t* status, bool check_close);
85 static void cleanup_opts(parsed_opts_t* opts);
86
87 static void usage(FILE *write_to)
88 {
89 fprintf(write_to,
90 "Usage: samtools split [-u <unaccounted.bam>] [-h <unaccounted_header.sam>]\n"
91 " [-f <format_string>] [-v] <merged.bam>\n"
92 "Options:\n"
93 " -f STRING output filename format string [\"%%*_%%#.%%.\"]\n"
94 " -u FILE1 put left-over reads in FILE1\n"
95 " -h FILE2 ... and override the header with FILE2 (-u file only)\n"
96 " -d TAG split by TAG value. TAG value must be a string.\n"
97 " -p NUMBER zero-pad numbers in filenames to NUMBER digits\n"
98 " -M,--max-split NUM limit number of output files from -d to NUM [%d]\n"
99 " -v verbose output\n"
100 " --no-PG do not add a PG line\n",
101 DEFAULT_MAX_SPLIT);
102 sam_global_opt_help(write_to, "-....@..");
103 fprintf(write_to,
104 "\n"
105 "Format string expansions:\n"
106 " %%%% %%\n"
107 " %%* basename\n"
108 " %%# index (of @RG in the header, or count of TAG values seen so far)\n"
109 " %%! @RG ID or TAG value\n"
110 " %%. filename extension for output format\n"
111 );
112 }
113
114 // Takes the command line options and turns them into something we can understand
115 static parsed_opts_t* parse_args(int argc, char** argv)
116 {
117 if (argc == 1) { usage(samtools_stdout); return NULL; }
118
119 const char *optstring = "vf:h:u:d:M:p:@:";
120 char *default_format_string = "%*_%#.%.";
121
122 static const struct option lopts[] = {
123 SAM_OPT_GLOBAL_OPTIONS('-', 0, 0, 0, 0, '@'),
124 {"no-PG", no_argument, NULL, 1},
125 {"max-split", required_argument, NULL, 'M'},
126 {"zero-pad", required_argument, NULL, 'p'},
127 { NULL, 0, NULL, 0 }
128 };
129
130 parsed_opts_t* retval = calloc(sizeof(parsed_opts_t), 1);
131 if (! retval ) { perror("cannot allocate option parsing memory"); return NULL; }
132
133 retval->max_split = DEFAULT_MAX_SPLIT;
134 sam_global_args_init(&retval->ga);
135
136 int opt;
137 while ((opt = getopt_long(argc, argv, optstring, lopts, NULL)) != -1) {
138 switch (opt) {
139 case 'f':
140 retval->output_format_string = optarg;
141 break;
142 case 'h':
143 retval->unaccounted_header_name = optarg;
144 break;
145 case 'v':
146 retval->verbose = true;
147 break;
148 case 'u':
149 retval->unaccounted_name = optarg;
150 break;
151 case 'd':
152 retval->tag = optarg;
153 default_format_string = "%*_%!.%.";
154 break;
155 case 'M': {
156 char *end = optarg;
157 retval->max_split = strtol(optarg, &end, 10);
158 if (*optarg == '\0' || *end != '\0' || retval->max_split == 0) {
159 print_error("split", "Invalid -M argument: \"%s\"", optarg);
160 free(retval);
161 return NULL;
162 }
163 if (retval->max_split < 0) // No limit requested
164 retval->max_split = LONG_MAX;
165 break;
166 }
167 case 'p': {
168 char *end = optarg;
169 unsigned long val = strtoul(optarg, &end, 10);
170 if (*optarg == '\0' || *end != '\0' || val > 20) {
171 print_error("split", "Invalid -p argument: \"%s\"", optarg);
172 free(retval);
173 return NULL;
174 }
175 retval->zero_pad = (int) val;
176 break;
177 }
178 case 1:
179 retval->no_pg = 1;
180 break;
181
182 default:
183 if (parse_sam_global_opt(opt, optarg, lopts, &retval->ga) == 0) break;
184 /* else fall-through */
185 case '?':
186 usage(samtools_stdout);
187 free(retval);
188 return NULL;
189 }
190 }
191
192 if (retval->output_format_string == NULL) retval->output_format_string = default_format_string;
193
194 argc -= optind;
195 argv += optind;
196
197 if (argc != 1) {
198 print_error("split", "Invalid number of arguments: %d", argc);
199 usage(samtools_stderr);
200 free(retval);
201 return NULL;
202 }
203
204 retval->merged_input_name = argv[0];
205
206 return retval;
207 }
208
209 // Expands a output filename format string
210 static char* expand_format_string(const char* format_string,
211 const char* basename, const char* tag_val,
212 const int file_idx, const int zero_pad,
213 const htsFormat *format)
214 {
215 kstring_t str = { 0, 0, NULL };
216 const char* pointer = format_string;
217 const char* next;
218 while ((next = strchr(pointer, '%')) != NULL) {
219 if (kputsn(pointer, next-pointer, &str) < 0) goto memfail;
220 ++next;
221 switch (*next) {
222 case '%':
223 if (kputc('%', &str) < 0) goto memfail;
224 break;
225 case '*':
226 if (kputs(basename, &str) < 0) goto memfail;
227 break;
228 case '#':
229 if (zero_pad == 0) {
230 if (kputl(file_idx, &str) < 0) goto memfail;
231 } else {
232 if (ksprintf(&str, "%0*d", zero_pad, file_idx) < 0)
233 goto memfail;
234 }
235 break;
236 case '!':
237 if (kputs(tag_val, &str) < 0) goto memfail;
238 break;
239 case '.':
240 // Only really need to cope with sam, bam, cram
241 if (format->format != unknown_format) {
242 if (kputs(hts_format_file_extension(format), &str) < 0)
243 goto memfail;
244 } else {
245 if (kputs("bam", &str) < 0) goto memfail;
246 }
247 break;
248 case '\0':
249 print_error("split", "Trailing %% in filename format string");
250 goto fail;
251 default:
252 // Error is: fprintf(samtools_stderr, "bad format string, unknown format specifier\n");
253 print_error("split", "Unknown specifier %%%c in filename format string", *next);
254 goto fail;
255 }
256 pointer = next + 1;
257 }
258 if (kputs(pointer, &str) < 0) goto memfail;
259 return ks_release(&str);
260
261 memfail:
262 print_error_errno("split", "Couldn't build output filename");
263 fail:
264 free(str.s);
265 return NULL;
266 }
267
268 // Parse the header, count the number of RG tags and return a list of their names
269 static bool count_RG(sam_hdr_t* hdr, size_t* count, char*** output_name)
270 {
271 char **names = NULL;
272 kstring_t id_val = KS_INITIALIZE;
273 int i, n_rg = sam_hdr_count_lines(hdr, "RG");
274
275 if (n_rg < 0) {
276 print_error("split", "Failed to get @RG IDs");
277 *count = 0;
278 *output_name = NULL;
279 return false;
280 }
281
282 if (n_rg == 0) {
283 *count = 0;
284 *output_name = NULL;
285 return true;
286 }
287
288 names = calloc(n_rg, sizeof(names[0]));
289 if (!names) goto memfail;
290
291 for (i = 0; i < n_rg; i++) {
292 if (sam_hdr_find_tag_pos(hdr, "RG", i, "ID", &id_val) < 0) goto memfail;
293 names[i] = ks_release(&id_val);
294 }
295
296 *count = n_rg;
297 *output_name = names;
298 return true;
299
300 memfail:
301 print_error_errno("split", "Failed to get @RG IDs");
302 *count = 0;
303 *output_name = NULL;
304 ks_free(&id_val);
305 free(names);
306 return false;
307 }
308
309 static int header_compatible(sam_hdr_t *hdr1, sam_hdr_t *hdr2)
310 {
311 size_t n;
312 if (sam_hdr_nref(hdr1) != sam_hdr_nref(hdr2)) {
313 print_error("split",
314 "Unaccounted header contains wrong number of references");
315 return -1;
316 }
317 for (n = 0; n < sam_hdr_nref(hdr1); n++) {
318 hts_pos_t h1_len = sam_hdr_tid2len(hdr1, n);
319 hts_pos_t h2_len = sam_hdr_tid2len(hdr2, n);
320 if (h1_len != h2_len) {
321 print_error("split",
322 "Unaccounted header reference %zu \"%s\" is not the same length as in the input file",
323 n + 1, sam_hdr_tid2name(hdr2, n));
324 return -1;
325 }
326 }
327 return 0;
328 }
329
330 static int grow_output_lists(state_t *state, size_t count) {
331 char **new_list = realloc(state->tag_vals, count * sizeof(char *));
332 if (!new_list)
333 return -1;
334 state->tag_vals = new_list;
335 new_list = realloc(state->index_file_name, count * sizeof(char *));
336 if (!new_list)
337 return -1;
338 state->index_file_name = new_list;
339 new_list = realloc(state->output_file_name, count * sizeof(char *));
340 if (!new_list)
341 return -1;
342 state->output_file_name = new_list;
343 samFile **new_file = realloc(state->output_file,
344 count * sizeof(samFile *));
345 if (!new_file)
346 return -1;
347 state->output_file = new_file;
348 sam_hdr_t **new_hdr = realloc(state->output_header,
349 count * sizeof(sam_hdr_t *));
350 if (!new_hdr)
351 return -1;
352 state->output_header = new_hdr;
353 return 0;
354 }
355
356 static khiter_t prep_sam_file(parsed_opts_t *opts, state_t *state,
357 const char *tag, const char *arg_list,
358 int is_rg) {
359 char *input_base_name = NULL, *new_file_name = NULL, *tag_val = NULL;
360 char *new_idx_fn = NULL;
361 sam_hdr_t *new_hdr = NULL;
362 samFile *new_sam_file = NULL;
363
364 khiter_t i = kh_get_c2i(state->tag_val_hash, tag);
365 if (i != kh_end(state->tag_val_hash)) {
366 return i;
367 }
368 // create new file
369 if (grow_output_lists(state, state->output_count + 1) != 0) {
370 print_error_errno("split", "Couldn't grow output lists");
371 return kh_end(state->tag_val_hash);
372 }
373 tag_val = strdup(tag);
374 if (!tag_val) {
375 print_error_errno("split", "Couldn't copy tag value");
376 return kh_end(state->tag_val_hash);
377 }
378 char *dirsep = strrchr(opts->merged_input_name, '/');
379 input_base_name = strdup(dirsep? dirsep+1 : opts->merged_input_name);
380 if (!input_base_name) {
381 print_error_errno("split", "Filename parsing failed");
382 goto fail;
383 }
384
385 char* extension = strrchr(input_base_name, '.');
386 if (extension) *extension = '\0';
387
388 new_file_name = expand_format_string(opts->output_format_string,
389 input_base_name, tag,
390 kh_size(state->tag_val_hash),
391 opts->zero_pad, &opts->ga.out);
392 if (!new_file_name) {
393 print_error_errno("split", "Filename creation failed");
394 goto fail;
395 }
396
397 new_hdr = sam_hdr_dup(state->merged_input_header);
398 if (!new_hdr) {
399 print_error_errno("split", "Duplicating header for file \"%s\" failed", new_file_name);
400 goto fail;
401 }
402 if (!opts->no_pg && sam_hdr_add_pg(new_hdr, "samtools",
403 "VN", samtools_version(),
404 arg_list ? "CL": NULL,
405 arg_list ? arg_list : NULL,
406 NULL)) {
407 print_error_errno("split", "Adding PG line to file \"%s\" failed", new_file_name);
408 goto fail;
409 }
410
411 if (is_rg) {
412 // If here, we've found an RG:Z: tag without a corresponding @RG
413 // line in the header.
414 if (sam_hdr_remove_lines(new_hdr, "RG", "ID", NULL) != 0) {
415 print_error_errno("split",
416 "Failed to remove @RG lines from file \"%s\"",
417 new_file_name);
418 goto fail;
419 }
420 if (sam_hdr_add_line(new_hdr, "RG", "ID", tag_val, NULL) != 0) {
421 print_error_errno("split",
422 "Failed to add @RG line to file \"%s\"",
423 new_file_name);
424 goto fail;
425 }
426 }
427
428 char outmode[4] = "w";
429 sam_open_mode(outmode + 1, new_file_name, NULL);
430 new_sam_file = sam_open_format(new_file_name, outmode, &opts->ga.out);
431 if (!new_sam_file) {
432 print_error_errno("split", "Opening filename for writing \"%s\" failed", new_file_name);
433 goto fail;
434 }
435 if (state->p.pool)
436 hts_set_opt(new_sam_file, HTS_OPT_THREAD_POOL, &state->p);
437
438 if (sam_hdr_write(new_sam_file, new_hdr) != 0) {
439 print_error_errno("split", "Couldn't write header to \"%s\"",
440 new_file_name);
441 goto fail;
442 }
443
444 if (state->write_index) {
445 new_idx_fn = auto_index(new_sam_file, new_file_name, new_hdr);
446 if (!new_idx_fn) {
447 print_error_errno("split", "Creating index file for file \"%s\" failed", new_file_name);
448 goto fail;
449 }
450 }
451
452 int ret = -1;
453 i = kh_put_c2i(state->tag_val_hash, tag_val, &ret);
454 if (ret < 0) {
455 print_error_errno("split", "Adding file \"%s\" failed", new_file_name);
456 goto fail;
457 }
458
459 kh_val(state->tag_val_hash, i) = state->output_count;
460 state->tag_vals[state->output_count] = tag_val;
461 state->index_file_name[state->output_count] = new_idx_fn;
462 state->output_file_name[state->output_count] = new_file_name;
463 state->output_file[state->output_count] = new_sam_file;
464 state->output_header[state->output_count] = new_hdr;
465 state->output_count++;
466 free(input_base_name);
467 return i;
468
469 fail:
470 free(input_base_name);
471 free(new_file_name);
472 free(tag_val);
473 free(new_idx_fn);
474 if (new_hdr)
475 sam_hdr_destroy(new_hdr);
476 if (new_sam_file)
477 sam_close(new_sam_file);
478 return kh_end(state->tag_val_hash);
479 }
480
481 // Set the initial state
482 static state_t* init(parsed_opts_t* opts, const char *arg_list)
483 {
484 state_t* retval = calloc(sizeof(state_t), 1);
485 if (!retval) {
486 print_error_errno("split", "Initialisation failed");
487 return NULL;
488 }
489
490 if (opts->ga.nthreads > 0) {
491 if (!(retval->p.pool = hts_tpool_init(opts->ga.nthreads))) {
492 fprintf(samtools_stderr, "Error creating thread pool\n");
493 cleanup_state(retval, false);
494 return NULL;
495 }
496 }
497
498 retval->merged_input_file = sam_open_format(opts->merged_input_name, "r", &opts->ga.in);
499 if (!retval->merged_input_file) {
500 print_error_errno("split", "Could not open \"%s\"", opts->merged_input_name);
501 cleanup_state(retval, false);
502 return NULL;
503 }
504 if (retval->p.pool)
505 hts_set_opt(retval->merged_input_file, HTS_OPT_THREAD_POOL, &retval->p);
506 retval->merged_input_header = sam_hdr_read(retval->merged_input_file);
507 if (retval->merged_input_header == NULL) {
508 print_error("split", "Could not read header from \"%s\"", opts->merged_input_name);
509 cleanup_state(retval, false);
510 return NULL;
511 }
512 retval->write_index = opts->ga.write_index;
513
514 if (opts->unaccounted_name) {
515 if (opts->unaccounted_header_name) {
516 samFile* hdr_load = sam_open_format(opts->unaccounted_header_name, "r", &opts->ga.in);
517 if (!hdr_load) {
518 print_error_errno("split", "Could not open unaccounted header file \"%s\"", opts->unaccounted_header_name);
519 cleanup_state(retval, false);
520 return NULL;
521 }
522 retval->unaccounted_header = sam_hdr_read(hdr_load);
523 if (retval->unaccounted_header == NULL) {
524 print_error("split", "Could not read header from \"%s\"", opts->unaccounted_header_name);
525 cleanup_state(retval, false);
526 sam_close(hdr_load);
527 return NULL;
528 }
529 sam_close(hdr_load);
530 if (header_compatible(retval->merged_input_header,
531 retval->unaccounted_header) != 0) {
532 cleanup_state(retval, false);
533 return NULL;
534 }
535 } else {
536 retval->unaccounted_header = sam_hdr_dup(retval->merged_input_header);
537 if (!opts->no_pg && sam_hdr_add_pg(retval->unaccounted_header, "samtools",
538 "VN", samtools_version(),
539 arg_list ? "CL": NULL,
540 arg_list ? arg_list : NULL,
541 NULL)) {
542 print_error("split", "Could not rewrite header for \"%s\"", opts->unaccounted_name);
543 cleanup_state(retval, false);
544 return NULL;
545 }
546 }
547
548 char outmode[4] = "w";
549 sam_open_mode(outmode + 1, opts->unaccounted_name, NULL);
550 retval->unaccounted_file = sam_open_format(opts->unaccounted_name, outmode, &opts->ga.out);
551
552 if (retval->unaccounted_file == NULL) {
553 print_error_errno("split", "Could not open unaccounted output file \"%s\"", opts->unaccounted_name);
554 cleanup_state(retval, false);
555 return NULL;
556 }
557 if (retval->p.pool)
558 hts_set_opt(retval->unaccounted_file, HTS_OPT_THREAD_POOL, &retval->p);
559 }
560
561 int is_rg = !opts->tag || strcmp(opts->tag, "RG") == 0;
562 if (is_rg) {
563 if (!count_RG(retval->merged_input_header,
564 &retval->output_count, &retval->tag_vals)) {
565 cleanup_state(retval, false);
566 return NULL;
567 }
568 if (opts->verbose)
569 fprintf(samtools_stderr, "@RG's found %zu\n",retval->output_count);
570 } else {
571 retval->output_count = 0;
572 }
573
574 // Prevent calloc(0, size);
575 size_t num = retval->output_count ? retval->output_count : 1;
576 retval->index_file_name = (char **)calloc(num, sizeof(char *));
577 retval->output_file_name = (char **)calloc(num, sizeof(char *));
578 retval->output_file = (samFile**)calloc(num, sizeof(samFile*));
579 retval->output_header = (sam_hdr_t**)calloc(num, sizeof(sam_hdr_t*));
580 retval->tag_val_hash = kh_init_c2i();
581 if (!retval->output_file_name || !retval->output_file || !retval->output_header ||
582 !retval->tag_val_hash || !retval->index_file_name) {
583 print_error_errno("split", "Could not initialise output file array");
584 cleanup_state(retval, false);
585 return NULL;
586 }
587 if (!is_rg)
588 return retval; // Done for this case - outputs will be opened later
589
590 // Adjust max_split if too small for the read-groups listed in the header
591 if (opts->max_split < retval->output_count)
592 opts->max_split = retval->output_count;
593
594 // Open output files for RGs
595 char* dirsep = strrchr(opts->merged_input_name, '/');
596 char* input_base_name = strdup(dirsep? dirsep+1 : opts->merged_input_name);
597 if (!input_base_name) {
598 print_error_errno("split", "Filename manipulation failed");
599 cleanup_state(retval, false);
600 return NULL;
601 }
602 char* extension = strrchr(input_base_name, '.');
603 if (extension) *extension = '\0';
604
605 size_t i;
606 for (i = 0; i < retval->output_count; i++) {
607 char* output_filename = NULL;
608 char outmode[4] = "w";
609
610 output_filename = expand_format_string(opts->output_format_string,
611 input_base_name,
612 retval->tag_vals[i], i,
613 opts->zero_pad, &opts->ga.out);
614
615 if ( output_filename == NULL ) {
616 cleanup_state(retval, false);
617 free(input_base_name);
618 return NULL;
619 }
620
621 retval->output_file_name[i] = output_filename;
622 sam_open_mode(outmode + 1, output_filename, NULL);
623 retval->output_file[i] = sam_open_format(output_filename, outmode, &opts->ga.out);
624
625 if (retval->output_file[i] == NULL) {
626 print_error_errno("split", "Could not open \"%s\"", output_filename);
627 cleanup_state(retval, false);
628 free(input_base_name);
629 return NULL;
630 }
631 if (retval->p.pool)
632 hts_set_opt(retval->output_file[i], HTS_OPT_THREAD_POOL, &retval->p);
633
634 // Record index in hash
635 int ret;
636 khiter_t iter = kh_put_c2i(retval->tag_val_hash, retval->tag_vals[i], &ret);
637 if (ret < 0) {
638 print_error_errno("split", "Couldn't add @RG ID to look-up table");
639 cleanup_state(retval, false);
640 free(input_base_name);
641 return NULL;
642 }
643 kh_val(retval->tag_val_hash,iter) = i;
644
645 // Set and edit header
646 retval->output_header[i] = sam_hdr_dup(retval->merged_input_header);
647 if (sam_hdr_remove_except(retval->output_header[i], "RG", "ID", retval->tag_vals[i]) ||
648 (!opts->no_pg &&
649 sam_hdr_add_pg(retval->output_header[i], "samtools",
650 "VN", samtools_version(),
651 arg_list ? "CL": NULL,
652 arg_list ? arg_list : NULL,
653 NULL))) {
654 print_error("split", "Could not rewrite header for \"%s\"", output_filename);
655 cleanup_state(retval, false);
656 free(input_base_name);
657 return NULL;
658 }
659 }
660
661 free(input_base_name);
662
663 return retval;
664 }
665
666 static bool split(state_t* state, parsed_opts_t *opts, char *arg_list)
667 {
668 int is_rg = !opts->tag || strcmp(opts->tag, "RG") == 0;
669 if (state->unaccounted_file) {
670 if (sam_hdr_write(state->unaccounted_file, state->unaccounted_header) != 0) {
671 print_error_errno("split", "Could not write output file header");
672 return false;
673 }
674 if (opts->ga.write_index) {
675 state->unaccounted_idx_fn = auto_index(state->unaccounted_file,
676 opts->unaccounted_name,
677 state->unaccounted_header);
678 if (!state->unaccounted_idx_fn) {
679 print_error_errno("split",
680 "Creating index file for file \"%s\" failed",
681 opts->unaccounted_name);
682 return false;
683 }
684 }
685 }
686 bam1_t* file_read = bam_init1();
687 // Read the first record
688 int r;
689 if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) {
690 // Nothing more to read? Ignore this file
691 bam_destroy1(file_read);
692 file_read = NULL;
693 if (r < -1) {
694 print_error("split", "Could not read first input record");
695 return false;
696 }
697 }
698
699 if (is_rg) {
700 size_t i;
701 for (i = 0; i < state->output_count; i++) {
702 if (sam_hdr_write(state->output_file[i], state->output_header[i]) != 0) {
703 print_error_errno("split", "Could not write file header to \"%s\"", state->output_file_name[i]);
704 goto error;
705 }
706 if (state->write_index) {
707 state->index_file_name[i] = auto_index(state->output_file[i],
708 state->output_file_name[i],
709 state->output_header[i]);
710 if (!state->index_file_name[i]) {
711 print_error_errno("split", "Could not create index for file \"%s\"", state->output_file_name[i]);
712 goto error;
713 }
714 }
715 }
716 }
717 while (file_read != NULL) {
718 // Get RG tag from read and look it up in hash to find file to output it to
719 uint8_t* tag = bam_aux_get(file_read, is_rg ? "RG" : opts->tag);
720 char *val = NULL;
721 char number[28];
722 khiter_t iter;
723 if (tag) {
724 switch (*tag) {
725 case 'Z': case 'H':
726 val = bam_aux2Z(tag);
727 break;
728 case 'c': case 'C': case 's': case 'S': case 'i': case 'I':
729 if (opts->zero_pad == 0) {
730 snprintf(number, sizeof(number), "%"PRId64, bam_aux2i(tag));
731 } else {
732 int64_t v = bam_aux2i(tag);
733 snprintf(number, sizeof(number), "%0*"PRId64,
734 v < 0 ? opts->zero_pad + 1 : opts->zero_pad, v);
735 }
736 val = number;
737 break;
738 default:
739 break;
740 }
741 }
742 if ( val != NULL ) {
743 iter = kh_get_c2i(state->tag_val_hash, val);
744 } else {
745 iter = kh_end(state->tag_val_hash);
746 }
747
748 // Check for opts->tag here instead of !is_rg so we open new
749 // files if the user specified '-d RG' and we find a RG:Z: value
750 // that wasn't listed in the header. If the '-d' option is
751 // not used, we don't open a file to preserve existing behaviour.
752 if (opts->tag && val && iter == kh_end(state->tag_val_hash)
753 && state->output_count < opts->max_split) {
754 // Need to open a new output file
755 iter = prep_sam_file(opts, state, val, arg_list, is_rg);
756 if (iter == kh_end(state->tag_val_hash)) { // Open failed
757 print_error("split",
758 "Could not create output file for tag \"%s:%s\"",
759 opts->tag, bam_aux2Z(tag));
760 goto error;
761
762 }
763 }
764
765 // Write the read out to correct file
766 if (iter != kh_end(state->tag_val_hash)) {
767 // if found write to the appropriate untangled bam
768 int i = kh_val(state->tag_val_hash,iter);
769 if (sam_write1(state->output_file[i], state->output_header[i], file_read) < 0) {
770 print_error_errno("split", "Could not write to \"%s\"", state->output_file_name[i]);
771 goto error;
772 }
773 } else {
774 // otherwise write to the unaccounted bam if there is one or fail
775 if (state->unaccounted_file == NULL) {
776 if (tag) {
777 fprintf(samtools_stderr, "Read \"%s\" with unaccounted for tag \"%s\".\n", bam_get_qname(file_read), bam_aux2Z(tag));
778 } else {
779 fprintf(samtools_stderr, "Read \"%s\" has no %s tag.\n",
780 bam_get_qname(file_read), is_rg ? "RG" : opts->tag);
781 }
782 goto error;
783 } else {
784 if (sam_write1(state->unaccounted_file, state->unaccounted_header, file_read) < 0) {
785 print_error_errno("split", "Could not write to unaccounted output file");
786 goto error;
787 }
788 }
789 }
790
791 // Replace written read with the next one to process
792 if ((r=sam_read1(state->merged_input_file, state->merged_input_header, file_read)) < 0) {
793 // Nothing more to read? Ignore this file in future
794 bam_destroy1(file_read);
795 file_read = NULL;
796 if (r < -1) {
797 print_error("split", "Could not read input record");
798 return false;
799 }
800 }
801 }
802
803 if (state->write_index) {
804 size_t i;
805 for (i = 0; i < state->output_count; i++) {
806 if (sam_idx_save(state->output_file[i]) < 0) {
807 print_error_errno("split", "writing index \"%s\" failed",
808 state->index_file_name[i]);
809 return false;
810 }
811 }
812 if (state->unaccounted_file) {
813 if (sam_idx_save(state->unaccounted_file) < 0) {
814 print_error_errno("split", "writing index \"%s\" failed",
815 state->unaccounted_idx_fn);
816 return false;
817 }
818 }
819 }
820
821 return true;
822 error:
823 bam_destroy1(file_read);
824 return false;
825 }
826
827 static int cleanup_state(state_t* status, bool check_close)
828 {
829 int ret = 0;
830
831 if (!status) return 0;
832 if (status->unaccounted_header) sam_hdr_destroy(status->unaccounted_header);
833 if (status->unaccounted_file) {
834 if (sam_close(status->unaccounted_file) < 0 && check_close) {
835 print_error("split", "Error on closing unaccounted file");
836 ret = -1;
837 }
838 }
839 sam_close(status->merged_input_file);
840 size_t i;
841 for (i = 0; i < status->output_count; i++) {
842 if (status->output_header && status->output_header[i])
843 sam_hdr_destroy(status->output_header[i]);
844 if (status->output_file && status->output_file[i]) {
845 if (sam_close(status->output_file[i]) < 0 && check_close) {
846 print_error("split", "Error on closing output file \"%s\"", status->output_file_name[i]);
847 ret = -1;
848 }
849 }
850 if (status->tag_vals) free(status->tag_vals[i]);
851 if (status->output_file_name) free(status->output_file_name[i]);
852 if (status->index_file_name[i]) free(status->index_file_name[i]);
853 }
854 if (status->merged_input_header)
855 sam_hdr_destroy(status->merged_input_header);
856 free(status->output_header);
857 free(status->output_file);
858 free(status->output_file_name);
859 free(status->index_file_name);
860 free(status->unaccounted_idx_fn);
861 kh_destroy_c2i(status->tag_val_hash);
862
863 free(status->tag_vals);
864 if (status->p.pool)
865 hts_tpool_destroy(status->p.pool);
866 free(status);
867
868 return ret;
869 }
870
871 static void cleanup_opts(parsed_opts_t* opts)
872 {
873 if (!opts) return;
874 sam_global_args_free(&opts->ga);
875 free(opts);
876 }
877
878 int main_split(int argc, char** argv)
879 {
880 int ret = 1;
881 char *arg_list = NULL;
882 parsed_opts_t* opts = parse_args(argc, argv);
883 if (!opts) goto cleanup_opts;
884 if (!opts->no_pg && !(arg_list = stringify_argv(argc+1, argv-1)))
885 goto cleanup_opts;
886 state_t* status = init(opts, arg_list);
887 if (!status) goto cleanup_opts;
888
889 if (!split(status, opts, arg_list)) {
890 cleanup_state(status, false);
891 goto cleanup_opts;
892 }
893
894 ret = cleanup_state(status, true);
895
896 cleanup_opts:
897 cleanup_opts(opts);
898 free(arg_list);
899
900 return ret;
901 }