/*
    iconv to be easy
    Copyright (C) 2019 Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#include <libziaint.h>

#include <ziconv.h>

#include <string.h>


int ziconv(iconv_t cd, char *inbuf, GString *outbuf){
	char *tmp, *inptr, *outptr;
	size_t sizein, sizeout, ret, oldsizein, size;
	if (!inbuf || !*inbuf) return -1;

	size = strlen(inbuf);
	tmp = g_malloc(size + 1);

	inptr = inbuf;
	sizein = size;

	while (sizein > 0){
		outptr = tmp;
		sizeout = size;
		oldsizein = sizein;

		ret = iconv(cd, &inptr, &sizein, &outptr, &sizeout);
		if (ret == (size_t)-1){
			//int err = errno;  // errno is always zero under MSVC
			//if (err != E2BIG && err != EILSEQ && err != EINVAL) return -1;
			if (sizein == oldsizein) break;
		}
		if (outptr != NULL) *outptr = '\0';
		g_string_append(outbuf, tmp);
	}
	
	g_free(tmp);
	return 0;
}
