/**********************************************************************
 
	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	<fcntl.h>
#include	"memory_debug.h"
#include	"xl.h"
#include	"lump.h"
#include	"pmd.h"

XL_SEXP * xl_pmd_status();

void
init_pmd_status(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"pmd-status"),
		get_func_prim(xl_pmd_status,FO_APPLICATIVE,0,2,2));
}


XL_SEXP *
get_period_format(GB_TIME * t)
{
char buf[100];
	gb_time_format(buf,t);
	return n_get_string(buf);
}

void
get_unit_system(L_CHAR ** unit,L_CHAR ** system,PMD_WORK * w)
{
L_CHAR * sys;
L_CHAR * ptr;
	sys = ll_copy_str(w->pmd_h.d.unit_path);
	for ( ptr = sys ; *ptr && *ptr != '?' ; ptr ++ );
	if ( *ptr == 0 ) {
		*unit = nl_copy_str(std_cm,"m");
		*system = sys;
		return;
	}
	else {
		*unit = ll_copy_str(ptr+1);
		*ptr = 0;
		*system = sys;
	}
}

XL_SEXP *
xl_pmd_status(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * db;
PMD_WORK w;
PMD_TEMP min;
PMD_TEMP max;
LUMP_INFO info;
XL_SEXP * ret;
L_CHAR * unit,* system;
L_CHAR * reso_unit;
	db = get_el(s,1);
	if ( get_type(db) != XLT_STRING )
		return db;
	if ( load_lump_info(&info,db->string.data) < 0 )
		return 0;
	open_db(&w,db->string.data,0,O_RDONLY);
	if ( w.err < 0 ) {
		close_db(&w);
		return 0;
	}
	get_db_status(&w,&min,&max);
	get_unit_system(&unit,&system,&w);
	close_db(&w);

	ret = List(n_get_symbol("pmd-status"),
		List(n_get_symbol("crd"),
			get_string(info.crd),
			-1),
		List(n_get_symbol("mr"),
			List(
				List(	get_floating(min.minrect.tl.x,
						unit),
					get_floating(min.minrect.tl.y,
						unit),
					-1),
				List(	get_floating(max.minrect.br.x,
						unit),
					get_floating(max.minrect.br.y,
						unit),
					-1),
				-1),
			-1),
		List(n_get_symbol("v"),
			get_floating(min.resolution,reso_c_unit_str(unit)),
			get_floating(max.resolution,reso_c_unit_str(unit)),
			-1),
		List(n_get_symbol("period"),
			get_period_format(&min.content_period_from),
			get_period_format(&max.content_period_from),
			-1),
		List(n_get_symbol("unit-system"),
			get_string(system),
			-1),
		-1);
	free_lump_info(&info);
	d_f_ree(system);
	d_f_ree(unit);
	return ret;
}


