#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define INCLUDE_HUFFSTUFF 
#include <huffman.h>

#define EOF -1

SHORT far pascal CompressBufferToBuffer(PCHAR pInput, ULONG ulInSize, 
                                        PCHAR pOutput, ULONG ulOutSize,
										  PULONG pulOutSize)
{
    SHORT rc;
	 struct _HuffStuff * pHS;

    pHS = StartHuff();
	 if (pHS == NULL)
	     return(HUFFMAN_MEMORY_ERROR);
    pHS->sType = HUFFMAN_BUFFER_TO_BUFFER;
    pHS->pInput = (PVOID)pInput;
    pHS->pOutput = (PVOID)pOutput;
	 pHS->fGetNextChar = GetNextBufferChar;
	 pHS->fPutNextChar = PutNextBufferChar;
	 pHS->ulMaxInput = ulInSize;
	 pHS->ulMaxOutput = ulOutSize - 4;

    pHS->textsize = ulInSize;
    *((PCHAR)pHS->pOutput) = (UCHAR)((pHS->textsize & 0xff000000L) >> 24);
    *((PCHAR)pHS->pOutput+1) = (UCHAR)((pHS->textsize & 0xff0000L) >> 16);
    *((PCHAR)pHS->pOutput+2) = (UCHAR)((pHS->textsize & 0xff00) >> 8);
    *((PCHAR)pHS->pOutput+3) = (UCHAR)(pHS->textsize & 0xff);
	 (PCHAR)pHS->pOutput += 4;
    if (pHS->textsize == 0)
	     return(HUFFMAN_FILE_LENGTH_ERROR);

	 rc = Compress(pHS);

	 *pulOutSize  = ulOutSize - pHS->ulMaxOutput;

	 EndHuff(pHS);
	 return(rc);
}


SHORT far pascal ExpandBufferToBuffer(PCHAR pInput, ULONG ulInSize, 
                                      PCHAR pOutput, ULONG ulOutSize,
										PULONG pulOutSize)
{
    SHORT rc;
	 struct _HuffStuff * pHS;

    pHS = StartHuff();
	 if (pHS == NULL)
	     return(HUFFMAN_MEMORY_ERROR);
    pHS->sType = HUFFMAN_BUFFER_TO_BUFFER;
    pHS->pInput = (PVOID)pInput;
    pHS->pOutput = (PVOID)pOutput;
	 pHS->fGetNextChar = GetNextBufferChar;
	 pHS->fPutNextChar = PutNextBufferChar;
	 pHS->ulMaxInput = ulInSize;
	 pHS->ulMaxOutput = ulOutSize;

    if (pHS->ulMaxInput < 4)
	     return(HUFFMAN_FILE_LENGTH_ERROR);
    pHS->textsize = *((PCHAR)pHS->pInput);
    pHS->textsize <<= 8;
    pHS->textsize |= *((PCHAR)pHS->pInput+1);
    pHS->textsize <<= 8;
    pHS->textsize |= *((PCHAR)pHS->pInput+2);
    pHS->textsize <<= 8;
    pHS->textsize |= *((PCHAR)pHS->pInput+3);
    (PCHAR)pHS->pInput += 4;
	 pHS->ulMaxInput -= 4;
    if (pHS->textsize == 0)
	     return(HUFFMAN_FILE_LENGTH_ERROR);

    rc = Expand(pHS);

	 *pulOutSize = pHS->textsize;

	 EndHuff(pHS);

	 return(rc);
}


SHORT GetNextBufferChar(struct _HuffStuff * pHS)
{
UCHAR c;

	 if (!pHS->ulMaxInput)
	     return(EOF);
    c = *(PCHAR)pHS->pInput;
    (PCHAR)pHS->pInput += 1;
	 pHS->ulMaxInput--;
    return(c);

}

SHORT PutNextBufferChar(struct _HuffStuff * pHS, USHORT c)
{

	 if (!pHS->ulMaxOutput)
	     return(EOF);
    *(PCHAR)(pHS->pOutput) = (UCHAR)c;
    (PCHAR)pHS->pOutput += 1;
	 pHS->ulMaxOutput--;
    return(1);

}

