/* char	*ConvDecimalToAsciiComma( s, x)
 *
 * ARGUMENT
 *   DEC	*x;
 *   char	*s;
 *
 *
 * DESCRIPTION
 *	Converts a DEC structure to an ascii string.  A	'-' will be printed
 *  for	negative numbers, but a	'+' sign will never be printed.	 A decimal
 *  point will be printed whenever the implied decimal is positive.  Trailing
 *  zeroes after the decimal point will	be printed.  Commas will be included
 *  if the number's absolute value is >= 1000.	The number of digits past
 *  the	decimal	point of the string will be the	same as	the implied decimal
 *  of the DEC.
 *	Possible error:	 the string not	being large enough
 *
 * SIDE	EFFECTS
 *	THE DESTINATION	char string MUST BE LONG ENOUGH	FOR ALL	THE DIGITS
 *  PLUS ANY SIGN, THE DECIMAL POINT AND THE TERMINATING NULL.
 *
 * RETURNS
 *	A string pointer if successful,	NULL otherwise.
 *
 * POSSIBLE ERROR CODES
 *
 *	GM_NULLPOINTER
 *	GM_NULLSTRING
 *
 * AUTHOR
 *   Jared Levy		Feb 1, 1987
 *   Copyright (C) 1987-1990 Greenleaf Software	Inc.  All rights reserved.
 *
 * MODIFICATIONS
 *
 */

#include <stdio.h>
#include <string.h>
#include "gmsystem.h"

char*	ConvDecimalToAsciiComma( s, x )
DEC	*x;
char	*s;

{
	int	i, wDigits, wOut;
	DEC	a,*pa=&a;
	char	t[GM_IMAXID * 2];

	_MacStart(GM_DTOAC);

	if(!s)	{
		_MacErr(GM_NULLSTRING);
		_MacRet(NULL);
	}

	if (!x)	 {
		strcpy(s, "(null)");
		_MacErr(GM_NULLPOINTER);
		_MacRet	(NULL);
	}

	if (_MacBad(x))	 {
		strcpy(s, "(null)");
		_MacErr(GM_INIT);
		_MacRet	(NULL);
	}

	wDigits	= wOut = 0;
	_MacDCopy(pa,x);	/* can't change	source field */

	if(_MacIsDecN(pa)) {
		++wOut;
	}

/* calculate wDigits */
	while(!(_MacIsDecZ(pa))) {
		i = (int) _DivUnsArrByUns(pa->dc.sl,10,5);
		t[wDigits] = (char) (i + 0x30);
		wDigits++;
	}

/* precede by zeroes if	necessary */
	for (; wDigits <= pa->dc.id; wDigits++)
		t[wDigits] = '0';

/* add minus sign */
	if (wOut!=0)
		s[0] = '-';


/* copy	wDigits	into string */
	for (wDigits--;	wDigits	>= 0; wDigits--) {
		if (wDigits == pa->dc.id - 1) {
			s[wOut]	= '.';
			wOut++;
		}

		s[wOut]	= t[wDigits];
		wOut++;

		if ((wDigits > pa->dc.id) &&
			((wDigits - pa->dc.id) % 3 == 0))  {
			s[wOut]	= ',';
			wOut++;
			}
	}

/* a # in the format string forces a decimal point */
	if (wfFlagNumber && x->dc.id==0)   {
		s[wOut]	= '.';
		wOut++;
	}

	s[wOut]	= '\0';
	_MacRet	(s);
}