static BAM_FILE _bamfile_open_r(SEXP filename, SEXP indexname, SEXP filemode) { BAM_FILE bfile = (BAM_FILE) Calloc(1, _BAM_FILE); bfile->file = NULL; if (0 != Rf_length(filename)) { const char *cfile = translateChar(STRING_ELT(filename, 0)); bfile->file = _bam_tryopen(cfile, CHAR(STRING_ELT(filemode, 0)), 0); if ((bfile->file->type & TYPE_BAM) != 1) { samclose(bfile->file); Free(bfile); Rf_error("'filename' is not a BAM file\n file: %s", cfile); } bfile->pos0 = bam_tell(bfile->file->x.bam); bfile->irange0 = 0; } bfile->index = NULL; if (0 != Rf_length(indexname)) { const char *cindex = translateChar(STRING_ELT(indexname, 0)); bfile->index = _bam_tryindexload(cindex); if (NULL == bfile->index) { samclose(bfile->file); Free(bfile); Rf_error("failed to open BAM index\n index: %s\n", cindex); } } bfile->iter = NULL; bfile->pbuffer = NULL; return bfile; }
SEXP bamfile_isincomplete(SEXP ext) { int ans = FALSE; BAM_FILE bfile; if (NULL != BAMFILE(ext)) { _checkext(ext, BAMFILE_TAG, "isIncomplete"); bfile = BAMFILE(ext); if (NULL != bfile && NULL != bfile->file) { /* heuristic: can we read a record? bam_seek does not * support SEEK_END */ off_t offset = bam_tell(bfile->file->x.bam); char buf; ans = bam_read(bfile->file->x.bam, &buf, 1) > 0; bam_seek(bfile->file->x.bam, offset, SEEK_SET); } } return ScalarLogical(ans); }
int32_t tmap_sam_io_read(tmap_sam_io_t *samio, tmap_sam_t *sam) { if(NULL != sam->b) { bam_destroy1(sam->b); } sam->b = bam_init1(); // check if we're past optional end bam virtual file offset if (samio->bam_end_vfo > 0) { BGZF* bgzf_fp = samio->fp->x.bam; if (bam_tell(bgzf_fp) >= samio->bam_end_vfo) { fprintf(stderr, "stopping at bam virtual file offset %lu\n", samio->bam_end_vfo); return -1; } } if(0 < samread(samio->fp, sam->b)) { char *str; int32_t i, len; // name str = bam1_qname(sam->b); len = strlen(str); tmap_sam_io_update_string(&sam->name, str, len); sam->name->s[len] = '\0'; // seq and qual len = sam->b->core.l_qseq; tmap_sam_io_update_string(&sam->seq, NULL, len); tmap_sam_io_update_string(&sam->qual, (char*)bam1_qual(sam->b), len); for(i=0;i<len;i++) { sam->seq->s[i] = bam_nt16_rev_table[bam1_seqi(bam1_seq(sam->b), i)]; sam->qual->s[i] = QUAL2CHAR(sam->qual->s[i]); } sam->seq->s[len] = sam->qual->s[len] = '\0'; // reverse compliment if necessary if((sam->b->core.flag & BAM_FREVERSE)) { tmap_sam_reverse_compliment(sam); } return 1; } return -1; }
static BAM_FILE _bamfile_open_w(SEXP file0, SEXP file1) { samfile_t *infile, *outfile; BAM_FILE bfile; if (0 == Rf_length(file1)) Rf_error("'file1' must be a character(1) path to a valid bam file"); infile = _bam_tryopen(translateChar(STRING_ELT(file1, 0)), "rb", 0); outfile = _bam_tryopen(translateChar(STRING_ELT(file0, 0)), "wb", infile->header); samclose(infile); bfile = (BAM_FILE) Calloc(1, _BAM_FILE); bfile->file = outfile; bfile->pos0 = bam_tell(bfile->file->x.bam); bfile->irange0 = 0; return bfile; }