+// FIXME: we'd better use no global variables...
+static rghash_t g_rghash = 0;
+static int g_min_mapQ = 0, g_flag_on = 0, g_flag_off = 0, g_qual_scale = 0, g_min_qlen = 0;
+static uint32_t g_subsam_seed = 0;
+static double g_subsam_frac = -1.;
+static char *g_library, *g_rg;
+static void *g_bed;
+
+void *bed_read(const char *fn);
+void bed_destroy(void *_h);
+int bed_overlap(const void *_h, const char *chr, int beg, int end);
+
+static int process_aln(const bam_header_t *h, bam1_t *b)
+{
+ if (g_qual_scale > 1) {
+ int i;
+ uint8_t *qual = bam1_qual(b);
+ for (i = 0; i < b->core.l_qseq; ++i) {
+ int c = qual[i] * g_qual_scale;
+ qual[i] = c < 93? c : 93;
+ }
+ }
+ if (g_min_qlen > 0) {
+ int k, qlen = 0;
+ uint32_t *cigar = bam1_cigar(b);
+ for (k = 0; k < b->core.n_cigar; ++k)
+ if ((bam_cigar_type(bam_cigar_op(cigar[k]))&1) || bam_cigar_op(cigar[k]) == BAM_CHARD_CLIP)
+ qlen += bam_cigar_oplen(cigar[k]);
+ if (qlen < g_min_qlen) return 1;
+ }
+ if (b->core.qual < g_min_mapQ || ((b->core.flag & g_flag_on) != g_flag_on) || (b->core.flag & g_flag_off))
+ return 1;
+ if (g_bed && b->core.tid >= 0 && !bed_overlap(g_bed, h->target_name[b->core.tid], b->core.pos, bam_calend(&b->core, bam1_cigar(b))))
+ return 1;
+ if (g_subsam_frac > 0.) {
+ uint32_t k = __ac_X31_hash_string(bam1_qname(b)) + g_subsam_seed;
+ if ((double)(k&0xffffff) / 0x1000000 >= g_subsam_frac) return 1;
+ }
+ if (g_rg || g_rghash) {
+ uint8_t *s = bam_aux_get(b, "RG");
+ if (s) {
+ if (g_rg) return (strcmp(g_rg, (char*)(s + 1)) == 0)? 0 : 1;
+ if (g_rghash) {
+ khint_t k = kh_get(rg, g_rghash, (char*)(s + 1));
+ return (k != kh_end(g_rghash))? 0 : 1;
+ }
+ }
+ }
+ if (g_library) {
+ const char *p = bam_get_library((bam_header_t*)h, b);
+ return (p && strcmp(p, g_library) == 0)? 0 : 1;
+ }
+ return 0;
+}
+
+static char *drop_rg(char *hdtxt, rghash_t h, int *len)
+{
+ char *p = hdtxt, *q, *r, *s;
+ kstring_t str;
+ memset(&str, 0, sizeof(kstring_t));
+ while (1) {
+ int toprint = 0;
+ q = strchr(p, '\n');
+ if (q == 0) q = p + strlen(p);
+ if (q - p < 3) break; // the line is too short; then stop
+ if (strncmp(p, "@RG\t", 4) == 0) {
+ int c;
+ khint_t k;
+ if ((r = strstr(p, "\tID:")) != 0) {
+ r += 4;
+ for (s = r; *s != '\0' && *s != '\n' && *s != '\t'; ++s);
+ c = *s; *s = '\0';
+ k = kh_get(rg, h, r);
+ *s = c;
+ if (k != kh_end(h)) toprint = 1;
+ }
+ } else toprint = 1;
+ if (toprint) {
+ kputsn(p, q - p, &str); kputc('\n', &str);
+ }
+ p = q + 1;
+ }
+ *len = str.l;
+ return str.s;
+}
+
+// callback function for bam_fetch() that prints nonskipped records