
/**************************************************************
    lzhuf.c
**************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include <huffman.h>


char BufferA[8192];
char BufferB[8192];

int main(int argc, char *argv[])
{
    char  *s;
	 int   rc;
	 ULONG ulTextSize;
    FILE  *infile, *outfile;

    if (argc != 4) {
	printf("'lzhuf c file1 file2' compresses file1 into file2.\n"
	       "'lzhuf e file2 file1' expands file2 into file1.\n"
	       "'lzhuf t file2 file1' expands file2 into file1 via buffers.\n");
	return EXIT_FAILURE;
    }
    if ((s = argv[1], s[1] || strpbrk(s, "CETcet") == NULL)
     || (s = argv[2], (infile = fopen(s, "rb")) == NULL)
     || (s = argv[3], (outfile = fopen(s, "wb")) == NULL)) {
	printf("??? %s\n", s);
	return EXIT_FAILURE;
    }
    if (toupper(*argv[1]) == 'C')
	rc = CompressFileToFile(infile, outfile);
    if (toupper(*argv[1]) == 'E')
	rc = ExpandFileToFile(infile, outfile);

    if (toupper(*argv[1]) == 'T'){
	fseek((FILE *)infile, 0L, 2);
	ulTextSize = ftell(infile);
	rewind((FILE *)infile);
	fprintf(stderr,"Input File Size %12ld\n", ulTextSize);
	rc = CompressFileToBuffer(infile, BufferA, (ULONG)sizeof(BufferA),
					    (PULONG)&ulTextSize);
	fprintf(stderr,"Compressed Buffer Size %12ld\n", ulTextSize);
	ulTextSize = BufferA[0];
	ulTextSize <<= 8;
	ulTextSize |= BufferA[1];
	ulTextSize <<= 8;
	ulTextSize |= BufferA[2];
	ulTextSize <<= 8;
	ulTextSize |= BufferA[3];
	rc = ExpandBufferToBuffer(BufferA, ulTextSize,
					    BufferB, (ULONG)sizeof(BufferB),
					    (PULONG)&ulTextSize);
	fprintf(stderr,"Expanded Buffer Size %12ld\n", ulTextSize);
	rc = CompressBufferToBuffer(BufferB, ulTextSize,
					      BufferA, (ULONG)sizeof(BufferA),
					      (PULONG)&ulTextSize);
	fprintf(stderr,"ReCompressed Buffer Size %12ld\n", ulTextSize);
	ulTextSize = BufferA[0];
	ulTextSize <<= 8;
	ulTextSize |= BufferA[1];
	ulTextSize <<= 8;
	ulTextSize |= BufferA[2];
	ulTextSize <<= 8;
	ulTextSize |= BufferA[3];
	rc = ExpandBufferToFile(BufferA, ulTextSize, outfile);
		  }

    fclose(infile);
    fclose(outfile);

    return EXIT_SUCCESS;
}
