/* lviconvwrapper_crio.c - 
 *   UTF8toSJIS / SJIStoUTF8 with gnu iconv wrapper library(*.so) for LabVIEW
 * date:  2012/04/21
 *
 * build: Makefile
 */

#include <string.h>

#include "iconv.h"
#include "lviconvwrapper.h"

int UTF8toSJIS(unsigned char *utf8str, int utf8strlen, unsigned char *sjisstr, int sjisstrlen)
{

   char *pin;
   char *pout;
   iconv_t cd;
   size_t ilen, rlen;

   if  (utf8str == NULL || sjisstr == NULL) {
        return -1;
   }

   cd = iconv_open("SJIS", "UTF-8");
   if(cd == (iconv_t)-1){
      return -1;
   }

   ilen = strlen((char*)utf8str);
   rlen = sjisstrlen - 1;
   if (ilen > rlen) {
	   return -1;
   }
   pin  = (char*)utf8str;
   pout = (char*)sjisstr;

   rlen = iconv(cd, &pin, &ilen, &pout, &rlen);
   if (rlen == -1) {

      return -1;
   }
   *pout = '\0';
   iconv_close(cd);

    return 0;
}

int SJIStoUTF8(unsigned char *sjisstr, int sjisstrlen, unsigned char *utf8str, int utf8strlen)
{
   char *pin;
   char *pout;
   iconv_t cd;
   size_t ilen, rlen;

   if  (utf8str == NULL || sjisstr == NULL) {
        return -1;
   }

   cd = iconv_open("UTF-8", "SJIS");
   if(cd == (iconv_t)-1){
      return -1;
   }

   ilen = strlen((char*)sjisstr);
   rlen = utf8strlen - 1;
   if (ilen > rlen) {
	   return -1;
   }
   pin  = (char*)sjisstr;
   pout = (char*)utf8str;

   rlen = iconv(cd, &pin, &ilen, &pout, &rlen);
   if (rlen == -1) {
      return -1;
   }
   *pout = '\0';
   iconv_close(cd);

    return 0;
}
