#define	STRICT
#include	<windows.h>
#include	"convert.h"

HINSTANCE	hKctrlDll = 0 ;
extern	DWORD	DllVersion ;
BOOL	(*InitKanjiControls)( void ) ;
void	(*ReleaseKanjiControls)( void ) ;
void	(*unicode2sjis)( LPCTSTR src, BYTE *dst, DWORD max ) ;
void	(*sjis2unicode)( const BYTE *src, LPTSTR dst, DWORD max ) ;
DWORD	(*GetKVersion)( void ) ;

void
init_convert( void )
{
	/* フォントDLLを読み込む */
	hKctrlDll = LoadLibrary( TEXT("KCTRL") ) ;
	if ( hKctrlDll ) {
		InitKanjiControls = (BOOL(*)(void))GetProcAddress( hKctrlDll, TEXT("InitKanjiControls") ) ;
		ReleaseKanjiControls = (void(*)(void))GetProcAddress( hKctrlDll, TEXT("ReleaseKanjiControls") ) ;
		if ( InitKanjiControls && ReleaseKanjiControls ) {
			if ( !(*InitKanjiControls)() ) {
				release_convert() ;
				return ;
			}
		}
		unicode2sjis = (void(*)(LPCTSTR,LPBYTE,DWORD))GetProcAddress( hKctrlDll, TEXT("unicode2sjis") ) ;
		sjis2unicode = (void(*)(const BYTE*,LPTSTR,DWORD))GetProcAddress( hKctrlDll, TEXT("sjis2unicode") ) ;
		GetKVersion = (DWORD(*)(void))GetProcAddress( hKctrlDll, TEXT("GetKVersion") ) ;
		if ( unicode2sjis && sjis2unicode && GetKVersion ) {
			DllVersion = GetKVersion() ;
		} else {
			release_convert() ;
		}
	}
}

void
release_convert( void )
{
	if ( hKctrlDll ) {
		(*ReleaseKanjiControls)() ;
		FreeLibrary( hKctrlDll ) ;
		hKctrlDll = 0 ;
	}
}

void
SjisToUnicode( const BYTE *src, LPTSTR dst, DWORD dstsize )
{
	if ( hKctrlDll ) {
		(*sjis2unicode)( src, dst, dstsize ) ;
	} else {
		mbstowcs( dst, src, strlen( src ) + 1 ) ;
	}
}

void
UnicodeToSjis( LPCTSTR src, LPBYTE dst, DWORD dstsize )
{
	if ( hKctrlDll ) {
		(*unicode2sjis)( src, dst, dstsize ) ;
	} else {
		wcstombs( dst, src, dstsize ) ;
	}
}
