6 void bam_fillmd1(bam1_t *b, char *ref, int is_equal)
8 uint8_t *seq = bam1_seq(b);
9 uint32_t *cigar = bam1_cigar(b);
10 bam1_core_t *c = &b->core;
11 int i, x, y, u = 0, has_md = 0;
14 if (bam_aux_get(b, "MD")) has_md = 1;
15 if (has_md == 1 && !is_equal) return; // no need to add MD
16 str = (kstring_t*)calloc(1, sizeof(kstring_t));
17 if (c->flag & BAM_FUNMAP) return;
18 for (i = y = 0, x = c->pos; i < c->n_cigar; ++i) {
19 int j, l = cigar[i]>>4, op = cigar[i]&0xf;
20 if (op == BAM_CMATCH) {
21 for (j = 0; j < l; ++j) {
23 int c1 = bam1_seqi(seq, z), c2 = bam_nt16_table[(int)ref[x+j]];
24 if (ref[x+j] == 0) break; // out of boundary
25 if ((c1 == c2 && c1 != 15 && c2 != 15) || c1 == 0) {
26 if (is_equal) seq[z/2] &= (z&1)? 0xf0 : 0x0f;
29 ksprintf(str, "%d", u);
36 } else if (op == BAM_CDEL) {
37 ksprintf(str, "%d", u);
39 for (j = 0; j < l; ++j) {
40 if (ref[x+j] == 0) break;
45 } else if (op == BAM_CINS || op == BAM_CSOFT_CLIP) {
47 } else if (op == BAM_CREF_SKIP) {
51 ksprintf(str, "%d", u);
52 if (!has_md) bam_aux_append(b, "MD", 'Z', str->l + 1, (uint8_t*)str->s);
53 free(str->s); free(str);
56 int bam_fillmd(int argc, char *argv[])
58 int c, is_equal = 0, tid = -1, ret, len;
59 bamFile fp, fpout = 0;
65 while ((c = getopt(argc, argv, "e")) >= 0) {
67 case 'e': is_equal = 1; break;
68 default: fprintf(stderr, "[bam_fillmd] unrecognized option '-%c'\n", c); return 1;
71 if (optind + 1 >= argc) {
72 fprintf(stderr, "Usage: bam fillmd [-e] <aln.bam> <ref.fasta>\n");
75 fp = strcmp(argv[optind], "-")? bam_open(argv[optind], "r") : bam_dopen(fileno(stdin), "r");
77 header = bam_header_read(fp);
78 fpout = bam_dopen(fileno(stdout), "w");
79 bam_header_write(fpout, header);
80 fai = fai_load(argv[optind+1]);
83 while ((ret = bam_read1(fp, b)) >= 0) {
84 if (tid != b->core.tid)
85 ref = fai_fetch(fai, header->target_name[b->core.tid], &len);
86 bam_fillmd1(b, ref, is_equal);
92 bam_header_destroy(header);
93 bam_close(fp); bam_close(fpout);