- if (q[1] < 0) return -1; // no high scoring segments
- endx = x - 1;
- // find the left boundary
- for (k = c->n_cigar - 1, score = max = 0, x = x-1, y = y-1; k >= 0; --k) {
- int op = cigar[k]&0xf;
- int ol = cigar[k]>>4;
- if (op == BAM_CMATCH) {
- for (j = 0; j < ol; ++j) {
- int c1, c2, z = y - j;
- c1 = bam_nt16_nt4_table[bam1_seqi(seq, z)];
- if (ref[x+j] == 0) return -1;
- c2 = bam_nt16_nt4_table[(int)bam_nt16_table[(int)ref[x-j]]];
- if (c1 < 3 && c2 < 3)
- score += c1 == c2? 5 : -4;
- if (score < 0) score = 0;
- if (score > max) max = score, q[0] = z, r[0] = x-j, kk[0] = k, kl[0] = j + 1;
- }
- x -= ol; y -= ol;
- } else if (op == BAM_CINS) {
- score -= 4 - ol * 3;
- y -= ol;
- if (score < 0) score = 0;
- } else if (op == BAM_CDEL) {
- score -= 4 - ol * 3;
- x -= ol;
- if (score < 0) score = 0;
- } else if (op == BAM_CSOFT_CLIP) y -= ol;
- else if (op == BAM_CREF_SKIP) x -= ol;
- }
- if (q[0] < 0 || q[1] - q[0] < 15) return -1; // the high-scoring segment is too short
- // modify CIGAR
- n_cigar = 0;
- cigar = calloc(c->n_cigar + 4, 4);
- if (q[0] != 0) cigar[n_cigar++] = (uint32_t)q[0]<<4 | BAM_CSOFT_CLIP;
- if (r[0] != c->pos) cigar[n_cigar++] = (uint32_t)(r[0] - c->pos)<<4 | BAM_CREF_SKIP;
- if (kk[0] == kk[1]) {
- cigar[n_cigar++] = (uint32_t)(kl[0] + kl[1] - (bam1_cigar(b)[kk[0]]>>4))<<4 | BAM_CMATCH;
- } else {
- cigar[n_cigar++] = (uint32_t)kl[0]<<4 | BAM_CMATCH;
- for (k = kk[0] + 1; k < kk[1]; ++k)
- cigar[n_cigar++] = bam1_cigar(b)[k];
- cigar[n_cigar++] = (uint32_t)kl[1]<<4 | BAM_CMATCH; // FIXME: add ref_skip after this line
- }
- if (q[1] + 1 != c->l_qseq)
- cigar[n_cigar++] = (uint32_t)(c->l_qseq - q[1] - 1)<<4 | BAM_CSOFT_CLIP;
- // copy over the alignment
- if (4 * (n_cigar - (int)c->n_cigar) + b->data_len > b->m_data) { // enlarge b->data
- b->m_data = 4 * (n_cigar - (int)c->n_cigar) + b->data_len;
- kroundup32(b->m_data);
- b->data = realloc(b->data, b->m_data);
- }
- if (n_cigar != (int)c->n_cigar) { // move data
- memmove(b->data + c->l_qname + 4 * n_cigar, bam1_seq(b), b->data_len - c->l_qname - 4 * c->n_cigar);
- b->data_len += 4 * (n_cigar - (int)c->n_cigar);
+ if (bq || zq) {
+ if ((apply_baq && zq) || (!apply_baq && bq)) return -3; // in both cases, do nothing
+ if (bq && apply_baq) { // then convert BQ to ZQ
+ for (i = 0; i < c->l_qseq; ++i)
+ qual[i] = qual[i] + 64 < bq[i]? 0 : qual[i] - ((int)bq[i] - 64);
+ *(bq - 3) = 'Z';
+ } else if (zq && !apply_baq) { // then convert ZQ to BQ
+ for (i = 0; i < c->l_qseq; ++i)
+ qual[i] += (int)zq[i] - 64;
+ *(zq - 3) = 'B';
+ }
+ return 0;