#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <iconv.h>
#include "utfchar.h"
  
int 
_utfchar_concat(UTFCHAR *dest, UTFCHAR *str1, UTFCHAR *str2)
{
      int i;
      for (i = 0; *str1; i++) {
         *dest++ = *str1++;
      }
      for (i = 0; *str2; i++) {
         *dest++ = *str2++;
      }
      *dest = 0;
      return i;
}

UTFCHAR *
_utfchar_dup (UTFCHAR *src)
{
  UTFCHAR *new_utfchar;
  int n_len;
  n_len = _utfchar_length (src);
  if (n_len == 0)
    return NULL;
  new_utfchar = (UTFCHAR *) calloc (n_len + 1, sizeof (UTFCHAR ));
  _utfchar_copy (new_utfchar, src);
  return new_utfchar;
}

int
_utfchar_copy(UTFCHAR * dest, UTFCHAR * original)
{
	int i;
	if (dest == NULL || original == NULL)
		return -1;
	for (i = 0; *original; i++) {
		*dest++ = *original++;
	}
	*dest = 0;
	return i;
}
                                                                                                  
int
_utfchar_length(UTFCHAR * p)
{
      int i;
		assert (p != NULL);
		if (p == NULL)
			return 0;
      for (i = 0; *p; i++)
         p++;
      return i;
}

int
_utfchar_comp (UTFCHAR *s1, UTFCHAR *s2)
{
  UTFCHAR *p1, *p2;
  
  p1 = s1, p2 = s2;
  
  while (*p1 && *p2){
    if (*p1 > *p2)
      return 1;
    else if (*p1 < *p2)
      return -1;
    p1++, p2++;
  }
  if (!*p1 && *p2)
    return -1;
  if (!*p2 && *p1)
    return 1;
  return 0;
}

void
_utfchar_print (UTFCHAR *utf_string)
{
  int len;
  char from_buffer[100], to_buffer[100];
  int  from_i = 0, to_i = 0;
  char *f_ptr, *t_ptr;
  iconv_t cd;
  size_t ret;

  len = _utfchar_length (utf_string);
  
  memset (from_buffer, 0, 100); memset (to_buffer, 0, 100);
  memcpy (from_buffer, utf_string, sizeof (UTFCHAR) * (len + 1));
  
  f_ptr = from_buffer, t_ptr = to_buffer;
  from_i = len * sizeof (UTFCHAR) , to_i = 100;
  
  cd = iconv_open ("EUC-KR", "UTF16");
  if (cd == (iconv_t) -1) {
    fprintf (stderr, "_utfchar_print error: iconv_open error,"
	     "returning..\n");
    return;
  }
  ret = iconv (cd, &f_ptr, &from_i, &t_ptr, &to_i);
  if (ret == (size_t) -1){
    fprintf (stderr, "_utfchar_print error: iconv error,"
	     "returning...\n");
    return;
  }
  fprintf (stdout, "%s", to_buffer);
  iconv_close (cd);
  return;
}

