Debian Codegraph @

samtools/bam_split.c

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