/* Copyright 2013 Akira Ohta (akohta001@gmail.com)
    This file is part of ntch.

    The ntch is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    The ntch 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.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ntch.  If not, see <http://www.gnu.org/licenses/>.
    
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <wchar.h>
#include <iconv.h>
#include <errno.h>

#include    "utils/nt_std_t.h"


BOOL nt_conv_sjis2wc(iconv_t icd,
	const char *src, wchar_t *data, size_t data_len)
{
	char *p_src, *p_dst;
	size_t n_src, n_dst, sz;
	p_src = (char*)src;
	p_dst = (char*)data;
	n_src = strlen(src) * sizeof(char);
	n_dst = data_len;
	while(0 < n_src){
		sz = iconv(icd, &p_src, &n_src, &p_dst, &n_dst);
		if(sz == -1){
			return FALSE;
		}
	}
	*((wchar_t*)p_dst) = L'\0';
	return TRUE;
}

BOOL nt_conv_wc2sjis(iconv_t icd,
	const wchar_t *src, char *data, size_t data_len)
{
	char *p_src, *p_dst;
	size_t n_src, n_dst, sz;
	p_src = (char*)src;
	p_dst = data;
	n_src = wcslen(src) * sizeof(wchar_t);
	n_dst = data_len;
	while(0 < n_src){
		sz = iconv(icd, &p_src, &n_src, &p_dst, &n_dst);
		if(sz == -1){
			return FALSE;
		}
	}
	*p_dst = '\0';
	return TRUE;
}

BOOL nt_conv_local2sjis(iconv_t icd,
	const char *src, char *data, size_t data_len)
{
	char	*p_src, *p_dst;
	size_t  n_src,  n_dst, sz;
	p_src = (char*)src;
	p_dst = data;
	n_src = strlen(p_src);
	n_dst = data_len;
	while(0 < n_src){
		sz = iconv(icd, &p_src, &n_src, &p_dst, &n_dst);
		if(((size_t)-1) == sz){
			return FALSE;
		}
	}
	*p_dst = '\0';
	return TRUE;
}
