#include <errno.h>
#include <iconv.h>
#include <stdio.h>

main(int argc, char** argv)
{
    iconv_t cd;
    size_t inbytesleft, outbytesleft;
    char inbuf[BUFSIZ], outbuf[BUFSIZ];
    char *inptr, *outptr;
    int bytesread, inputlen;
    int rc = 0;


    cd = iconv_open(argv[2], argv[1]);
    fprintf(stderr, "iconv_open returned %d\n", cd);
    fprintf(stderr, "errno = %d\n", errno);

    if (!cd || (cd == (iconv_t)-1)) {
        exit(1);
    }

    inbytesleft = 0;

    while (bytesread = _read(0, inbuf + inbytesleft, BUFSIZ - inbytesleft)) {

        inptr = inbuf;
        outptr = outbuf;
        outbytesleft = BUFSIZ;
        inbytesleft += bytesread;
        inputlen = inbytesleft;

        errno = 0;
        rc = iconv(cd, &inptr, &inbytesleft, &outptr, &outbytesleft);
        fprintf(stderr, "iconv returned %d\n", rc);
        fprintf(stderr, "errno = %d\n", errno);

        _write(1, outbuf, BUFSIZ - outbytesleft);

        if (rc == -1) {

            if (errno == EILSEQ) { /* Illegal sequence */
                break;
            }
            else if (errno == EINVAL) { /* Truncated input */
		/* Do nothing. Should get handled on next interation. */	
            }
            else if (errno == E2BIG) { /* Output buffer too small. */
		/* Do nothing. Should get handled on next interation. */	
            }

            /* Copy any unconverted input to front of buffer. */
            memcpy(inbuf, inptr, inbytesleft);
        }

    } /* while */

    errno = 0;
    rc = iconv_close(cd);
    fprintf(stderr, "iconv_close returned %d\n", rc);
    fprintf(stderr, "errno = %d\n", errno);


    exit(rc);
}

