1 /****************************************************************
2  *
3  * The author of this software is David M. Gay.
4  *
5  * Copyright (c) 1991, 2006 by AT&T.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose without fee is hereby granted, provided that this entire notice
9  * is included in all copies of any software which is or includes a copy
10  * or modification of this software and in all copies of the supporting
11  * documentation for such software.
12  *
13  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
14  * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR AT&T MAKES ANY
15  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
16  * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
17  *
18  ***************************************************************/
19 
20 /* Please send bug reports to
21 	David M. Gay
22 	AT&T Bell Laboratories, Room 2C-463
23 	600 Mountain Avenue
24 	Murray Hill, NJ 07974-2070
25 	U.S.A.
26 	dmg@research.att.com or research!dmg
27  */
28 
29 #include <string.h>
30 #include <stdlib.h>
31 #include "mprec.h"
32 #include <stdlib.h>
33 
34 static int
35 _DEFUN (quorem,
36 	(b, S),
37 	_Jv_Bigint * b _AND _Jv_Bigint * S)
38 {
39   int n;
40   long borrow, y;
41   unsigned long carry, q, ys;
42   unsigned long *bx, *bxe, *sx, *sxe;
43 #ifdef Pack_32
44   long z;
45   unsigned long si, zs;
46 #endif
47 
48   n = S->_wds;
49 #ifdef DEBUG
50   /*debug*/ if (b->_wds > n)
51     /*debug*/ Bug ("oversize b in quorem");
52 #endif
53   if (b->_wds < n)
54     return 0;
55   sx = S->_x;
56   sxe = sx + --n;
57   bx = b->_x;
58   bxe = bx + n;
59   q = *bxe / (*sxe + 1);	/* ensure q <= true quotient */
60 #ifdef DEBUG
61   /*debug*/ if (q > 9)
62     /*debug*/ Bug ("oversized quotient in quorem");
63 #endif
64   if (q)
65     {
66       borrow = 0;
67       carry = 0;
68       do
69 	{
70 #ifdef Pack_32
71 	  si = *sx++;
72 	  ys = (si & 0xffff) * q + carry;
73 	  zs = (si >> 16) * q + (ys >> 16);
74 	  carry = zs >> 16;
75 	  y = (*bx & 0xffff) - (ys & 0xffff) + borrow;
76 	  borrow = y >> 16;
77 	  Sign_Extend (borrow, y);
78 	  z = (*bx >> 16) - (zs & 0xffff) + borrow;
79 	  borrow = z >> 16;
80 	  Sign_Extend (borrow, z);
81 	  Storeinc (bx, z, y);
82 #else
83 	  ys = *sx++ * q + carry;
84 	  carry = ys >> 16;
85 	  y = *bx - (ys & 0xffff) + borrow;
86 	  borrow = y >> 16;
87 	  Sign_Extend (borrow, y);
88 	  *bx++ = y & 0xffff;
89 #endif
90 	}
91       while (sx <= sxe);
92       if (!*bxe)
93 	{
94 	  bx = b->_x;
95 	  while (--bxe > bx && !*bxe)
96 	    --n;
97 	  b->_wds = n;
98 	}
99     }
100   if (cmp (b, S) >= 0)
101     {
102       q++;
103       borrow = 0;
104       carry = 0;
105       bx = b->_x;
106       sx = S->_x;
107       do
108 	{
109 #ifdef Pack_32
110 	  si = *sx++;
111 	  ys = (si & 0xffff) + carry;
112 	  zs = (si >> 16) + (ys >> 16);
113 	  carry = zs >> 16;
114 	  y = (*bx & 0xffff) - (ys & 0xffff) + borrow;
115 	  borrow = y >> 16;
116 	  Sign_Extend (borrow, y);
117 	  z = (*bx >> 16) - (zs & 0xffff) + borrow;
118 	  borrow = z >> 16;
119 	  Sign_Extend (borrow, z);
120 	  Storeinc (bx, z, y);
121 #else
122 	  ys = *sx++ + carry;
123 	  carry = ys >> 16;
124 	  y = *bx - (ys & 0xffff) + borrow;
125 	  borrow = y >> 16;
126 	  Sign_Extend (borrow, y);
127 	  *bx++ = y & 0xffff;
128 #endif
129 	}
130       while (sx <= sxe);
131       bx = b->_x;
132       bxe = bx + n;
133       if (!*bxe)
134 	{
135 	  while (--bxe > bx && !*bxe)
136 	    --n;
137 	  b->_wds = n;
138 	}
139     }
140   return q;
141 }
142 
143 #ifdef DEBUG
144 #include <stdio.h>
145 
146 void
print(_Jv_Bigint * b)147 print (_Jv_Bigint * b)
148 {
149   int i, wds;
150   unsigned long *x, y;
151   wds = b->_wds;
152   x = b->_x+wds;
153   i = 0;
154   do
155     {
156       x--;
157       fprintf (stderr, "%08x", *x);
158     }
159   while (++i < wds);
160   fprintf (stderr, "\n");
161 }
162 #endif
163 
164 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
165  *
166  * Inspired by "How to Print Floating-Point Numbers Accurately" by
167  * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 92-101].
168  *
169  * Modifications:
170  *	1. Rather than iterating, we use a simple numeric overestimate
171  *	   to determine k = floor(log10(d)).  We scale relevant
172  *	   quantities using O(log2(k)) rather than O(k) multiplications.
173  *	2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
174  *	   try to generate digits strictly left to right.  Instead, we
175  *	   compute with fewer bits and propagate the carry if necessary
176  *	   when rounding the final digit up.  This is often faster.
177  *	3. Under the assumption that input will be rounded nearest,
178  *	   mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
179  *	   That is, we allow equality in stopping tests when the
180  *	   round-nearest rule will give the same floating-point value
181  *	   as would satisfaction of the stopping test with strict
182  *	   inequality.
183  *	4. We remove common factors of powers of 2 from relevant
184  *	   quantities.
185  *	5. When converting floating-point integers less than 1e16,
186  *	   we use floating-point arithmetic rather than resorting
187  *	   to multiple-precision integers.
188  *	6. When asked to produce fewer than 15 digits, we first try
189  *	   to get by with floating-point arithmetic; we resort to
190  *	   multiple-precision integer arithmetic only if we cannot
191  *	   guarantee that the floating-point calculation has given
192  *	   the correctly rounded result.  For k requested digits and
193  *	   "uniformly" distributed input, the probability is
194  *	   something like 10^(k-15) that we must resort to the long
195  *	   calculation.
196  */
197 
198 
199 char *
200 _DEFUN (_dtoa_r,
201 	(ptr, _d, mode, ndigits, decpt, sign, rve, float_type),
202 	struct _Jv_reent *ptr _AND
203 	double _d _AND
204 	int mode _AND
205 	int ndigits _AND
206 	int *decpt _AND
207 	int *sign _AND
208 	char **rve _AND
209 	int float_type)
210 {
211   /*
212 	float_type == 0 for double precision, 1 for float.
213 
214 	Arguments ndigits, decpt, sign are similar to those
215 	of ecvt and fcvt; trailing zeros are suppressed from
216 	the returned string.  If not null, *rve is set to point
217 	to the end of the return value.  If d is +-Infinity or NaN,
218 	then *decpt is set to 9999.
219 
220 	mode:
221 		0 ==> shortest string that yields d when read in
222 			and rounded to nearest.
223 		1 ==> like 0, but with Steele & White stopping rule;
224 			e.g. with IEEE P754 arithmetic , mode 0 gives
225 			1e23 whereas mode 1 gives 9.999999999999999e22.
226 		2 ==> max(1,ndigits) significant digits.  This gives a
227 			return value similar to that of ecvt, except
228 			that trailing zeros are suppressed.
229 		3 ==> through ndigits past the decimal point.  This
230 			gives a return value similar to that from fcvt,
231 			except that trailing zeros are suppressed, and
232 			ndigits can be negative.
233 		4-9 should give the same return values as 2-3, i.e.,
234 			4 <= mode <= 9 ==> same return as mode
235 			2 + (mode & 1).  These modes are mainly for
236 			debugging; often they run slower but sometimes
237 			faster than modes 2-3.
238 		4,5,8,9 ==> left-to-right digit generation.
239 		6-9 ==> don't try fast floating-point estimate
240 			(if applicable).
241 
242 		> 16 ==> Floating-point arg is treated as single precision.
243 
244 		Values of mode other than 0-9 are treated as mode 0.
245 
246 		Sufficient space is allocated to the return value
247 		to hold the suppressed trailing zeros.
248 	*/
249 
250   int bbits, b2, b5, be, dig, i, ieps, ilim0, j, j1, k, k0,
251     k_check, leftright, m2, m5, s2, s5, try_quick;
252   int ilim = 0, ilim1 = 0, spec_case = 0;
253   union double_union d, d2, eps;
254   long L;
255 #ifndef Sudden_Underflow
256   int denorm;
257   unsigned long x;
258 #endif
259   _Jv_Bigint *b, *b1, *delta, *mlo = NULL, *mhi, *S;
260   double ds;
261   char *s, *s0;
262 
263   d.d = _d;
264 
265   if (ptr->_result)
266     {
267       ptr->_result->_k = ptr->_result_k;
268       ptr->_result->_maxwds = 1 << ptr->_result_k;
269       Bfree (ptr, ptr->_result);
270       ptr->_result = 0;
271     }
272 
273   if (word0 (d) & Sign_bit)
274     {
275       /* set sign for everything, including 0's and NaNs */
276       *sign = 1;
277       word0 (d) &= ~Sign_bit;	/* clear sign bit */
278     }
279   else
280     *sign = 0;
281 
282 #if defined(IEEE_Arith) + defined(VAX)
283 #ifdef IEEE_Arith
284   if ((word0 (d) & Exp_mask) == Exp_mask)
285 #else
286   if (word0 (d) == 0x8000)
287 #endif
288     {
289       /* Infinity or NaN */
290       *decpt = 9999;
291       s =
292 #ifdef IEEE_Arith
293 	!word1 (d) && !(word0 (d) & 0xfffff) ? "Infinity" :
294 #endif
295 	"NaN";
296       if (rve)
297 	*rve =
298 #ifdef IEEE_Arith
299 	  s[3] ? s + 8 :
300 #endif
301 	  s + 3;
302       return s;
303     }
304 #endif
305 #ifdef IBM
306   d.d += 0;			/* normalize */
307 #endif
308   if (!d.d)
309     {
310       *decpt = 1;
311       s = "0";
312       if (rve)
313 	*rve = s + 1;
314       return s;
315     }
316 
317   b = d2b (ptr, d.d, &be, &bbits);
318 #ifdef Sudden_Underflow
319   i = (int) (word0 (d) >> Exp_shift1 & (Exp_mask >> Exp_shift1));
320 #else
321   if ((i = (int) (word0 (d) >> Exp_shift1 & (Exp_mask >> Exp_shift1))))
322     {
323 #endif
324       d2.d = d.d;
325       word0 (d2) &= Frac_mask1;
326       word0 (d2) |= Exp_11;
327 #ifdef IBM
328       if (j = 11 - hi0bits (word0 (d2) & Frac_mask))
329 	d2.d /= 1 << j;
330 #endif
331 
332       /* log(x)	~=~ log(1.5) + (x-1.5)/1.5
333 		 * log10(x)	 =  log(x) / log(10)
334 		 *		~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
335 		 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
336 		 *
337 		 * This suggests computing an approximation k to log10(d) by
338 		 *
339 		 * k = (i - Bias)*0.301029995663981
340 		 *	+ ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
341 		 *
342 		 * We want k to be too large rather than too small.
343 		 * The error in the first-order Taylor series approximation
344 		 * is in our favor, so we just round up the constant enough
345 		 * to compensate for any error in the multiplication of
346 		 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
347 		 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
348 		 * adding 1e-13 to the constant term more than suffices.
349 		 * Hence we adjust the constant term to 0.1760912590558.
350 		 * (We could get a more accurate k by invoking log10,
351 		 *  but this is probably not worthwhile.)
352 		 */
353 
354       i -= Bias;
355 #ifdef IBM
356       i <<= 2;
357       i += j;
358 #endif
359 #ifndef Sudden_Underflow
360       denorm = 0;
361     }
362   else
363     {
364       /* d is denormalized */
365 
366       i = bbits + be + (Bias + (P - 1) - 1);
367       x = i > 32 ? word0 (d) << (64 - i) | word1 (d) >> (i - 32)
368 	: word1 (d) << (32 - i);
369       d2.d = x;
370       word0 (d2) -= 31 * Exp_msk1;	/* adjust exponent */
371       i -= (Bias + (P - 1) - 1) + 1;
372       denorm = 1;
373     }
374 #endif
375   ds = (d2.d - 1.5) * 0.289529654602168 + 0.1760912590558 + i * 0.301029995663981;
376   k = (int) ds;
377   if (ds < 0. && ds != k)
378     k--;			/* want k = floor(ds) */
379   k_check = 1;
380   if (k >= 0 && k <= Ten_pmax)
381     {
382       if (d.d < tens[k])
383 	k--;
384       k_check = 0;
385     }
386   j = bbits - i - 1;
387   if (j >= 0)
388     {
389       b2 = 0;
390       s2 = j;
391     }
392   else
393     {
394       b2 = -j;
395       s2 = 0;
396     }
397   if (k >= 0)
398     {
399       b5 = 0;
400       s5 = k;
401       s2 += k;
402     }
403   else
404     {
405       b2 -= k;
406       b5 = -k;
407       s5 = 0;
408     }
409   if (mode < 0 || mode > 9)
410     mode = 0;
411   try_quick = 1;
412   if (mode > 5)
413     {
414       mode -= 4;
415       try_quick = 0;
416     }
417   leftright = 1;
418   switch (mode)
419     {
420     case 0:
421     case 1:
422       ilim = ilim1 = -1;
423       i = 18;
424       ndigits = 0;
425       break;
426     case 2:
427       leftright = 0;
428       /* no break */
429     case 4:
430       if (ndigits <= 0)
431 	ndigits = 1;
432       ilim = ilim1 = i = ndigits;
433       break;
434     case 3:
435       leftright = 0;
436       /* no break */
437     case 5:
438       i = ndigits + k + 1;
439       ilim = i;
440       ilim1 = i - 1;
441       if (i <= 0)
442 	i = 1;
443     }
444   j = sizeof (unsigned long);
445   for (ptr->_result_k = 0; (int) (sizeof (_Jv_Bigint) - sizeof (unsigned long)) + j <= i;
446        j <<= 1)
447     ptr->_result_k++;
448   ptr->_result = Balloc (ptr, ptr->_result_k);
449   s = s0 = (char *) ptr->_result;
450 
451   if (ilim >= 0 && ilim <= Quick_max && try_quick)
452     {
453       /* Try to get by with floating-point arithmetic. */
454 
455       i = 0;
456       d2.d = d.d;
457       k0 = k;
458       ilim0 = ilim;
459       ieps = 2;			/* conservative */
460       if (k > 0)
461 	{
462 	  ds = tens[k & 0xf];
463 	  j = k >> 4;
464 	  if (j & Bletch)
465 	    {
466 	      /* prevent overflows */
467 	      j &= Bletch - 1;
468 	      d.d /= bigtens[n_bigtens - 1];
469 	      ieps++;
470 	    }
471 	  for (; j; j >>= 1, i++)
472 	    if (j & 1)
473 	      {
474 		ieps++;
475 		ds *= bigtens[i];
476 	      }
477 	  d.d /= ds;
478 	}
479       else if ((j1 = -k))
480 	{
481 	  d.d *= tens[j1 & 0xf];
482 	  for (j = j1 >> 4; j; j >>= 1, i++)
483 	    if (j & 1)
484 	      {
485 		ieps++;
486 		d.d *= bigtens[i];
487 	      }
488 	}
489       if (k_check && d.d < 1. && ilim > 0)
490 	{
491 	  if (ilim1 <= 0)
492 	    goto fast_failed;
493 	  ilim = ilim1;
494 	  k--;
495 	  d.d *= 10.;
496 	  ieps++;
497 	}
498       eps.d = ieps * d.d + 7.;
499       word0 (eps) -= (P - 1) * Exp_msk1;
500       if (ilim == 0)
501 	{
502 	  S = mhi = 0;
503 	  d.d -= 5.;
504 	  if (d.d > eps.d)
505 	    goto one_digit;
506 	  if (d.d < -eps.d)
507 	    goto no_digits;
508 	  goto fast_failed;
509 	}
510 #ifndef No_leftright
511       if (leftright)
512 	{
513 	  /* Use Steele & White method of only
514 	   * generating digits needed.
515 	   */
516 	  eps.d = 0.5 / tens[ilim - 1] - eps.d;
517 	  for (i = 0;;)
518 	    {
519 	      L = d.d;
520 	      d.d -= L;
521 	      *s++ = '0' + (int) L;
522 	      if (d.d < eps.d)
523 		goto ret1;
524 	      if (1. - d.d < eps.d)
525 		goto bump_up;
526 	      if (++i >= ilim)
527 		break;
528 	      eps.d *= 10.;
529 	      d.d *= 10.;
530 	    }
531 	}
532       else
533 	{
534 #endif
535 	  /* Generate ilim digits, then fix them up. */
536 	  eps.d *= tens[ilim - 1];
537 	  for (i = 1;; i++, d.d *= 10.)
538 	    {
539 	      L = d.d;
540 	      d.d -= L;
541 	      *s++ = '0' + (int) L;
542 	      if (i == ilim)
543 		{
544 		  if (d.d > 0.5 + eps.d)
545 		    goto bump_up;
546 		  else if (d.d < 0.5 - eps.d)
547 		    {
548 		      while (*--s == '0');
549 		      s++;
550 		      goto ret1;
551 		    }
552 		  break;
553 		}
554 	    }
555 #ifndef No_leftright
556 	}
557 #endif
558     fast_failed:
559       s = s0;
560       d.d = d2.d;
561       k = k0;
562       ilim = ilim0;
563     }
564 
565   /* Do we have a "small" integer? */
566 
567   if (be >= 0 && k <= Int_max)
568     {
569       /* Yes. */
570       ds = tens[k];
571       if (ndigits < 0 && ilim <= 0)
572 	{
573 	  S = mhi = 0;
574 	  if (ilim < 0 || d.d <= 5 * ds)
575 	    goto no_digits;
576 	  goto one_digit;
577 	}
578       for (i = 1;; i++)
579 	{
580 	  L = d.d / ds;
581 	  d.d -= L * ds;
582 #ifdef Check_FLT_ROUNDS
583 	  /* If FLT_ROUNDS == 2, L will usually be high by 1 */
584 	  if (d.d < 0)
585 	    {
586 	      L--;
587 	      d.d += ds;
588 	    }
589 #endif
590 	  *s++ = '0' + (int) L;
591 	  if (i == ilim)
592 	    {
593 	      d.d += d.d;
594 	      if (d.d > ds || (d.d == ds && L & 1))
595 		{
596 		bump_up:
597 		  while (*--s == '9')
598 		    if (s == s0)
599 		      {
600 			k++;
601 			*s = '0';
602 			break;
603 		      }
604 		  ++*s++;
605 		}
606 	      break;
607 	    }
608 	  if (!(d.d *= 10.))
609 	    break;
610 	}
611       goto ret1;
612     }
613 
614   m2 = b2;
615   m5 = b5;
616   mhi = mlo = 0;
617   if (leftright)
618     {
619       if (mode < 2)
620 	{
621 	  i =
622 #ifndef Sudden_Underflow
623 	    denorm ? be + (Bias + (P - 1) - 1 + 1) :
624 #endif
625 #ifdef IBM
626 	    1 + 4 * P - 3 - bbits + ((bbits + be - 1) & 3);
627 #else
628 	    1 + P - bbits;
629 #endif
630 	}
631       else
632 	{
633 	  j = ilim - 1;
634 	  if (m5 >= j)
635 	    m5 -= j;
636 	  else
637 	    {
638 	      s5 += j -= m5;
639 	      b5 += j;
640 	      m5 = 0;
641 	    }
642 	  if ((i = ilim) < 0)
643 	    {
644 	      m2 -= i;
645 	      i = 0;
646 	    }
647 	}
648       b2 += i;
649       s2 += i;
650       mhi = i2b (ptr, 1);
651     }
652   if (m2 > 0 && s2 > 0)
653     {
654       i = m2 < s2 ? m2 : s2;
655       b2 -= i;
656       m2 -= i;
657       s2 -= i;
658     }
659   if (b5 > 0)
660     {
661       if (leftright)
662 	{
663 	  if (m5 > 0)
664 	    {
665 	      mhi = pow5mult (ptr, mhi, m5);
666 	      b1 = mult (ptr, mhi, b);
667 	      Bfree (ptr, b);
668 	      b = b1;
669 	    }
670 	  if ((j = b5 - m5))
671 	    b = pow5mult (ptr, b, j);
672 	}
673       else
674 	b = pow5mult (ptr, b, b5);
675     }
676   S = i2b (ptr, 1);
677   if (s5 > 0)
678     S = pow5mult (ptr, S, s5);
679 
680   /* Check for special case that d is a normalized power of 2. */
681 
682   if (mode < 2)
683     {
684       if (!word1 (d) && !(word0 (d) & Bndry_mask)
685 #ifndef Sudden_Underflow
686 	  && word0(d) & Exp_mask
687 #endif
688 	)
689 	{
690 	  /* The special case */
691 	  b2 += Log2P;
692 	  s2 += Log2P;
693 	  spec_case = 1;
694 	}
695       else
696 	spec_case = 0;
697     }
698 
699   /* Arrange for convenient computation of quotients:
700    * shift left if necessary so divisor has 4 leading 0 bits.
701    *
702    * Perhaps we should just compute leading 28 bits of S once
703    * and for all and pass them and a shift to quorem, so it
704    * can do shifts and ors to compute the numerator for q.
705    */
706 
707 #ifdef Pack_32
708   if ((i = ((s5 ? 32 - hi0bits (S->_x[S->_wds - 1]) : 1) + s2) & 0x1f))
709     i = 32 - i;
710 #else
711   if ((i = ((s5 ? 32 - hi0bits (S->_x[S->_wds - 1]) : 1) + s2) & 0xf))
712     i = 16 - i;
713 #endif
714   if (i > 4)
715     {
716       i -= 4;
717       b2 += i;
718       m2 += i;
719       s2 += i;
720     }
721   else if (i < 4)
722     {
723       i += 28;
724       b2 += i;
725       m2 += i;
726       s2 += i;
727     }
728   if (b2 > 0)
729     b = lshift (ptr, b, b2);
730   if (s2 > 0)
731     S = lshift (ptr, S, s2);
732   if (k_check)
733     {
734       if (cmp (b, S) < 0)
735 	{
736 	  k--;
737 	  b = multadd (ptr, b, 10, 0);	/* we botched the k estimate */
738 	  if (leftright)
739 	    mhi = multadd (ptr, mhi, 10, 0);
740 	  ilim = ilim1;
741 	}
742     }
743   if (ilim <= 0 && mode > 2)
744     {
745       if (ilim < 0 || cmp (b, S = multadd (ptr, S, 5, 0)) <= 0)
746 	{
747 	  /* no digits, fcvt style */
748 	no_digits:
749 	  k = -1 - ndigits;
750 	  goto ret;
751 	}
752     one_digit:
753       *s++ = '1';
754       k++;
755       goto ret;
756     }
757   if (leftright)
758     {
759       if (m2 > 0)
760 	mhi = lshift (ptr, mhi, m2);
761 
762       /* Single precision case, */
763       if (float_type)
764 	mhi = lshift (ptr, mhi, 29);
765 
766       /* Compute mlo -- check for special case
767        * that d is a normalized power of 2.
768        */
769 
770       mlo = mhi;
771       if (spec_case)
772 	{
773 	  mhi = Balloc (ptr, mhi->_k);
774 	  Bcopy (mhi, mlo);
775 	  mhi = lshift (ptr, mhi, Log2P);
776 	}
777 
778       for (i = 1;; i++)
779 	{
780 	  dig = quorem (b, S) + '0';
781 	  /* Do we yet have the shortest decimal string
782 	   * that will round to d?
783 	   */
784 	  j = cmp (b, mlo);
785 	  delta = diff (ptr, S, mhi);
786 	  j1 = delta->_sign ? 1 : cmp (b, delta);
787 	  Bfree (ptr, delta);
788 #ifndef ROUND_BIASED
789 	  if (j1 == 0 && !mode && !(word1 (d) & 1))
790 	    {
791 	      if (dig == '9')
792 		goto round_9_up;
793 	      if (j > 0)
794 		dig++;
795 	      *s++ = dig;
796 	      goto ret;
797 	    }
798 #endif
799 	  if (j < 0 || (j == 0 && !mode
800 #ifndef ROUND_BIASED
801 	      && !(word1 (d) & 1)
802 #endif
803 	    ))
804 	    {
805 	      if (j1 > 0)
806 		{
807 		  b = lshift (ptr, b, 1);
808 		  j1 = cmp (b, S);
809 		  if ((j1 > 0 || (j1 == 0 && dig & 1))
810 		      && dig++ == '9')
811 		    goto round_9_up;
812 		}
813 	      *s++ = dig;
814 	      goto ret;
815 	    }
816 	  if (j1 > 0)
817 	    {
818 	      if (dig == '9')
819 		{		/* possible if i == 1 */
820 		round_9_up:
821 		  *s++ = '9';
822 		  goto roundoff;
823 		}
824 	      *s++ = dig + 1;
825 	      goto ret;
826 	    }
827 	  *s++ = dig;
828 	  if (i == ilim)
829 	    break;
830 	  b = multadd (ptr, b, 10, 0);
831 	  if (mlo == mhi)
832 	    mlo = mhi = multadd (ptr, mhi, 10, 0);
833 	  else
834 	    {
835 	      mlo = multadd (ptr, mlo, 10, 0);
836 	      mhi = multadd (ptr, mhi, 10, 0);
837 	    }
838 	}
839     }
840   else
841     for (i = 1;; i++)
842       {
843 	*s++ = dig = quorem (b, S) + '0';
844 	if (i >= ilim)
845 	  break;
846 	b = multadd (ptr, b, 10, 0);
847       }
848 
849   /* Round off last digit */
850 
851   b = lshift (ptr, b, 1);
852   j = cmp (b, S);
853   if (j > 0 || (j == 0 && dig & 1))
854     {
855     roundoff:
856       while (*--s == '9')
857 	if (s == s0)
858 	  {
859 	    k++;
860 	    *s++ = '1';
861 	    goto ret;
862 	  }
863       ++*s++;
864     }
865   else
866     {
867       while (*--s == '0');
868       s++;
869     }
870 ret:
871   Bfree (ptr, S);
872   if (mhi)
873     {
874       if (mlo && mlo != mhi)
875 	Bfree (ptr, mlo);
876       Bfree (ptr, mhi);
877     }
878 ret1:
879   Bfree (ptr, b);
880   *s = 0;
881   *decpt = k + 1;
882   if (rve)
883     *rve = s;
884   return s0;
885 }
886 
887 
888 _VOID
889 _DEFUN (_dtoa,
890 	(_d, mode, ndigits, decpt, sign, rve, buf, float_type),
891 	double _d _AND
892 	int mode _AND
893 	int ndigits _AND
894 	int *decpt _AND
895 	int *sign _AND
896 	char **rve _AND
897 	char *buf _AND
898 	int float_type)
899 {
900   struct _Jv_reent reent;
901   char *p;
902   int i;
903 
904   memset (&reent, 0, sizeof reent);
905 
906   p = _dtoa_r (&reent, _d, mode, ndigits, decpt, sign, rve, float_type);
907   strcpy (buf, p);
908 
909   for (i = 0; i < reent._result_k; ++i)
910     {
911       struct _Jv_Bigint *l = reent._freelist[i];
912       while (l)
913 	{
914 	  struct _Jv_Bigint *next = l->_next;
915 	  free (l);
916 	  l = next;
917 	}
918     }
919   if (reent._freelist)
920     free (reent._freelist);
921 }
922