/**********************************************************************
 
	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	"memory_debug.h"

XL_SEXP * xl_MemoryStatistics();


void
init_MemoryStatistics(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"MemoryStatistics"),
		get_func_prim(xl_MemoryStatistics,FO_APPLICATIVE,0,1,1));
}

XL_SEXP *
xl_MemoryStatistics(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
MEM_LIST * m;
XL_SEXP * ret;
int large;
char * ptr;
L_CHAR * max;
	m = 0;
	ret = 0;
	large = 0;
	ptr = "";
	max = get_sf_attribute(sf,l_string(std_cm,"max"));
	for ( ; ; ) {
		m = get_mem_debug_list(m);
		if ( m == 0 )
			break;
		if ( m->size == 0 )
			continue;
		if ( m->size > large ) {
			ptr = "*";
			large = m->size;
		}
		else	ptr = "";
		if ( max == 0 || strcmp(ptr,"*") == 0 )
			ret = cons(
				List(n_get_string(ptr),
					n_get_string(m->file),
					get_integer(m->line,0),
					get_integer(m->size,0),
					-1),
				ret);
	}
	return reverse(ret);
}


