+#include "knetfile.h"
+
+#define PACKAGE_VERSION "0.2.5 (r1005)"
+
+#define error(...) { fprintf(stderr,__VA_ARGS__); return -1; }
+
+int reheader_file(const char *header, const char *file, int meta)
+{
+ BGZF *fp = bgzf_open(file,"r");
+ if (bgzf_read_block(fp) != 0 || !fp->block_length)
+ return -1;
+
+ char *buffer = fp->uncompressed_block;
+ int skip_until = 0;
+
+ if ( buffer[0]==meta )
+ {
+ skip_until = 1;
+
+ // Skip the header
+ while (1)
+ {
+ if ( buffer[skip_until]=='\n' )
+ {
+ skip_until++;
+ if ( skip_until>=fp->block_length )
+ {
+ if (bgzf_read_block(fp) != 0 || !fp->block_length)
+ error("no body?\n");
+ skip_until = 0;
+ }
+ // The header has finished
+ if ( buffer[skip_until]!=meta ) break;
+ }
+ skip_until++;
+ if ( skip_until>=fp->block_length )
+ {
+ if (bgzf_read_block(fp) != 0 || !fp->block_length)
+ error("no body?\n");
+ skip_until = 0;
+ }
+ }
+ }
+
+ FILE *fh = fopen(header,"r");
+ if ( !fh )
+ error("%s: %s", header,strerror(errno));
+ int page_size = getpagesize();
+ char *buf = valloc(page_size);
+ BGZF *bgzf_out = bgzf_dopen(fileno(stdout), "w");
+ ssize_t nread;
+ while ( (nread=fread(buf,1,page_size-1,fh))>0 )
+ {
+ if ( nread<page_size-1 && buf[nread-1]!='\n' )
+ buf[nread++] = '\n';
+ if (bgzf_write(bgzf_out, buf, nread) < 0) error("Error: %d\n",bgzf_out->errcode);
+ }
+ fclose(fh);
+
+ if ( fp->block_length - skip_until > 0 )
+ {
+ if (bgzf_write(bgzf_out, buffer+skip_until, fp->block_length-skip_until) < 0)
+ error("Error: %d\n",fp->errcode);
+ }
+ if (bgzf_flush(bgzf_out) < 0)
+ error("Error: %d\n",bgzf_out->errcode);
+
+ while (1)
+ {
+#ifdef _USE_KNETFILE
+ nread = knet_read(fp->fp, buf, page_size);
+#else
+ nread = fread(buf, 1, page_size, fp->fp);
+#endif
+ if ( nread<=0 )
+ break;
+
+ int count = fwrite(buf, 1, nread, bgzf_out->fp);
+ if (count != nread)
+ error("Write failed, wrote %d instead of %d bytes.\n", count,(int)nread);
+ }
+
+ if (bgzf_close(bgzf_out) < 0)
+ error("Error: %d\n",bgzf_out->errcode);
+
+ return 0;
+}