/* Multibyte Character Functions.
   Copyright (C) 1998 Free Software Foundation, Inc.

This file is part of GCC.

GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version.

GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING.  If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.  */

/* Note regarding cross compilation:

   In general, translation of multibyte characters to wide characters can
   only work in a native compiler since the translation function (mbtowc)
   needs to know about both the source and target character encoding.  However,
   this particular implementation for JIS, SJIS and EUCJP source characters
   will work for any compiler with a newlib target.  Other targets may also
   work provided that their wchar_t implementation is 2 bytes and the encoding
   leaves the source character values unchanged (except for removing the
   state shifting markers).  */

#include "config.h"
#ifdef MULTIBYTE_CHARS
#include "system.h"
#include "mbchar.h"
#include <locale.h>

/* mbchar fix */
#include <iconv.h>
typedef enum {ASC, ROME, JIS_78, JIS_83} JIS_ESC_STATE;
/*
typedef enum {ESCAPE, DOLLAR, BRACKET, AT, B, J, NUL, JIS_CHAR, OTHER,
	      JIS_C_NUM} JIS_CHAR_TYPE;

typedef enum {ASCII, A_ESC, A_ESC_DL, JIS, JIS_1, JIS_2, J_ESC, J_ESC_BR,
	     J2_ESC, J2_ESC_BR, INV, JIS_S_NUM} JIS_STATE; 

typedef enum {COPYA, COPYJ, COPYJ2, MAKE_A, MAKE_J, NOOP,
	      EMPTY, ERROR} JIS_ACTION;
*/

/* State/action tables for processing JIS encoding:

   Where possible, switches to JIS are grouped with proceding JIS characters
   and switches to ASCII are grouped with preceding JIS characters.
   Thus, maximum returned length is:
     2 (switch to JIS) + 2 (JIS characters) + 2 (switch back to ASCII) = 6.  */

/* mbchar fix */
/*static const JIS_STATE JIS_state_table[JIS_S_NUM][JIS_C_NUM] = {*/
/*            ESCAPE DOLLAR   BRACKET   AT     B      J     NUL JIS_CHAR OTH*/
/*ASCII   { A_ESC, ASCII,   ASCII,    ASCII, ASCII, ASCII, ASCII,ASCII,ASCII},*/
/*A_ESC   { ASCII, A_ESC_DL,ASCII,    ASCII, ASCII, ASCII, ASCII,ASCII,ASCII},*/
/*A_ESC_DL{ ASCII, ASCII,   ASCII,    JIS,   JIS,   ASCII, ASCII,ASCII,ASCII},*/
/*JIS     { J_ESC, JIS_1,   JIS_1,    JIS_1, JIS_1, JIS_1, INV,  JIS_1,INV },*/
/*JIS_1   { INV,   JIS_2,   JIS_2,    JIS_2, JIS_2, JIS_2, INV,  JIS_2,INV },*/
/*JIS_2   { J2_ESC,JIS,     JIS,      JIS,   JIS,   JIS,   INV,  JIS,  JIS },*/
/*J_ESC   { INV,   INV,     J_ESC_BR, INV,   INV,   INV,   INV,  INV,  INV },*/
/*J_ESC_BR{ INV,   INV,     INV,      INV,   ASCII, ASCII, INV,  INV,  INV },*/
/*J2_ESC  { INV,   INV,     J2_ESC_BR,INV,   INV,   INV,   INV,  INV,  INV },*/
/*J2_ESC_BR{INV,   INV,     INV,      INV,   ASCII, ASCII, INV,  INV,  INV },
};*/

