]> git.donarmstrong.com Git - samtools.git/blob - bam_reheader.c
make pileup work with CIGAR with I/D at the beginning or in the end
[samtools.git] / bam_reheader.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "bgzf.h"
4 #include "bam.h"
5
6 #define BUF_SIZE 0x10000
7
8 int bam_reheader(BGZF *in, const bam_header_t *h, int fd)
9 {
10         BGZF *fp;
11         bam_header_t *old;
12         int len;
13         uint8_t *buf;
14         if (in->open_mode != 'r') return -1;
15         buf = malloc(BUF_SIZE);
16         old = bam_header_read(in);
17         fp = bgzf_fdopen(fd, "w");
18         bam_header_write(fp, h);
19         if (in->block_offset < in->block_length) {
20                 bgzf_write(fp, in->uncompressed_block + in->block_offset, in->block_length - in->block_offset);
21                 bgzf_flush(fp);
22         }
23 #ifdef _USE_KNETFILE
24         while ((len = knet_read(in->x.fpr, buf, BUF_SIZE)) > 0)
25 #else
26         while (!feof(in->file) && (len = fread(buf, 1, BUF_SIZE, in->file)) > 0)
27 #endif
28                 fwrite(buf, 1, len, fp->x.fpw);
29         free(buf);
30         fp->block_offset = in->block_offset = 0;
31         bgzf_close(fp);
32         return 0;
33 }
34
35 int main_reheader(int argc, char *argv[])
36 {
37         bam_header_t *h;
38         BGZF *in;
39         if (argc != 3) {
40                 fprintf(stderr, "Usage: samtools reheader <in.header.sam> <in.bam>\n");
41                 return 1;
42         }
43         { // read the header
44                 tamFile fph = sam_open(argv[1]);
45                 if (fph == 0) {
46                         fprintf(stderr, "[%s] fail to read the header from %s.\n", __func__, argv[1]);
47                         return 1;
48                 }
49                 h = sam_header_read(fph);
50                 sam_close(fph);
51         }
52         in = strcmp(argv[2], "-")? bam_open(argv[2], "r") : bam_dopen(fileno(stdin), "r");
53         if (in == 0) {
54                 fprintf(stderr, "[%s] fail to open file %s.\n", __func__, argv[2]);
55                 return 1;
56         }
57         bam_reheader(in, h, fileno(stdout));
58         bgzf_close(in);
59         return 0;
60 }