#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "range.h"

#define SYMS 256
#define IOBUF_SIZE 32*1024

Uint ftbl[SYMS];
char ibuf[IOBUF_SIZE];
char obuf[IOBUF_SIZE];

/* An order 0 decoder file to file demonstration */
int main (int argc, char **argv) {
	int sym;
	rc_decoder rd;
	rc_model rcm;
	FILE *fp, *ofp;
	Uint fsize, i;
	
	if (argc != 3) {
		fprintf(stderr, "Usage:\n%s infile outfile\n", argv[0]);
		exit(1);
	}
	fp = fopen(argv[1], "rb");
	ofp = fopen(argv[2], "wb");
	if (fp && ofp) {
		setvbuf(fp, ibuf, _IOFBF, IOBUF_SIZE);
		setvbuf(ofp, obuf, _IOFBF, IOBUF_SIZE);
		fsize = (Uint)getc(fp);  /* Get filesize */
		fsize |= (Uint)getc(fp) << 8;
		fsize |= (Uint)getc(fp) << 16;
		fsize |= (Uint)getc(fp) << 24;
		
		i = ModelInit (&rcm, SYMS, ftbl, NULL, 2, (Uint)1<<14, ADAPT);
		if (i != RC_OK) {
			fprintf(stderr, "Error: maxFreq or totFreq > 65536\n");
			exit(1);
		}
		StartDecode (&rd, fp, NULL, 0);
		printf("Decoding...\n");
		fflush(stdout);
		for (i = 0; i < fsize; i++) {
			sym = DecodeSymbol (&rd, &rcm);
			if (rd.error != RC_OK) break;
			fputc(sym, ofp);
		}
		
		switch (rd.error) {
			case RC_OK:
				printf("Decompressed %lu bytes to %lu bytes\n", (unsigned long)rd.passed, (unsigned long)fsize);
				fflush(stdout);
				break;
			case RC_ERROR:
				fprintf(stderr, "Decode error: Symbol outside range\n");
				break;
			case RC_IO_ERROR:
				fprintf(stderr, "Decode error: Could not input compressed data\n");
		}
	}
	fclose(fp);
	fclose(ofp);
	
	return 0;
}