/*static const JIS_ACTION JIS_action_table[JIS_S_NUM][JIS_C_NUM] = {*/
/*            ESCAPE DOLLAR BRACKET AT     B       J      NUL  JIS_CHAR OTH */
/*ASCII    {NOOP,  COPYA, COPYA, COPYA,  COPYA,  COPYA, EMPTY, COPYA, COPYA},*/
/*A_ESC    {COPYA, NOOP,  COPYA, COPYA,  COPYA,  COPYA, COPYA, COPYA, COPYA},*/
/*A_ESC_DL {COPYA, COPYA, COPYA, MAKE_J, MAKE_J, COPYA, COPYA, COPYA, COPYA},*/
/*JIS      {NOOP,  NOOP,  NOOP,  NOOP,   NOOP,   NOOP,  ERROR, NOOP,  ERROR},*/
/*JIS_1    {ERROR, NOOP,  NOOP,  NOOP,   NOOP,   NOOP,  ERROR, NOOP,  ERROR},*/
/*JIS_2    {NOOP,  COPYJ2,COPYJ2,COPYJ2, COPYJ2, COPYJ2,ERROR, COPYJ2,COPYJ2},*/
/*J_ESC    {ERROR, ERROR, NOOP,  ERROR,  ERROR,  ERROR, ERROR, ERROR, ERROR},*/
/*J_ESC_BR {ERROR, ERROR, ERROR, ERROR,  NOOP,   NOOP,  ERROR, ERROR, ERROR},*/
/*J2_ESC   {ERROR, ERROR, NOOP,  ERROR,  ERROR,  ERROR, ERROR, ERROR, ERROR},*/
/*J2_ESC_BR{ERROR, ERROR, ERROR, ERROR,  COPYJ,  COPYJ, ERROR, ERROR, ERROR},
};*/

/* mbchar fix */
static JIS_ESC_STATE esc_state = ASC;

const char *literal_codeset = "C-EUCJP";

/* Store into *PWC (if PWC is not null) the wide character
   corresponding to the multibyte character at the start of the
   buffer S of size N.  Return the number of bytes in the multibyte
   character.  Return -1 if the bytes do not form a valid character,
   or 0 if S is null or points to a null byte.

   This function behaves like the Standard C function mbtowc, except
   it treats locale names of the form "C-..." specially.  */

