static char rcsid[] = "$Header:gcvt.c 12.0$";
/* @(#)gcvt.c	4.1 (Berkeley) 12/21/80 */
/*
 * gcvt  - Floating output conversion to
 * minimal length string
 */
#include <ctype.h>
#define DEBUG 0 

char	*ecvt();

char *
gcvt(number, ndigit, buf)
double number;
char *buf;
{
	int sign, decpt;
	int oldndig;	/* for determining f(loat) or e(xp) print format */
	int cvtlen;	/* for checking precision returned from ecvt */
	register char *p1, *p2;
	register i;

	p1 = ecvt(number, ndigit, &decpt, &sign);
	p2 = buf;
#if DEBUG
	printf("ecvt returns %s\n",p1);
	printf("value of ndigit is %5d\n", ndigit);
	printf("value of decpt is %5d\n", decpt); 
#endif
	if (sign)
		*p2++ = '-';
       if (!isdigit(*p1)) {			/* INF, NAN() */
	    while (*p2 = *p1++) p2++;
	}
       else {
	if ((cvtlen= strlen(p1)) < ndigit)	/* < full precision from ecvt */
	     ndigit= cvtlen;	
	for (i= (ndigit<=17 ? ndigit-1 : 16),
	     oldndig= ndigit= (i<=16 ? i+1 : 17)       ; i>0 && p1[i]=='0'; i--)
		ndigit--;
	if (decpt >= 0 && decpt-oldndig > 0 
	 || decpt < -3) {			 /* use E-style */
		decpt--;
		*p2++ = *p1++;
		if ((i=1) < ndigit) {
		    *p2++ = '.';
		    do	*p2++ = *p1++;
			while (++i < ndigit);
		}
		*p2++ = 'e';
		if (decpt<0) {
			decpt = -decpt;
			*p2++ = '-';
		} else
			*p2++ = '+';
		if (decpt>99) {
		    *p2++ = decpt/100 + '0';
		    decpt = decpt%100;
		}
		*p2++ = decpt/10 + '0';
		*p2++ = decpt%10 + '0';
	} else {
		if (decpt<=0) {
			if (*p1!='0') {
				*p2++ = '0';
				*p2++ = '.';
			}
			while (decpt<0) {
				decpt++;
				*p2++ = '0';
			}
		}
		for (i=1; i<=ndigit; i++) {
			*p2++ = *p1++;
			if (i==decpt)
				*p2++ = '.';
		}
		if (ndigit<decpt) {
			while (ndigit++<decpt)
				*p2++ = '0';
			*p2++ = '.';
		}
	}
       }
	if (p2[-1]=='.')
		p2--;
	*p2 = '\0';
	return(buf);
}
