8 void bam_fillmd1(bam1_t *b, char *ref, int is_equal)
10 uint8_t *seq = bam1_seq(b);
11 uint32_t *cigar = bam1_cigar(b);
12 bam1_core_t *c = &b->core;
17 old_md = bam_aux_get(b, "MD");
18 if (c->flag & BAM_FUNMAP) return;
19 if (old_md && !is_equal) return; // no need to add MD
20 str = (kstring_t*)calloc(1, sizeof(kstring_t));
21 for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
22 int j, l = cigar[i]>>4, op = cigar[i]&0xf;
23 if (op == BAM_CMATCH) {
24 for (j = 0; j < l; ++j) {
26 int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
27 if (ref[x+j] == 0) break; // out of boundary
28 if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) {
29 if (is_equal) seq[z/2] &= (z&1)? 0xf0 : 0x0f;
32 ksprintf(str, "%d", u);
39 } else if (op == BAM_CDEL) {
40 ksprintf(str, "%d", u);
42 for (j = 0; j < l; ++j) {
43 if (ref[x+j] == 0) break;
49 } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) {
51 } else if (op == BAM_CREF_SKIP) {
55 ksprintf(str, "%d", u);
56 if (!old_md) bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s);
59 if (strlen((char*)old_md+1) == str->l) {
60 for (i = 0; i < str->l; ++i)
61 if (toupper(old_md[i+1]) != toupper(str->s[i]))
63 if (i < str->l) is_diff = 1;
66 fprintf(stderr, "[bam_fillmd1] different MD for read '%s': '%s' != '%s'\n", bam1_qname(b), old_md+1, str->s);
68 free(str->s); free(str);
71 int bam_fillmd(int argc, char *argv[])
73 int c, is_equal = 0, tid = -2, ret, len;
74 bamFile fp, fpout = 0;
80 while ((c = getopt(argc, argv, "e")) >= 0) {
82 case 'e': is_equal = 1; break;
83 default: fprintf(stderr, "[bam_fillmd] unrecognized option '-%c'\n", c); return 1;
86 if (optind + 1 >= argc) {
87 fprintf(stderr, "Usage: bam fillmd [-e] <aln.bam> <ref.fasta>\n");
90 fp = strcmp(argv[optind], "-")? bam_open(argv[optind], "r") : bam_dopen(fileno(stdin), "r");
92 header = bam_header_read(fp);
93 fpout = bam_dopen(fileno(stdout), "w");
94 bam_header_write(fpout, header);
95 fai = fai_load(argv[optind+1]);
98 while ((ret = bam_read1(fp, b)) >= 0) {
99 if (b->core.tid >= 0) {
100 if (tid != b->core.tid) {
102 ref = fai_fetch(fai, header->target_name[b->core.tid], &len);
105 bam_fillmd1(b, ref, is_equal);
107 bam_write1(fpout, b);
113 bam_header_destroy(header);
114 bam_close(fp); bam_close(fpout);