int
local_mbtowc (pwc, s, n)
     wchar_t *pwc;
     const char *s;
     size_t n;
{
/* mbchar fix */
/*  static JIS_STATE save_state = ASCII;
  JIS_STATE curr_state = save_state;*/
  const unsigned char *t = (const unsigned char *) s;

  if (s != NULL && n == 0)
    return -1;

  if (literal_codeset == NULL || strlen (literal_codeset) <= 1)
    /* This must be the "C" locale or unknown locale -- fall thru */
    ;
  else if (! strcmp (literal_codeset, "C-SJIS"))
    {
      int char1;
      if (s == NULL)
	/* Not state-dependent.  */
        return 0;

      char1 = *t;
      if (ISSJIS1 (char1))
        {
          int char2 = t[1];

          if (n <= 1)
            return -1;

          if (ISSJIS2 (char2))
            {
	      if (pwc != NULL)
		*pwc = (((wchar_t) *t) << 8) + (wchar_t) (*(t + 1));
              return 2;
            }

	  return -1;
        }

      if (pwc != NULL)
	*pwc = (wchar_t) *t;

      if (*t == '\0')
	return 0;

      return 1;
    }
  else if (! strcmp (literal_codeset, "C-EUCJP"))
    {
      int char1;

      if (s == NULL)
	/* Not state-dependent.  */
        return 0;

      char1 = *t;
      if (ISEUCJP (char1))
        {
          int char2 = t[1];     

          if (n <= 1)
            return -1;

          if (ISEUCJP (char2))
            {
	      if (pwc != NULL)
		*pwc = (((wchar_t) *t) << 8) + (wchar_t) (*(t + 1));
              return 2;
            }

	  return -1;
        }

      if (pwc != NULL)
	*pwc = (wchar_t) *t;

      if (*t == '\0')
	return 0;

      return 1;
    }
  else if (! strcmp (literal_codeset, "C-JIS"))
    {
/* mbchar fix */
      unsigned int ch;

      if (s == NULL)
	{
	  esc_state = ASC;

	  /* Not state-dependent.  */
	  return 0;
	}

      for (ch = 0; ch + 2 < n; ch += 3)
	{
	  if (t[ch] == JIS_ESC_CHAR)
	    {
	      if (t[ch + 1] == '(')
		{
		  if (t[ch + 2] == 'B')
		    esc_state = ASC;
		  else
		  if (t[ch + 2] == 'J')
		    esc_state = ROME;
		  else
		    {
		      esc_state = ASC;
		      return -1;
		    }
		}
	      else
	      if (t[ch + 1] == '$')
		{
		  if (t[ch + 2] == '@')
		    esc_state = JIS_78;
		  else
		  if (t[ch + 2] == 'B')
		    esc_state = JIS_83;
		  else
		    {
		      esc_state = ASC;
		      return -1;
		    }
		}
	      else
		{
		  esc_state = ASC;
		  return -1;
		}
	    }
	  else
	    break;
	}

      if (t[ch] == '\0')
	{
	  if (pwc != NULL)
	    *pwc = (wchar_t) t[ch];

	  return ch;
	}

      switch (esc_state)
	{
	  case ASC:
	  case ROME:
	    if (ch >= n)
	      return -1;

	    if (pwc != NULL)
	      *pwc = (wchar_t) t[ch];

	    return ch + 1;

	  case JIS_78:
	  case JIS_83:
	    if (ch + 1 >= n)
	      return -1;

	    if (pwc != NULL)
	      *pwc = (((wchar_t) t[ch]) << 8) + (wchar_t) t[ch + 1];

	    return ch + 2;

	  default:
	    return -1;
	}
    }
               
/* mbchar fix */
/*#ifdef CROSS_COMPILE*/
  if (s == NULL)
    /* Not state-dependent.  */
    return 0;

  if (pwc != NULL)
    *pwc = (wchar_t) *t;
  return 1;
/*#else*/

  /* This must be the "C" locale or unknown locale.  */
/*  return mbtowc (pwc, s, n);*/
/*#endif*/
}

/* Return the number of bytes in the multibyte character at the start
   of the buffer S of size N.  Return -1 if the bytes do not form a
   valid character, or 0 if S is null or points to a null byte.

   This function behaves like the Standard C function mblen, except
   it treats locale names of the form "C-..." specially.  */

int
local_mblen (s, n)
     const char *s;
     size_t n;
{
  return local_mbtowc (NULL, s, n);
}

/* Return the maximum mumber of bytes in a multibyte character.

   This function returns the same value as the Standard C macro MB_CUR_MAX,
   except it treats locale names of the form "C-..." specially.  */

int
local_mb_cur_max ()
{
  if (literal_codeset == NULL || strlen (literal_codeset) <= 1)
    ;
  else if (! strcmp (literal_codeset, "C-SJIS"))
    return 2;
  else if (! strcmp (literal_codeset, "C-EUCJP"))
    return 2;
  else if (! strcmp (literal_codeset, "C-JIS"))
    return 8; /* 3 + 2 + 3 */

#ifdef CROSS_COMPILE
  return 1;
#else
  if (MB_CUR_MAX > 0)
    return MB_CUR_MAX;

  return 1; /* default */
#endif
}
/* mbchar fix */
/* なんちゃってWideCharをもとに戻す
   返値は書き込んだバイト数
*/
int
local_wctomb (str, wc)
     char *str;
     unsigned int wc;
{
  unsigned char *s = (unsigned char *) str;
  int  rt = 0;
  static JIS_ESC_STATE esc_save_state = ASC;

  if (literal_codeset == NULL || strlen (literal_codeset) <= 1)
    ;
  else
  if (! strcmp (literal_codeset, "C-JIS"))
    {
      if (esc_state != esc_save_state)
	{
	  esc_save_state = esc_state;
	  *s++ = JIS_ESC_CHAR; ++rt;
	  switch (esc_state)
	    {
	      case ASC:
		*s++ = '('; ++rt;
		*s++ = 'B'; ++rt;
		break;
	      case ROME:
		*s++ = '('; ++rt;
		*s++ = 'J'; ++rt;
		break;
	      case JIS_78:
		*s++ = '$'; ++rt;
		*s++ = '@'; ++rt;
		break;
	      case JIS_83:
		*s++ = '$'; ++rt;
		*s++ = 'B'; ++rt;
		break;
	      default:
		return 0;
	    }
	}
    }

  if (wc > 0xFF)
    {
      *s       = (wc & 0xFF00) >> 8; ++rt;
      *(s + 1) =  wc & 0x00FF;       ++rt;
    }
  else
    {
      *s = wc; ++rt;
    }

  return rt;
}

