/**********************************************************************
 
	Copyright (C) 2004 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	<fcntl.h>
#include	"xlerror.h"
#include	"xl.h"
#include	"addrdb_jp.h"
#include	"xl_addrdb.h"

XL_SEXP * xl_AddrdbConvert();

void
init_AddrdbConvert(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"AddrdbConvert"),
		get_func_prim(xl_AddrdbConvert, FO_NORMAL, 0, 2, 2));
}

XL_SEXP *
xl_AddrdbConvert(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
ADDRDB* db;
int ret;
L_CHAR *input_dir,*output_dir;
int address_columun;
L_CHAR *input_file_encoding;
	
	input_file_encoding = l_string(std_cm, "Shift_JIS");
	address_columun = 0;
	input_dir=output_dir=0;

	for ( ; sf ; sf = sf->next ) {
		if ( l_strcmp(sf->name,l_string(std_cm,"input_dir")) == 0 ) {
			input_dir = sf->data;
		}
		else if ( l_strcmp(sf->name,l_string(std_cm,"output_dir")) == 0 ) {
			output_dir = sf->data;
		}
		else if ( l_strcmp(sf->name,l_string(std_cm,"input_encoding")) == 0 ) {
			input_file_encoding = sf->data;
		}
		else if ( l_strcmp(sf->name,l_string(std_cm,"address_columun")) == 0 ) {
			address_columun = atoi(n_string(std_cm, sf->name));
		}
	}
	
	if(input_dir==0||output_dir==0){
		goto attribute_not_found;
	}

	db = addrdb_get_db_from_symbol(env, get_el(s,1));
	if(db == NULL)
		goto type_missmatch;
	
	ret = addrdb_convert_csv_batch(
			db, 
			n_string(std_cm, input_dir), 
			n_string(std_cm, output_dir), 
			n_string(std_cm, input_file_encoding),
			address_columun);
	
	if ( db == 0 )
		goto cannot_open;
	
	return get_integer(ret,0);
attribute_not_found:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_UNDEF_SYMBOL,
		l_string(std_cm,"AddrdbConvert"),
		n_get_string("attribute not found"));
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"AddrdbConvert"),
		n_get_string("type missmatch"));
cannot_open:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_OPEN_FILE,
		l_string(std_cm,"AddrdbConvert"),
		n_get_string("cannot open the file"));

}

