/**********************************************************************
 
	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	"xlerror.h"
#include	"xl.h"
#include	"xl_zlib.h"
#include	"memory_debug.h"

XL_SEXP * xl_Compress();


void
init_Compress(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"Compress"),
		get_func_prim(xl_Compress,FO_APPLICATIVE,0,2,4));
}


XL_SEXP *
xl_zlib_compress(
	XL_SYM_FIELD * sf,XL_SEXP * bin)
{
void * ret_buf;
int ret_size;
XL_SEXP * ret;
L_CHAR * opt;
int _opt;
	opt = get_sf_attribute(sf,l_string(std_cm,"option"));
	if ( opt == 0 )
		_opt = 9;
	else	_opt = atoi(n_string(std_cm,opt));
	ret_buf = zlib_compress(
		&ret_size,
		bin->raw.data,
		bin->raw.size,
		_opt);
	if ( ret_buf == 0 )
		return 0;
	ret = get_raw(ret_buf,ret_size);
	d_f_ree(ret_buf);
	return ret;
}

XL_SEXP *
xl_Compress(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,
	XL_SYM_FIELD * sf)
{
L_CHAR * mode;
char * _mode;
XL_SEXP * bin;
	mode = get_sf_attribute(sf,
			l_string(std_cm,"mode"));
	if ( mode == 0 )
		_mode = "zlib";
	else	_mode = n_string(std_cm,mode);
	bin = get_el(s,1);
	if ( get_type(bin) != XLT_RAW )
		goto type_missmatch;
	if ( strcmp(_mode,"zlib") ) {
		return xl_zlib_compress(sf,bin);
	}
	else {
		goto unsupport;
	}
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"Compress"),
		0);
unsupport:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_UNSUPPORT_MODE,
		l_string(std_cm,"Compress"),
		n_get_string("Unsupport Compress Mode"));
}