/* なんちゃってWideCharをShift-JISに変換
   返値は書き込んだバイト数
*/
int
local_wctosjis (str, wc)
     char *str;
     unsigned int wc;
{
  unsigned char *ustr = (unsigned char *) str;
  unsigned char s[5];
  char *pt = str;
  const char *ps = (const char *) s;
  size_t st = 2;
  size_t ss;

  iconv_t cd;

  if (wc <= 0xFF)
    {
      *str = wc;
      return 1;
    }

  if (literal_codeset == NULL || strlen (literal_codeset) <= 1)
    ;
# ifdef __linux__
  else
  if (! strcmp (literal_codeset, "C-SJIS"))
    {
      ss = 2;
      cd = iconv_open("EUCJP","SHIFT_JIS");
      if (cd == (iconv_t) -1) return 0;

      s[0] = (wc & 0xFF00) >> 8;
      s[1] =  wc & 0x00FF;
      iconv(cd,&ps,&ss,&pt,&st);
      iconv_close(cd);
      return 2;
    }
# endif
# ifndef __linux__
  else
  if (! strcmp (literal_codeset, "C-EUCJP"))
    {
      ss = 2;
      cd = iconv_open("SHIFT_JIS","EUCJP");
      if (cd == (iconv_t) -1) return 0;

      s[0] = (wc & 0xFF00) >> 8;
      s[1] =  wc & 0x00FF;
      iconv(cd,&ps,&ss,&pt,&st);
      iconv_close(cd);
      return 2;
    }
# endif
  else
  if (! strcmp (literal_codeset, "C-JIS"))
    {
      ss = 5;
# ifndef __linux__
      cd = iconv_open("SHIFT_JIS","ISO-2022-JP");
# else
      cd = iconv_open("EUCJP","ISO-2022-JP");
# endif
      if (cd == (iconv_t) -1) return 0;

      s[0] = JIS_ESC_CHAR;
      switch (esc_state)
	{
	  case ASC:
	    s[1] = '(';
	    s[2] = 'B';
	    break;
	  case ROME:
	    s[1] = '(';
	    s[2] = 'J';
	    break;
	  case JIS_78:
	    s[1] = '$';
	    s[2] = '@';
	    break;
	  case JIS_83:
	    s[1] = '$';
	    s[2] = 'B';
	    break;
	  default:
	    return 0;
	}
      s[3] = (wc & 0xFF00) >> 8;
      s[4] =  wc & 0x00FF;
      iconv(cd,&ps,&ss,&pt,&st);
      iconv_close(cd);
      return 2;
    }

  *ustr       = (wc & 0xFF00) >> 8;
  *(ustr + 1) =  wc & 0x00FF;
  return 2;
}

/* なんちゃってWideCharをロケール設定されたコードに変換 */
int
local_wctonative (str, wc)
     char *str;
     unsigned int wc;
{
  return wctomb(str, (wchar_t) local_wctouni (wc));
}

