// lviconvwrapper_linux.c - 
//   UTF8toSJIS / SJIStoUTF8 with gnu iconv wrapper library(*.so) for LabVIEW
// date:  2012/04/21
//
// build: gcc -fPIC -shared lviconvwrapper_linux.c -o liblviconvwrapper.so

#include <string.h>

#include <iconv.h>
#include "lviconvwrapper.h"

int UTF8toSJIS(unsigned char *utf8str, int utf8strlen, unsigned char *sjisstr, int sjisstrlen)
{
//   char const *pin;
   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){
      // perror("iconv open");
      return -1;
   }

   ilen = strlen((char*)utf8str);
   rlen = sjisstrlen - 1;
   if (ilen > rlen) {
      // perror("iconv");
	   return -1;
   }
   pin  = (char*)utf8str; // important!! 
   pout = (char*)sjisstr; // important!!

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

    return 0;
}

int SJIStoUTF8(unsigned char *sjisstr, int sjisstrlen, unsigned char *utf8str, int utf8strlen)
{
//   char const *pin;
   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){
      // perror("iconv open");
      return -1;
   }

   ilen = strlen((char*)sjisstr);
   rlen = utf8strlen - 1;
   if (ilen > rlen) {
      // perror("iconv");
	   return -1;
   }
   pin  = (char*)sjisstr; // important!! 
   pout = (char*)utf8str; // important!!

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

    return 0;
}
