/* char	*ConvDecimalToAsciiCommaRound(s, x, n)
 *
 * ARGUMENT
 *   DEC	*x;
 *   char	*s;
 *   int	n;
 *
 *
 * 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.  A comma will be printed
 *  every three	digits left of the decimal point.
 *
 * SIDE	EFFECTS
 *	None.
 *
 * RETURNS
 *	A string pointer if successful,	NULL otherwise.
 *
 * POSSIBLE ERROR CODES
 *
 *	GM_NULLPOINTER
 *	GM_NULLSTRING
 *	GM_CNVRW
 *	GM_INVALIDID
 *
 * 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*	ConvDecimalToAsciiCommaRound( s, x, n)
char	*s;
DEC	*x;
int n;		/*  0...18 */
{
	DEC	a,*pa=&a;
	int	i, wDigits, wOut;
	char	t[GM_IMAXID * 2];

	_MacStart(GM_DTOACR);

	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);
	}

	if (n<GM_MINID)	 {
		_MacErr(GM_INVALIDID);
		n = GM_MINID;
	}

	if (n>GM_MAXID)	 {
		_MacErr(GM_INVALIDID);
		n = GM_MAXID;
	}

	wDigits	= wOut = 0;

	/* preserve source integrity */
	_MacDCopy(pa,x);
	if(_MacIsDecN(pa)) {
		++wOut;
	}

	if (n <	pa->dc.id)  {
		if (wfGMRound)
			_DivUnsArrByPwrOf10(pa->dc.sl, 5, pa->dc.id - n);
		else
			_DivUnsArrByPwrOf10Trunc(pa->dc.sl, 5, pa->dc.id - n);
		pa->dc.id = n;
		if (_MacIsDecZ(pa))
			wOut = 0;
		_MacErr(GM_CNVRW);
		}

/* 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++;
			}
	}

	if (pa->dc.id <	n)  {
		if (pa->dc.id == 0)  {
			s[wOut]	= '.';
			wOut++;
			}
		for (i=pa->dc.id; i<n; i++)  {
			s[wOut]	= '0';
			wOut++;
			}
		}

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

	s[wOut]	= '\0';


	_MacRet	(s);
}