Commit bb50e02d by Rudolf

Add throwaways as first 3 bits

This allows the last byte to be interpreted correctly, by not allowing the
cursor to move further than the max bits to read.
parent 5664a457
Showing with 63 additions and 1 deletions
......@@ -7,6 +7,8 @@
#include "header.h"
#include "print_helper.h"
#define HUFFMAN_START 3
void free_tree(struct tree *parent)
{
while (parent != NULL) {
......@@ -41,12 +43,54 @@ char *read_text(FILE *file, long size)
return buf;
}
int insert_throwaways(FILE *file, unsigned char throwaways)
{
long filepos = ftell(file);
unsigned char firstbyte;
fseek(file, 0, SEEK_SET);
fread(&firstbyte, sizeof(firstbyte), 1, file);
throwaways &= 0x7;
firstbyte |= (throwaways << 5);
printb(firstbyte);
fseek(file, 0, SEEK_SET);
fwrite(&firstbyte, sizeof(firstbyte), 1, file);
fseek(file, filepos, SEEK_SET);
return 0;
}
unsigned char read_throwaways(FILE *file)
{
long filepos = ftell(file);
unsigned char firstbyte;
fseek(file, 0, SEEK_SET);
fread(&firstbyte, sizeof(firstbyte), 1, file);
firstbyte >>= 5;
firstbyte &= 0x7;
fseek(file, filepos, SEEK_SET);
return firstbyte;
}
int encode_file(FILE *in, FILE *out)
{
struct tree *tree;
struct BIT_BUFFER bitbuf;
bb_init(&bitbuf, out);
/* Make room for throwaways right now. */
bitbuf.pos += HUFFMAN_START;
long size = get_file_size(in);
fseek(in, 0, SEEK_SET);
......@@ -77,6 +121,8 @@ int decode_file(FILE *in, FILE *out)
struct BIT_BUFFER bitbuf;
bb_init(&bitbuf, in);
bitbuf.pos += HUFFMAN_START;
fseek(in, 0, SEEK_SET);
decode_header(&bitbuf, tree);
......@@ -131,7 +177,7 @@ int main(int argc, char *argv[])
return -1;
}
FILE *output = fopen(outfile, "w");
FILE *output = fopen(outfile, "w+");
if (!output) {
fprintf(stderr, "Failed to open output file\n");
fclose(input);
......
#include <stdlib.h>
#include "huffman.h"
#include "tree.h"
/* The character set we support */
......@@ -136,6 +137,8 @@ int encode_tree(struct BIT_BUFFER *bitbuf, struct tree *parent, char *buf,
write_entry(bitbuf, parent, buf[i]);
}
insert_throwaways(bitbuf->fp, 8 - bitbuf->pos);
return 0;
}
......@@ -143,8 +146,16 @@ static int read_entries(struct BIT_BUFFER *bitbuf, FILE *out,
struct tree *parent)
{
int *bit;
int bitsread = 0;
int totalbits = get_file_size(bitbuf->fp) * 8;
int huffmanbits = totalbits - read_throwaways(bitbuf->fp);
printf("Total bits to parse %d\n", huffmanbits);
struct tree *leaf = parent;
while ((bit = bb_read(bitbuf, 1)) != NULL) {
if (*bit == 1) {
fwrite(&leaf->right->ch, 1, 1, out);
leaf->right->freq++;
......@@ -158,6 +169,11 @@ static int read_entries(struct BIT_BUFFER *bitbuf, FILE *out,
}
}
free(bit);
if (bitsread == huffmanbits)
break;
bitsread++;
}
return 0;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment