/*
Copyright 1990-2003 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

#pragma ident	"$Id$"

#include "iiimpAux.h"

#if 0
#ifdef	linux
#define USE_CSCONV
#endif
#endif /* 0 */

#if !defined(USE_ICONV) && !defined(USE_CSCONV)
#if defined(sun)
#define USE_ICONV
#else
#define USE_CSCONV
#endif
#endif

#ifdef USE_ICONV
#include <iconv.h> 
#endif

#include <locale.h>
#include <langinfo.h>
#include <strings.h>
#if !defined(USE_CSCONV)
#include <errno.h>
#endif /* !USE_CSCONV */
#if 0
#include "iiimpIM.h"
#include "iiimp.h"
#include "iiimpReq.h"
#endif

#define UTF16_STRLEN	4096

#ifdef USE_CSCONV
#include <dlfcn.h>
#include "csconv.h"
#define CSC_OPEN_LOCALE	"csconv_open_locale"
#define CSC_OPEN	"csconv_open"
#define CSC_CONV	"csconv"
#define CSC_CLOSE	"csconv_close"

typedef csconv_t	(* csc_open_locale_t)(const char *,
					      const char *, const char *);
typedef csconv_t	(* csc_open_t)(const char *, const char *);
typedef size_t		(* csc_conv_t)(csconv_t, const char **, size_t *,
				       char **, size_t *);
typedef int		(* csc_close_t)(csconv_t);

static void *			csc_handle;	
static csc_open_locale_t	csc_open_locale;
static csc_open_t		csc_open;
static csc_conv_t		csc_conv;
static csc_close_t		csc_close;

static char *current_locale = 0;
#endif

#ifdef USE_ICONV
static iconv_t i_conv1 = NULL;
static iconv_t i_conv2 = NULL;
static Bool skip_native_to_utf8_conv = False;
#endif

#ifdef USE_CSCONV
static void
dlopen_csconv()
{
      csc_handle = dlopen(CSC_PATH, RTLD_LAZY);
      if (NULL == csc_handle) {
        csc_handle = (void *)(-1);
	return;
      }

      csc_open_locale = (csc_open_locale_t)dlsym(csc_handle, CSC_OPEN_LOCALE);
      csc_open = (csc_open_t)dlsym(csc_handle, CSC_OPEN);
      csc_conv = (csc_conv_t)dlsym(csc_handle, CSC_CONV);
      csc_close = (csc_close_t)dlsym(csc_handle, CSC_CLOSE);

      if ((NULL == csc_open_locale) || (NULL == csc_open) ||
	  (NULL == csc_conv) || (NULL == csc_close)) {
        dlclose(csc_handle);
	csc_handle = (void *)(-1);
	return;
      }
}
#endif

static int
IIimpConvertToUTF16(char *from_buf, size_t from_left,
		    char **to_buf, size_t *to_left) {
  size_t src_len, dst_len;
  char *src, *dst;
#ifndef USE_CSCONV
  const char *ip;
  size_t ileft;
  char *op;
  size_t oleft;
  char buffer[UTF16_STRLEN];		/* Fix me! */
#endif /* !USE_CSCONV */
  const size_t buf_len = UTF16_STRLEN;
  size_t ret = 0;
#ifdef USE_CSCONV
  static csconv_t csconv_cd = NULL;

#endif

#ifdef USE_CSCONV
  if (current_locale == NULL){
    current_locale = (char*)strdup(setlocale(LC_CTYPE, NULL));
  }

  do {
    if (((void *)(-1) == csc_handle) ||
	((csconv_t)(-1) == csconv_cd)) {
      continue;
    }
    if (NULL == csc_handle) {
      dlopen_csconv();
      if ((void *)(-1) == csc_handle) {
	continue;
      }
    }
    if (NULL == csconv_cd) {

      csconv_cd = (csc_open_locale)(current_locale, "UTF-16", "MultiByte");
      
      if ((csconv_t)(-1) == csconv_cd) {
	continue;
      }
    }

    dst = *((char **)to_buf);

    ret = csc_conv(csconv_cd,
		   (const char **)&from_buf, (size_t*)&from_left,
		   &dst, to_left);
    return ret;
  } while (0);
#endif

#ifdef USE_ICONV
  if (i_conv1 == (iconv_t)-1 || i_conv2 == (iconv_t)-1){
    goto done;
  }

  if (i_conv1 == NULL && !skip_native_to_utf8_conv) {
    char *encoding = nl_langinfo(CODESET);
    if (!strcmp(encoding, "UTF-8")) {
      skip_native_to_utf8_conv = True;
    } else {
      if ((i_conv1 = iconv_open("UTF-8", encoding))
	  == (iconv_t)-1) {
	goto done;
      }
    }
  }

  if (i_conv2 == NULL){
    if ((i_conv2 = iconv_open("UCS-2",
			      "UTF-8")) == (iconv_t)-1)
      goto done;
  }

  if (!skip_native_to_utf8_conv) {
    ip = (const char *)from_buf;
    ileft = from_left;

    op = *((char **)to_buf);
    oleft = (size_t)(*to_left);

    while ((0 < ileft) && (0 < oleft)) {
      dst = buffer;
      dst_len = buf_len;
      ret = iconv(i_conv1, &ip, &ileft, (char**)&dst, &dst_len);
      if ((ret != 0) && (E2BIG != errno)) {
	goto done;
      }

      src = buffer;
      src_len = buf_len - dst_len;

      ret = iconv(i_conv2, (const char**)&src, (size_t*)&src_len,
		  &op, &oleft);
      if (ret != 0) goto done;
    }

    dst_len = oleft;

  } else {
    src = from_buf;
    src_len = from_left;
    dst = *to_buf;
    dst_len = *to_left;
    ret = iconv(i_conv2, (const char**)&src, (size_t*)&src_len,
		(char**)&dst, &dst_len);
  }

  if (0xFEFF == **((CARD16 **)to_buf)) {
    memmove(*to_buf, *to_buf + 2, *to_left - dst_len - 2);
    *to_left = (dst_len + 2);
  } else {
    *to_left = dst_len;
  }
done:
#endif /* USE_ICONV */
  return(ret);
}

