/***************************************************************************
 *   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 <helper.h>
#include <gtincl.h>
#include "ucs4.h"

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

ucs4char_t* convert_to_internal (const char* from_code,
				 char* input,
				 size_t insize)
{
  iconv_t cd;

  ucs4char_t* outbuf;
  char* outptr;
  size_t outsize;

  if (from_code == NULL || input == NULL || insize == 0) return NULL;

  cd = iconv_open(ucs4_get_iconv_charset(),from_code);
  if (cd == (iconv_t)-1) {
    fprintf(stderr,"%s: %s\n",_("Error on text conversion"), strerror(errno));
    exit(EXIT_FAILURE);
  }

  outsize = insize*sizeof(ucs4char_t);
  outbuf  = mem_alloc(outsize+sizeof(ucs4char_t),1);
  outptr  = (char*)outbuf;

  if (iconv(cd,(ICONV_CAST)&input,&insize,&outptr,&outsize) == (size_t)-1) {
    fprintf(stderr,_("Error on text conversion from charset \"%s\" to charset \"%s\": %s\n"),
	    from_code,ucs4_get_iconv_charset(),strerror(errno));
    exit(EXIT_FAILURE);
  }
  iconv_close(cd);

  return mem_realloc(outbuf,(ucs4len(outbuf)+1)*sizeof(ucs4char_t));
}
