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