#ifdef USE_ICONV
static iconv_t i_conv1_FromUTF16 = NULL;
static iconv_t i_conv2_FromUTF16 = NULL;
#endif

/* Used when transfering data from AUX to IM,
   do data conversion from UCS2 to EUC */
static int
IIimpConvertFromUTF16(char *from_buf, size_t from_left,
		      char **to_buf, size_t * to_left) {
  size_t src_len, dst_len;
  char *src, *dst;
#ifndef USE_CSCONV
  const char *ip;
  size_t ileft;
  char *op;
  size_t oleft;
  char buffer[UTF16_STRLEN];	/* Fix me! */
#endif /* !USE_CSCONV */
  const size_t buf_len = UTF16_STRLEN;
  size_t ret = 0;

#ifdef USE_CSCONV
  static csconv_t csconv_cd = NULL;
#endif

#ifdef USE_CSCONV
  do {
    if (((void *)(-1) == csc_handle) ||
	((csconv_t)(-1) == csconv_cd)) {
      continue;
    }
    if (NULL == csc_handle) {
      dlopen_csconv();
      if ((void *)(-1) == csc_handle) {
	continue;
      }
    }
    if (NULL == csconv_cd) {

      csconv_cd = (csc_open_locale)(current_locale, "MultiByte", "UTF-16");
      
      if ((csconv_t)(-1) == csconv_cd) {
	continue;
      }
    }

    dst = *((char **)to_buf);

    ret = csc_conv(csconv_cd,
		   (const char **)&from_buf, (size_t*)&from_left,
		   &dst, to_left);
    return ret;
  } while (0);
#endif

#ifdef USE_ICONV
  if (i_conv1_FromUTF16 == (iconv_t)-1 ||
      i_conv2_FromUTF16 == (iconv_t)-1) {
    goto done;
  }

  if (i_conv2_FromUTF16 == NULL && !skip_native_to_utf8_conv) {
    char *encoding = nl_langinfo(CODESET);
    if (!strcmp(encoding, "UTF-8")) {
      skip_native_to_utf8_conv = True;
    } else {
      if ((i_conv2_FromUTF16 = iconv_open(encoding, "UTF-8"))
	  == (iconv_t) - 1) {
	goto done;
      }
    }
  }
  if (i_conv1_FromUTF16 == NULL) {
    if ((i_conv1_FromUTF16 = iconv_open("UTF-8", "UCS-2"))
	== (iconv_t) - 1) {
      goto done;
    }
  }

  if (skip_native_to_utf8_conv) {
    src = from_buf;
    src_len = from_left;	/* don't stop at '\0' in case of ascii */
    dst = *((char **) to_buf);
    ret = iconv(i_conv1_FromUTF16, (const char**)&src, (size_t*)&src_len,
		(char**)&dst, (size_t*)to_left);
  } else {
    ip = (const char *)from_buf;
    ileft = from_left;

    op = *((char **)to_buf);
    oleft = (size_t)(*to_left);

    while ((0 < ileft) && (0 < oleft)) {
      dst = buffer;
      dst_len = buf_len;
      ret = iconv(i_conv1_FromUTF16, &ip, &ileft, (char**)&dst, &dst_len);
      if ((ret != 0) && (E2BIG != errno)) {
	goto done;
      }

      src = buffer;
      src_len = buf_len - dst_len;

      ret = iconv(i_conv2_FromUTF16, (const char**)&src, (size_t*)&src_len,
		  &op, &oleft);
      if (ret != 0) goto done;
    }

    *to_left = oleft;
  }
done:
#endif /* USE_ICONV */
  return(ret);
}

/* from iiimpAux.c */
size_t
utf16_mb(
        const char **   inbuf,
        size_t *        inbytesleft,
        char **         outbuf,
        size_t *        outbytesleft)
{
        int     r;

        r = IIimpConvertFromUTF16((char *)(*inbuf), *inbytesleft,
                                  outbuf, outbytesleft);
        return (size_t)r;
}

size_t
mb_utf16(
        const char **   inbuf,
        size_t *        inbytesleft,
        char **         outbuf,
        size_t *        outbytesleft)
{
        int     r;

        r = IIimpConvertToUTF16((char *)(*inbuf), *inbytesleft,
                                  outbuf, outbytesleft);
        return (size_t)r;
}
