/* DEC	*RoundDecimal(pDst,pSrc1,wID)
 *
 * ARGUMENT
 *	pDst is	a pointer to the destination DEC structure.
 *	pSrc1 is a ptr to the source1 DEC structure.
 *	wID is the integer specifying location of implied decimal
 *		for the	conversion.
 *
 * DESCRIPTION
 *	Adjusts	the number in pSrc1 (if	necessary) while copying it to
 *   pDst adjusting pDst to wID	number of decimal places. If pDst is null
 *   on	entry, tries to	first create a pDst, then the conversion.  When	the
 *   number of decimal places decreases, the result is rounded off.
 *
 * SIDE	EFFECTS
 *	pSrc1 remains unchanged	and pDst is undefined on error.
 *
 * RETURNS
 *	Returns	a pointer to the pDst structure	unless error,
 *   in	which case it returns a	NULL(a C false). On error, the error
 *   is	in wGMError, unless an error was already there.
 *
 * POSSIBLE ERROR CODES
 *
 *	GM_NULLPOINTER
 *	GM_INVALIDID
 *	GM_OVERFLOW
 *	GM_UNDERFLOW
 *
 * AUTHOR
 * Jared Levy	5/28/87
 *   Copyright (C) 1987-1990 Greenleaf Software	Inc.  All rights reserved.
 *
 * MODIFICATIONS
 *
*/

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

DEC	*RoundDecimal(pDst,pSrc1,wID)
DEC	*pDst, *pSrc1;
int	wID;
{
	int	i;

	_MacStart(GM_DROUND);
	_MacInVarD(pSrc1);
	_MacOutVarD(pDst);

	if (wID<GM_MINID||wID>GM_MAXID)	 {
		_MacErr(GM_INVALIDID);
		_MacRet(GM_NULL);
	}

  /* Added by Guy */
  if (wID >= pDst->dc.id)
  {
    if (pDst != pSrc1)
      _MacDCopy(pDst,pSrc1);
		_MacRet(pDst);
  }

  if(_MacIsDecZ(pSrc1)) {
		_MacDZero(pDst);
		pDst->dc.id = wID;
		_MacRet(pDst);
	}

	i = _ScaleDec80Bit(pDst, pSrc1,	wID);

/*  check if number can	fit into 64 bits (no shifting allowed) */
	if (!((pDst->dc.msd == 0)  && (pDst->dc.sl[3] <	 32768L)))
		i = GM_OVERFLOW;

	if (i == GM_OVERFLOW)  {
		_MacErr(GM_OVERFLOW);
		_MacRet(GM_NULL);
		}

	if (_MacIsDecZ(pDst))
		_MacErr(GM_UNDERFLOW);

	_MacRet(pDst);
}