#include "wm.h"

extern void init_socket_properties ();

BOOL WINAPI
DllMain (HINSTANCE hinstDLL,	// DLL モジュールのハンドル
	 DWORD fdwReason,	// 関数を呼び出す理由
	 LPVOID lpvReserved	// 予約済み
  )
{
  switch (fdwReason)
    {
    case DLL_PROCESS_ATTACH:
      // スレッド関連通知は不要
      DisableThreadLibraryCalls (hinstDLL);
      init_socket_properties ();
    }
  return TRUE;
}

void
to_unicode (const char *utf8, _TCHAR * buff)
{
  unsigned int buffpos = 0;
  unsigned int bytepos = 0;
  unsigned int utf8len = strlen (utf8);
  unsigned int bufflen = MAX_PATH + 1;
  while (bytepos < utf8len)
    {
      unsigned int b, b2, b3;
      if (buffpos + 1 >= bufflen)
	{
	  break;
	}
      b = utf8[bytepos++];
      if ((b & 0x80) == 0)
	{
	  buff[buffpos] = (_TCHAR) b;
	}
      else if ((b & 0xe0) == 0xc0)
	{
	  b2 = utf8[bytepos++];
	  buff[buffpos] = (_TCHAR) (((b & 0x1f) << 6) | (b2 & 0x3f));
	}
      else if ((b & 0xf0) == 0xe0)
	{
	  b2 = utf8[bytepos++];
	  b3 = utf8[bytepos++];
	  buff[buffpos] =
	    (_TCHAR) (((b & 0x0f) << 12) | ((b2 & 0x3f) << 6) | (b3 & 0x3f));
	}
      buffpos++;
    }
  if (buffpos < bufflen)
    {
      buff[buffpos] = _T ('\0');
    }
}

void
to_utf8 (const _TCHAR * buff, char *utf8)
{
  unsigned int buffpos = 0;
  unsigned int bytepos = 0;
  _TCHAR c;
  while ((c = buff[buffpos++]) != _T ('\0'))
    {
      if (c >= 0x0001 && c <= 0x007f)
	{
	  utf8[bytepos++] = (char) c;
	}
      else if (c == 0x0000 || (c >= 0x0080 && c <= 0x07ff))
	{
	  utf8[bytepos++] = 0xc0 | ((c >> 6) & 0x3f);
	  utf8[bytepos++] = 0x80 | (c & 0x3f);
	}
      else
	{
	  utf8[bytepos++] = 0xe0 | ((c >> 12) & 0x0f);
	  utf8[bytepos++] = 0x80 | ((c >> 6) & 0x3f);
	  utf8[bytepos++] = 0x80 | (c & 0x3f);
	}
    }
  utf8[bytepos] = '\0';
}
