#include <getopt.h>
#include <unistd.h>
#include <ctype.h>
#include <htslib/sam.h>
static void print_usage(FILE *fp)
{
fprintf(fp, "Usage: pileup infile\n\
Shows the pileup api usage.\n");
return;
}
typedef struct plpconf {
char *inname;
samFile *infile;
sam_hdr_t *in_samhdr;
} plpconf;
int plpconstructor(void *data, const bam1_t *b, bam_pileup_cd *cd) {
return 0;
}
int plpdestructor(void *data, const bam1_t *b, bam_pileup_cd *cd) {
return 0;
}
int readdata(void *data, bam1_t *b)
{
plpconf *conf = (plpconf*)data;
if (!conf || !conf->infile) {
return -2; }
return sam_read1(conf->infile, conf->infile->bam_header, b);
}
int main(int argc, char *argv[])
{
int ret = EXIT_FAILURE;
bam1_t *bamdata = NULL;
plpconf conf = {0};
bam_plp_t plpiter = NULL;
int tid = -1, n = -1, j = 0, k = 0;
int refpos = -1;
const bam_pileup1_t *plp = NULL;
if (argc != 2) {
print_usage(stderr);
goto end;
}
conf.inname = argv[1];
if (!(bamdata = bam_init1())) {
printf("Failed to initialize bamdata\n");
goto end;
}
if (!(conf.infile = sam_open(conf.inname, "r"))) {
printf("Could not open %s\n", conf.inname);
goto end;
}
if (!(conf.in_samhdr = sam_hdr_read(conf.infile))) {
printf("Failed to read header from file!\n");
goto end;
}
if (!(plpiter = bam_plp_init(readdata, &conf))) {
printf("Failed to initialize pileup data\n");
goto end;
}
bam_plp_constructor(plpiter, plpconstructor);
bam_plp_destructor(plpiter, plpdestructor);
while ((plp = bam_plp_auto(plpiter, &tid, &refpos, &n))) {
printf("%d\t%d\t", tid+1, refpos+1);
for (j = 0; j < n; ++j) {
if (plp[j].is_del || plp[j].is_refskip) {
printf("*");
continue;
}
printf("%c", plp[j].is_head ? toupper(seq_nt16_str[bam_seqi(bam_get_seq(plp[j].b), plp[j].qpos)]) :
(plp[j].is_tail ? toupper(seq_nt16_str[bam_seqi(bam_get_seq(plp[j].b), plp[j].qpos)]) : tolower(seq_nt16_str[bam_seqi(bam_get_seq(plp[j].b), plp[j].qpos)])));
if (plp[j].indel > 0) {
printf("+%d", plp[j].indel);
for (k = 0; k < plp[j].indel; ++k) {
printf("%c", tolower(seq_nt16_str[bam_seqi(bam_get_seq(plp[j].b), plp[j].qpos + k + 1)]));
}
}
else if (plp[j].indel < 0) {
printf("%d", plp[j].indel);
for (k = 0; k < -plp[j].indel; ++k) {
printf("?");
}
}
printf(" ");
}
printf("\n");
fflush(stdout);
}
ret = EXIT_SUCCESS;
end:
if (conf.in_samhdr) {
sam_hdr_destroy(conf.in_samhdr);
}
if (conf.infile) {
sam_close(conf.infile);
}
if (bamdata) {
bam_destroy1(bamdata);
}
if (plpiter) {
bam_plp_destroy(plpiter);
}
return ret;
}