ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/bamread/bam2bed.c
Revision: 123
Committed: Mon Dec 5 22:21:21 2011 UTC (7 years, 10 months ago) by gpertea
File size: 1746 byte(s)
Log Message:
bamread files

Line User Rev File contents
1 gpertea 123 #include <stdio.h>
2     #include "bam/sam.h"
3    
4     /* callback for bam_fetch() */
5     static int fetch_func(const bam1_t *b, void *data)
6     {
7     samfile_t *fp = (samfile_t*)data;
8     uint32_t *cigar = bam1_cigar(b);
9     const bam1_core_t *c = &b->core;
10     int i, l;
11     if (c->flag&BAM_FUNMAP) return 0; /* skip unmapped reads */
12     for (i = l = 0; i < c->n_cigar; ++i) {
13     int op = cigar[i]&0xf;
14     if (op == BAM_CMATCH || op == BAM_CDEL || op == BAM_CREF_SKIP)
15     l += cigar[i]>>4;
16     }
17     printf("%s\t%d\t%d\t%s\t%d\t%c\n", fp->header->target_name[c->tid],
18     c->pos, c->pos + l, bam1_qname(b), c->qual, (c->flag&BAM_FREVERSE)? '-' : '+');
19     return 0;
20     }
21     int main(int argc, char *argv[])
22     {
23     samfile_t *fp;
24     if (argc == 1) {
25     fprintf(stderr, "Usage: bam2bed <in.bam> [region]\n");
26     return 1;
27     }
28     if ((fp = samopen(argv[1], "rb", 0)) == 0) {
29     fprintf(stderr, "bam2bed: Fail to open BAM file %s\n", argv[1]);
30     return 1;
31     }
32     if (argc == 2) { /* if a region is not specified */
33     bam1_t *b = bam_init1();
34     while (samread(fp, b) >= 0) fetch_func(b, fp);
35     bam_destroy1(b);
36     } else {
37     int ref, beg, end;
38     bam_index_t *idx;
39     if ((idx = bam_index_load(argv[1])) == 0) { /* load BAM index */
40     fprintf(stderr, "bam2bed: BAM index file is not available.\n");
41     return 1;
42     }
43     bam_parse_region(fp->header, argv[2], &ref, &beg, &end); /* parse region */
44     if (ref < 0) {
45     fprintf(stderr, "bam2bed: Invalid region %s\n", argv[2]);
46     return 1;
47     }
48     bam_fetch(fp->x.bam, idx, ref, beg, end, fp, fetch_func);
49     bam_index_destroy(idx);
50     }
51     samclose(fp);
52     return 0;
53     }