/***************************************************************************
 *   copyright           : (C) 2002 by Hendrik Sattler                     *
 *   mail                : post@hendrik-sattler.de                         *
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

//own headers
#include <charsets.h>
#include <gtincl.h>

//standard headers
#include <stdio.h>
#include <iconv.h>
#include <string.h>

#ifdef WORDS_BIGENDIAN
#define UCS2_DEF "UCS-2BE"
#else
#define UCS2_DEF "UCS-2LE"
#endif

const char* ucs2_get_iconv_charset() {
  static char* ucs2_charset = NULL;
  iconv_t cd;

  if (ucs2_charset == NULL) {
    cd = iconv_open(UCS2_DEF,UCS2_DEF);
    if (cd == (iconv_t)-1) {
      fprintf(stderr,_("%s: the iconv implementation of this system does not support %s"),_("Error"),UCS2_DEF);
      exit(EXIT_FAILURE);
    } else {
      ucs2_charset = UCS2_DEF;
    }
    iconv_close(cd);
  }
  return ucs2_charset;
}

size_t ucs2len (const ucs2char_t* input) {
  size_t retval = 0;
  if (input != NULL) while (input[retval] != 0) ++retval;
  return retval;
}

ucs2char_t* ucs2ndup(const ucs2char_t* s, size_t n) {
  ucs2char_t* retval;
  size_t i = 0;

  if (s == NULL) return NULL;
  while (s[i] != 0 && i < n) ++i;
  retval = mem_alloc((i+1)*sizeof(*retval),0);
  (void)memcpy(retval,s,i*sizeof(*s));
  retval[i] = 0;
  return retval;
}
ucs2char_t* ucs2dup(const ucs2char_t* s) {
  return ucs2ndup((ucs2char_t*)s,ucs2len(s)+1);
}
