Compress binary packages with xz.
[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                 fwrite(buf, 1, len, fp->x.fpw);
26 #else
27         while (!feof(in->file) && (len = fread(buf, 1, BUF_SIZE, in->file)) > 0)
28                 fwrite(buf, 1, len, fp->file);
29 #endif
30         free(buf);
31         fp->block_offset = in->block_offset = 0;
32         bgzf_close(fp);
33         return 0;
34 }
35
36 int main_reheader(int argc, char *argv[])
37 {
38         bam_header_t *h;
39         BGZF *in;
40         if (argc != 3) {
41                 fprintf(stderr, "Usage: samtools reheader <in.header.sam> <in.bam>\n");
42                 return 1;
43         }
44         { // read the header
45                 tamFile fph = sam_open(argv[1]);
46                 if (fph == 0) {
47                         fprintf(stderr, "[%s] fail to read the header from %s.\n", __func__, argv[1]);
48                         return 1;
49                 }
50                 h = sam_header_read(fph);
51                 sam_close(fph);
52         }
53         in = strcmp(argv[2], "-")? bam_open(argv[2], "r") : bam_dopen(fileno(stdin), "r");
54         if (in == 0) {
55                 fprintf(stderr, "[%s] fail to open file %s.\n", __func__, argv[2]);
56                 return 1;
57         }
58         bam_reheader(in, h, fileno(stdout));
59         bgzf_close(in);
60         return 0;
61 }