/* int	ConvDecimalToInt(x)
 *
 * ARGUMENT
 *	DEC	*x;
 *
 * DESCRIPTION
 *	Converts a DEC to an integer.
 *
 * SIDE	EFFECTS
 *	None.
 *
 * RETURNS
 *	The integer if the conversion is successful, and the error code
 * otherwise.
 *
 * POSSIBLE ERROR CODES
 *
 *	GM_NULLPOINTER
 *	GM_CNVRE
 *	GM_CNVRW
 *
 * AUTHOR
 *  Jared Levy	Feb. 9,	1987
 *   Copyright (C) 1987-1990 Greenleaf Software	Inc.  All rights reserved.
 *
 * MODIFICATIONS
 *
 */

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

int	ConvDecimalToInt(x)
DEC	*x;
{
	DEC	temp;
	DEC	*pt, dn, *n=&dn;
	int	i;
	mbool	wfIsNeg;
	short	s;

	_MacStart(GM_DTOI);
	/* check for null pointer */
	_MacInVar(x, 0);

	_MacDCopy(n, x);

/*
 * The following three lines of	code shouldn't be separated.  I	ran into
 * a problem with Zortech v2.06.  If the _ScaleDec80Bit	is called right
 * after executing _MacIsDecN, the 0 in	the parameter list sometimes
 * gets	changed	to a -1.  This is bad.	Expect Zortech to fix it someday,
 * but since I only had	to change the order of execution of these three
 * lines, no need to change.  Same problem is found in DTOL.C.
 */

	wfIsNeg	= _MacIsDecN(n);
	pt = &temp;
	(void) _ScaleDec80Bit(pt, n, 0);	/* convert to integer */


/* |x| <= 32767	*/
	if ((pt->dc.sl[1] == 0)	&& (pt->dc.sl[0]< 32768L)
		&& (pt->dc.sl[2] == 0)
		&& (pt->dc.sl[3] == 0) && (pt->dc.msd == 0)) {
			i = (int) (pt->dc.sl[0]);
			if (CompareDecimal(pt, n)!=0)
				_MacErr(GM_CNVRW);
			if(wfIsNeg)
				{_MacRet(-i);}
			else
				_MacRet	(i);
			}

/* check for -32768 */
	if ((pt->dc.sl[0] == 32768L) &&	(wfIsNeg)
		&& (pt->dc.sl[1] == 0) && (pt->dc.sl[2]	== 0)
		&& (pt->dc.sl[3] == 0) && (pt->dc.msd == 0)) {
			if (CompareDecimal(pt, n)!=0)
				_MacErr(GM_CNVRW);
			s = (short) -32768L;
			_MacRet((int) s);
	    }
/* overflow */
	_MacErr(GM_CNVRE);
	_MacRet(0);
}