1 #include <stdlib.h> //EXIT_FAILURE
5 #include <search.h> //hsearch
15 // callback for bam_fetch()
16 static int fetch_func(const bam1_t *b, void *data)
18 bam_plbuf_t *buf = (bam_plbuf_t*)data;
19 bam_plbuf_push(b, buf);
22 // callback for bam_plbuf_init()
23 static int pileup_func(uint32_t tid, uint32_t pos, int n, const bam_pileup1_t *pl, void *data)
25 tmpstruct_t *tmp = (tmpstruct_t*)data;
26 if ((int)pos >= tmp->beg && (int)pos < tmp->end)
27 printf("%s\t%d\t%d\n", tmp->in->header->target_name[tid], pos + 1, n);
38 int main (int argc
, char *argv
[]) {
40 fprintf(stderr
,"Usage: %s <in.sam> <snp.lst> <outprefix>\n",argv
[0]);
43 samfile_t
*samIn
= samopen(argv
[1], "r", NULL
);
45 fprintf(stderr
, "Fail to open SAM file %s\n", argv
[1]);
48 bam_header_t
*samHeader
=samIn
->header
;
49 ChrNum
= samHeader
->n_targets
;
52 hData_t
*hData
= malloc(ChrNum
* sizeof(hData_t
));
54 fprintf(stderr
, "[x]malloc failed\n");
57 for (int32_t i
=0;i
<ChrNum
;++i
) {
58 printf("[%0*d] %21s -> %9u bp\n",(int)(1+log10(ChrNum
)),1+i
,samHeader
->target_name
[i
],samHeader
->target_len
[i
]);
59 hItem
.key
= samHeader
->target_name
[i
];
60 hData
[i
].ChrLen
= samHeader
->target_len
[i
];
61 hData
[i
].pBitArray
= calloc(1, BITNSLOTS(samHeader
->target_len
[i
]) );
62 hItem
.data
= &hData
[i
];
63 phItem
= hsearch(hItem
, ENTER
);
64 /* there should be no failures */
66 fprintf(stderr
, "[x]hash entry failed\n");
72 if (argc == 2) { // if a region is not specified
73 sampileup(samIn, -1, pileup_func, &tmp);
78 idx = bam_index_load(argv[1]); // load BAM index
80 fprintf(stderr, "BAM indexing file is not available.\n");
83 bam_parse_region(samIn->header, argv[2], &ref,
84 &tmp.beg, &tmp.end); // parse the region
86 fprintf(stderr, "Invalid region %s\n", argv[2]);
89 buf = bam_plbuf_init(pileup_func, &tmp); // initialize pileup
90 bam_fetch(samIn->x.bam, idx, ref, tmp.beg, tmp.end, buf, fetch_func);
91 bam_plbuf_push(0, buf); // finalize pileup
92 bam_index_destroy(idx);
93 bam_plbuf_destroy(buf);
97 for (int32_t i
=0;i
<ChrNum
;++i
) {
98 free(hData
[i
].pBitArray
);