/* gcvt.c (emx+gcc) -- Copyright (c) 1994 by Eberhard Mattes */

#include <sys/emx.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>

char *gcvt (double x, int digits, char *buffer)
{
  char str[DIG+2], *dst;
  const char *src;
  int xp, i;

  dst = buffer;

  /* Handle trivial cases first.  The empty string is produced if
     DIGITS is less than one. */

  if (digits < 1)
    {
      *dst = 0;
      return (buffer);
    }

  /* Handle special cases. */

  src = _cvt_nan (_fxam (x));
  if (src != NULL)
    {
      strcpy (dst, src);
      return (buffer);
    }

  /* "0" is produced if X is zero (the code below doesn't work if X is
     zero). */

  if (x == 0.0)
    {
      *dst++ = '0';
      *dst = 0;
      return (buffer);
    }

  /* Make the number positive. */

  if (x < 0)
    {
      x = -x;
      *dst++ = '-';
    }

  /* Compute a string of digits and an exponent for the number. */

  xp = _cvt_float_decimal (x, str);
  _cvt_round (str, &xp, digits, DIG);
  _cvt_remove_zeros (str, 1);

  /* Decide whether to use fixed or exponential format. */

  if (xp < 0 || xp >= digits)
    {
      /* Exponential format: #.####e+## */

      *dst++ = str[0];
      if (str[1] != 0)
        *dst++ = '.';
      for (src = str+1; *src != 0; ++src)
        *dst++ = *src;
      *dst++ = 'e';
      if (xp < 0)
        {
          *dst++ = '-';
          xp = -xp;
        }
      else
        *dst++ = '+';

      /* Use at least two digits for the exponent. */

      if (xp < 10)
        *dst++ = '0';
      _itoa (xp, dst, 10);
    }
  else
    {
      /* Fixed format: ####.#### */

      /* Take digits from the string. */

      for (i = 0; str[i] != 0; ++i)
        {
          if (i == xp + 1)
            *dst++ = '.';
          *dst++ = str[i];
        }

      /* Append zeros until the exponent is correct. */

      for (; i <= xp; ++i)
        *dst++ = '0';

      *dst = 0;
    }
  return (buffer);
}
