/* 
 * gcc libxml_614333.c  `pkg-config --cflags --libs libxml-2.0`
 */

#include <string.h>
#include <stdint.h>
#include <libxml/parser.h>
#include <iconv.h>

void errorHandler(void* ctx, const char* message, ...) {
    va_list args;
    va_start (args, message);
    va_end (args);
    printf("error: ");
    vprintf(message, args);
}

char *latin9_to_utf16(char *str) {
    size_t inbytesleft = strlen(str);
    size_t outbytesleft = inbytesleft * 2;
    char *output = malloc(outbytesleft);
    char *ret = output;
    iconv_t cd = iconv_open("UTF16BE", "LATIN9");
    iconv(cd, &str, &inbytesleft, &output, &outbytesleft);
    iconv_close(cd);
    return (char *) ret;
}

int main() {
    /* create a sax handler, and define an error method to see the error message */
    xmlSAXHandler sax;
    memset (&sax, 0, sizeof(sax));
    sax.error = errorHandler;
    xmlParserCtxtPtr parser = xmlCreatePushParserCtxt(&sax, 0, 0, 0, 0);

    char* str = "<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?><pere err=\"0\"><date type=\"ug\"><mday>30</mday><mon>3</mon><year>2010</year><hour>9</hour><min>8</min><sec>13</sec></date></pere>";
    size_t len = strlen(str);
    char* chunk = latin9_to_utf16 (str);

    /* set parser encoding to utf16 */
    xmlSwitchEncoding(parser, XML_CHAR_ENCODING_UTF16BE);
    int res = xmlParseChunk(parser, (const char*)chunk, sizeof(uint16_t) * len, 0);
    // xmlParseChunk return XML_ERR_DOCUMENT_END
    printf("result: %d\n", res); 

    return 0;
}
