/* wcstombs.c (emx+gcc) -- Copyright (c) 1994-1996 by Eberhard Mattes */

#include <stdlib.h>
#include <ctype.h>
#include <emx/locale.h>

size_t wcstombs (char *s, const wchar_t *pwcs, size_t n)
{
  size_t result;
  wchar_t wc;
  int shift, i;

  shift = 0; result = 0;
  switch (_cur_mbyte.mode)
    {
    case _MB_8BITS:
      while (n != 0 && *pwcs != 0)
        {
          wc = *pwcs++;
          if (wc > 255)         /* wchar_t is unsigned */
            return (size_t)-1;
          s[result++] = (char)wc;
          --n;
        }
      break;

    default:
      while (n != 0 && *pwcs != 0)
        {
          i = _wctomb (s + result, *pwcs++, n, &shift);
          if (i < 1)
            return (size_t)-1;
          result += i; n -= i;
        }
      break;
    }

  /* ANSI X3.159-1989, 4.10.8.2: "Otherwise, the wcstombs function
     returns the number of bytes modified, not including a terminating
     null character, if any." */

  if (n != 0)
    s[result] = 0;
  return result;
}
