/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/



#include	<stdlib.h>
#include	"zlib.h"
#include	"xl_zlib.h"
#include	"memory_debug.h"

void *zlib_compress(
	int *compressedSize,
	void *sourceMemory,
	int sourceSize,
	int opt)
{
	unsigned char *compressed;

    *compressedSize = sourceSize + sourceSize/1000 + 12;
    compressed = (unsigned char*)d_alloc(*compressedSize);
    if( Z_OK != compress2( compressed,
        (unsigned long*)compressedSize,
        (unsigned char*)(sourceMemory),
        sourceSize,
        opt )){
        d_f_ree(compressed);
        compressed = 0;
        *compressedSize = 0;
    }

    return compressed;
}

void *
zlib_uncompress(
	int *uncompress_len,
	void * data,
	int length)
{
void * ret;
int ret_len;
int er;
	ret_len = length;
	ret = d_alloc(length);
	for ( ; ; ) {
		er = uncompress(
			ret,
			(unsigned long*)&ret_len,
			data,
			length);
		switch ( er ) {
		case 0:
			*uncompress_len = ret_len;
			return ret;
		case Z_BUF_ERROR:
			ret_len *= 2;
			ret = d_re_alloc(ret,ret_len);
			continue;
		default:
			d_f_ree(ret);
			return 0;
		}
	}
}

/*
int main(int argc, char* argv[])
{
	void * uncompressed;
	char *psz = "aaabbbcccdddeee";
	int compressedLen;
	int uncompressedlen;
	int len;
	void *compressed;
	len = strlen(psz)+1;

	printf("psz len = %i\n",len);
	compressed = zlib_compress(&compressedLen,
		psz,len);
	if ( compressed )
		printf("ok\n");
	printf("size %i\n",compressedLen);
	uncompressed = zlib_uncompress(&uncompressedlen,
			compressed,compressedLen);
	printf("- %i %s %s %i %i\n",
	      	psz,
		uncompressed,
		uncompressedlen,
	      	strcmp(psz,uncompressed));
	return 0;
}
*/