/* なんちゃってWideCharをUCS-2に変換
   変換されたものが返値で渡される
*/
unsigned int
local_wctouni (wc)
     unsigned int wc;
{
  unsigned char t[2];
  char s[5];
  char *pt = (char *) t;
  const char *ps = s;
  size_t st = 2;
  size_t ss;

  iconv_t cd;

  if (wc <= 0xFF)
    {
      return wc;
    }

  if (literal_codeset == NULL || strlen (literal_codeset) <= 1)
    return wc;
  else
  if (! strcmp (literal_codeset, "C-SJIS"))
    {
      ss = 2;
      cd = iconv_open("UCS-2","SHIFT_JIS");
      if (cd == (iconv_t) -1) return wc;

      s[0] = (wc & 0xFF00) >> 8;
      s[1] =  wc & 0x00FF;
    }
  else
  if (! strcmp (literal_codeset, "C-EUCJP"))
    {
      ss = 2;
      cd = iconv_open("UCS-2","EUCJP");
      if (cd == (iconv_t) -1) return wc;

      s[0] = (wc & 0xFF00) >> 8;
      s[1] =  wc & 0x00FF;
    }
  else
  if (! strcmp (literal_codeset, "C-JIS"))
    {
      ss = 5;
      cd = iconv_open("UCS-2","ISO-2022-JP");
      if (cd == (iconv_t) -1) return wc;

      s[0] = JIS_ESC_CHAR;
      switch (esc_state)
	{
	  case ASC:
	    s[1] = '(';
	    s[2] = 'B';
	    break;
	  case ROME:
	    s[1] = '(';
	    s[2] = 'J';
	    break;
	  case JIS_78:
	    s[1] = '$';
	    s[2] = '@';
	    break;
	  case JIS_83:
	    s[1] = '$';
	    s[2] = 'B';
	    break;
	  default:
	    return wc;
	}
      s[3] = (wc & 0xFF00) >> 8;
      s[4] =  wc & 0x00FF;
    }
  else
    {
      return wc;
    }

  iconv(cd,&ps,&ss,&pt,&st);
  iconv_close(cd);

  return (((unsigned int) t[0]) << 8) + ((unsigned int) t[1]);
}

/* 渡された文字列を literal_codeset に従って
   ロケール設定されたコードに変換
*/
void
local_mbstonative (str, src)
     char *str;
     const char *src;
{
  iconv_t cd = (iconv_t) -1;
  size_t ss = strlen (src) + 1;
  size_t st = ss * 2;
  const char *s = src;
  char *t = alloca (st);
  unsigned char *ut = (unsigned char *) t;
  const wchar_t *wcs = alloca (sizeof (wchar_t) * ss);
  wchar_t *pwc = (wchar_t *) wcs;

  if (literal_codeset == NULL || strlen (literal_codeset) <= 1)
    {
      strcpy(str,src);
      return ;
    }
  else
  if (! strcmp (literal_codeset, "C-SJIS"))
    cd = iconv_open("UCS-2","SHIFT_JIS");
  else
  if (! strcmp (literal_codeset, "C-EUCJP"))
    cd = iconv_open("UCS-2","EUC-JP");
  else
  if (! strcmp (literal_codeset, "C-JIS"))
    cd = iconv_open("UCS-2","ISO-2022-JP");

  if (cd == (iconv_t) -1) 
    {
      strcpy(str,src);
      return ;
    }

  iconv(cd,&s,&st,&t,&st);
  iconv_close(cd);

  while ((*ut != 0) || (*(ut+1) != 0))
    {
      *pwc++ = (((unsigned int) *ut) << 8) + ((unsigned int) (*(ut+1)));
      ut += 2;
    }

  *pwc = 0;

  wcstombs(str, wcs, (strlen (src) + 1) * 2);
}

#else  /* MULTIBYTE_CHARS */
extern int dummy;  /* silence 'ANSI C forbids an empty source file' warning */
#endif /* MULTIBYTE_CHARS */
