/**********************************************************************
 
	Copyright (C) 2004 
	Hirohisa MORI <joshua@nichibun.ac.jp>
	Tomohito Nakajima <nakajima@zeta.co.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	"memory_debug.h"
#include	"xlerror.h"
#include	"xl.h"
#include	"utils.h"

XL_SEXP * xl_Rm();

void
init_Rm(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"Rm"),
		get_func_prim(xl_Rm, FO_APPLICATIVE, 0, 2, 2));
}

XL_SEXP *
xl_Rm(XLISP_ENV * env, XL_SEXP * s, XLISP_ENV * arg_env, XL_SYM_FIELD * sf)
{
XL_SEXP * file;
char *path;
int flag;
	
	flag = 0;
	file = get_el(s,1);
	for ( ; sf ; sf = sf->next ) {
		if ( l_strcmp(sf->name,l_string(std_cm,"flag")) ){
			if ( l_strcmp(sf->data, l_string(std_cm,"file")) == 0 ){
				flag |= RMF_FILE;
			}
			else if(l_strcmp(sf->data, l_string(std_cm,"rec")) == 0 ){
				flag |= RMF_REC;
			}
			else if(l_strcmp(sf->data, l_string(std_cm,"dir")) == 0 ){
				flag |= RMF_DIR;
			}
		}
	}
	if(flag == 0){
		flag = RMF_FILE;
	}
	if(get_type(file) != XLT_STRING){
		goto type_missmatch;
	}
	path = n_string(std_cm, file->string.data);
	path = change_delim_str(path);
	if(!is_safe_as_filename(path)){
		goto error_filename;
	}
	u_rm(path, flag);
	d_f_ree(path);
	return 0;

type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"Rm"),
		List(n_get_string("filename"),
			n_get_string("is type missmatch"),
			-1));
error_filename:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_INV_FORMAT,
		l_string(std_cm,"Rm"),
		List(n_get_string("filename"),
			n_get_string("is invalid"),
			-1));

}

