Initial import from FreeBSD RELENG_4:
[dragonfly.git] / lib / libcr / stdlib / strtod.c
1 /*-
2  * Copyright (c) 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD: src/lib/libc/stdlib/strtod.c,v 1.3.8.4 2002/08/31 22:26:35 dwmalone Exp $
34  */
35
36 #if defined(LIBC_SCCS) && !defined(lint)
37 static char sccsid[] = "@(#)strtod.c    8.1 (Berkeley) 6/4/93";
38 #endif /* LIBC_SCCS and not lint */
39
40 /****************************************************************
41  *
42  * The author of this software is David M. Gay.
43  *
44  * Copyright (c) 1991 by AT&T.
45  *
46  * Permission to use, copy, modify, and distribute this software for any
47  * purpose without fee is hereby granted, provided that this entire notice
48  * is included in all copies of any software which is or includes a copy
49  * or modification of this software and in all copies of the supporting
50  * documentation for such software.
51  *
52  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
53  * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR AT&T MAKES ANY
54  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
55  * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
56  *
57  ***************************************************************/
58
59 /* Please send bug reports to
60         David M. Gay
61         AT&T Bell Laboratories, Room 2C-463
62         600 Mountain Avenue
63         Murray Hill, NJ 07974-2070
64         U.S.A.
65         dmg@research.att.com or research!dmg
66  */
67
68 /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
69  *
70  * This strtod returns a nearest machine number to the input decimal
71  * string (or sets errno to ERANGE).  With IEEE arithmetic, ties are
72  * broken by the IEEE round-even rule.  Otherwise ties are broken by
73  * biased rounding (add half and chop).
74  *
75  * Inspired loosely by William D. Clinger's paper "How to Read Floating
76  * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
77  *
78  * Modifications:
79  *
80  *      1. We only require IEEE, IBM, or VAX double-precision
81  *              arithmetic (not IEEE double-extended).
82  *      2. We get by with floating-point arithmetic in a case that
83  *              Clinger missed -- when we're computing d * 10^n
84  *              for a small integer d and the integer n is not too
85  *              much larger than 22 (the maximum integer k for which
86  *              we can represent 10^k exactly), we may be able to
87  *              compute (d*10^k) * 10^(e-k) with just one roundoff.
88  *      3. Rather than a bit-at-a-time adjustment of the binary
89  *              result in the hard case, we use floating-point
90  *              arithmetic to determine the adjustment to within
91  *              one bit; only in really hard cases do we need to
92  *              compute a second residual.
93  *      4. Because of 3., we don't need a large table of powers of 10
94  *              for ten-to-e (just some small tables, e.g. of 10^k
95  *              for 0 <= k <= 22).
96  */
97
98 /*
99  * #define IEEE_8087 for IEEE-arithmetic machines where the least
100  *      significant byte has the lowest address.
101  * #define IEEE_MC68k for IEEE-arithmetic machines where the most
102  *      significant byte has the lowest address.
103  * #define Sudden_Underflow for IEEE-format machines without gradual
104  *      underflow (i.e., that flush to zero on underflow).
105  * #define IBM for IBM mainframe-style floating-point arithmetic.
106  * #define VAX for VAX-style floating-point arithmetic.
107  * #define Unsigned_Shifts if >> does treats its left operand as unsigned.
108  * #define No_leftright to omit left-right logic in fast floating-point
109  *      computation of dtoa.
110  * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3.
111  * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
112  *      that use extended-precision instructions to compute rounded
113  *      products and quotients) with IBM.
114  * #define ROUND_BIASED for IEEE-format with biased rounding.
115  * #define Inaccurate_Divide for IEEE-format with correctly rounded
116  *      products but inaccurate quotients, e.g., for Intel i860.
117  * #define Just_16 to store 16 bits per 32-bit long when doing high-precision
118  *      integer arithmetic.  Whether this speeds things up or slows things
119  *      down depends on the machine and the number being converted.
120  * #define KR_headers for old-style C function headers.
121  * #define Bad_float_h if your system lacks a float.h or if it does not
122  *      define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
123  *      FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
124  */
125
126 #if defined(i386) || defined(mips) && defined(MIPSEL)
127 #define IEEE_8087
128 #else
129 #define IEEE_MC68k
130 #endif
131
132 #ifdef DEBUG
133 #include "stdio.h"
134 #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
135 #endif
136
137 #include <locale.h>
138 #ifdef __cplusplus
139 #include "malloc.h"
140 #include "memory.h"
141 #else
142 #ifndef KR_headers
143 #include "stdlib.h"
144 #include "string.h"
145 #else
146 #include "malloc.h"
147 #include "memory.h"
148 #endif
149 #endif
150
151 #include "errno.h"
152 #include <ctype.h>
153 #ifdef Bad_float_h
154 #undef __STDC__
155 #ifdef IEEE_MC68k
156 #define IEEE_ARITHMETIC
157 #endif
158 #ifdef IEEE_8087
159 #define IEEE_ARITHMETIC
160 #endif
161 #ifdef IEEE_ARITHMETIC
162 #define DBL_DIG 15
163 #define DBL_MAX_10_EXP 308
164 #define DBL_MAX_EXP 1024
165 #define FLT_RADIX 2
166 #define FLT_ROUNDS 1
167 #define DBL_MAX 1.7976931348623157e+308
168 #endif
169
170 #ifdef IBM
171 #define DBL_DIG 16
172 #define DBL_MAX_10_EXP 75
173 #define DBL_MAX_EXP 63
174 #define FLT_RADIX 16
175 #define FLT_ROUNDS 0
176 #define DBL_MAX 7.2370055773322621e+75
177 #endif
178
179 #ifdef VAX
180 #define DBL_DIG 16
181 #define DBL_MAX_10_EXP 38
182 #define DBL_MAX_EXP 127
183 #define FLT_RADIX 2
184 #define FLT_ROUNDS 1
185 #define DBL_MAX 1.7014118346046923e+38
186 #endif
187
188 #ifndef LONG_MAX
189 #define LONG_MAX 2147483647
190 #endif
191 #else
192 #include "float.h"
193 #endif
194 #ifndef __MATH_H__
195 #include "math.h"
196 #endif
197
198 #ifdef __cplusplus
199 extern "C" {
200 #endif
201
202 #ifndef CONST
203 #ifdef KR_headers
204 #define CONST /* blank */
205 #else
206 #define CONST const
207 #endif
208 #endif
209
210 #ifdef Unsigned_Shifts
211 #define Sign_Extend(a,b) if (b < 0) a |= 0xffff0000;
212 #else
213 #define Sign_Extend(a,b) /*no-op*/
214 #endif
215
216 #if defined(IEEE_8087) + defined(IEEE_MC68k) + defined(VAX) + defined(IBM) != 1
217 Exactly one of IEEE_8087, IEEE_MC68k, VAX, or IBM should be defined.
218 #endif
219
220 union doubleasulongs {
221         double x;
222         unsigned long w[2];
223 };
224 #ifdef IEEE_8087
225 #define word0(x) (((union doubleasulongs *)&x)->w)[1]
226 #define word1(x) (((union doubleasulongs *)&x)->w)[0]
227 #else
228 #define word0(x) (((union doubleasulongs *)&x)->w)[0]
229 #define word1(x) (((union doubleasulongs *)&x)->w)[1]
230 #endif
231
232 /* The following definition of Storeinc is appropriate for MIPS processors.
233  * An alternative that might be better on some machines is
234  * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
235  */
236 #if defined(IEEE_8087) + defined(VAX)
237 #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
238 ((unsigned short *)a)[0] = (unsigned short)c, a++)
239 #else
240 #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
241 ((unsigned short *)a)[1] = (unsigned short)c, a++)
242 #endif
243
244 /* #define P DBL_MANT_DIG */
245 /* Ten_pmax = floor(P*log(2)/log(5)) */
246 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
247 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
248 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
249
250 #if defined(IEEE_8087) + defined(IEEE_MC68k)
251 #define Exp_shift  20
252 #define Exp_shift1 20
253 #define Exp_msk1    0x100000
254 #define Exp_msk11   0x100000
255 #define Exp_mask  0x7ff00000
256 #define P 53
257 #define Bias 1023
258 #define IEEE_Arith
259 #define Emin (-1022)
260 #define Exp_1  0x3ff00000
261 #define Exp_11 0x3ff00000
262 #define Ebits 11
263 #define Frac_mask  0xfffff
264 #define Frac_mask1 0xfffff
265 #define Ten_pmax 22
266 #define Bletch 0x10
267 #define Bndry_mask  0xfffff
268 #define Bndry_mask1 0xfffff
269 #define LSB 1
270 #define Sign_bit 0x80000000
271 #define Log2P 1
272 #define Tiny0 0
273 #define Tiny1 1
274 #define Quick_max 14
275 #define Int_max 14
276 #define Infinite(x) (word0(x) == 0x7ff00000) /* sufficient test for here */
277 #else
278 #undef  Sudden_Underflow
279 #define Sudden_Underflow
280 #ifdef IBM
281 #define Exp_shift  24
282 #define Exp_shift1 24
283 #define Exp_msk1   0x1000000
284 #define Exp_msk11  0x1000000
285 #define Exp_mask  0x7f000000
286 #define P 14
287 #define Bias 65
288 #define Exp_1  0x41000000
289 #define Exp_11 0x41000000
290 #define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
291 #define Frac_mask  0xffffff
292 #define Frac_mask1 0xffffff
293 #define Bletch 4
294 #define Ten_pmax 22
295 #define Bndry_mask  0xefffff
296 #define Bndry_mask1 0xffffff
297 #define LSB 1
298 #define Sign_bit 0x80000000
299 #define Log2P 4
300 #define Tiny0 0x100000
301 #define Tiny1 0
302 #define Quick_max 14
303 #define Int_max 15
304 #else /* VAX */
305 #define Exp_shift  23
306 #define Exp_shift1 7
307 #define Exp_msk1    0x80
308 #define Exp_msk11   0x800000
309 #define Exp_mask  0x7f80
310 #define P 56
311 #define Bias 129
312 #define Exp_1  0x40800000
313 #define Exp_11 0x4080
314 #define Ebits 8
315 #define Frac_mask  0x7fffff
316 #define Frac_mask1 0xffff007f
317 #define Ten_pmax 24
318 #define Bletch 2
319 #define Bndry_mask  0xffff007f
320 #define Bndry_mask1 0xffff007f
321 #define LSB 0x10000
322 #define Sign_bit 0x8000
323 #define Log2P 1
324 #define Tiny0 0x80
325 #define Tiny1 0
326 #define Quick_max 15
327 #define Int_max 15
328 #endif
329 #endif
330
331 #ifndef IEEE_Arith
332 #define ROUND_BIASED
333 #endif
334
335 #ifdef RND_PRODQUOT
336 #define rounded_product(a,b) a = rnd_prod(a, b)
337 #define rounded_quotient(a,b) a = rnd_quot(a, b)
338 #ifdef KR_headers
339 extern double rnd_prod(), rnd_quot();
340 #else
341 extern double rnd_prod(double, double), rnd_quot(double, double);
342 #endif
343 #else
344 #define rounded_product(a,b) a *= b
345 #define rounded_quotient(a,b) a /= b
346 #endif
347
348 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
349 #define Big1 0xffffffff
350
351 #ifndef Just_16
352 /* When Pack_32 is not defined, we store 16 bits per 32-bit long.
353  * This makes some inner loops simpler and sometimes saves work
354  * during multiplications, but it often seems to make things slightly
355  * slower.  Hence the default is now to store 32 bits per long.
356  */
357 #ifndef Pack_32
358 #define Pack_32
359 #endif
360 #endif
361
362 #define Kmax 15
363
364 #ifdef __cplusplus
365 extern "C" double strtod(const char *s00, char **se);
366 extern "C" char *__dtoa(double d, int mode, int ndigits,
367                         int *decpt, int *sign, char **rve, char **resultp);
368 #endif
369
370  struct
371 Bigint {
372         struct Bigint *next;
373         int k, maxwds, sign, wds;
374         unsigned long x[1];
375 };
376
377  typedef struct Bigint Bigint;
378
379  static Bigint *
380 Balloc
381 #ifdef KR_headers
382         (k) int k;
383 #else
384         (int k)
385 #endif
386 {
387         int x;
388         Bigint *rv;
389
390         x = 1 << k;
391         rv = (Bigint *)malloc(sizeof(Bigint) + (x-1)*sizeof(long));
392         rv->k = k;
393         rv->maxwds = x;
394         rv->sign = rv->wds = 0;
395         return rv;
396 }
397
398  static void
399 Bfree
400 #ifdef KR_headers
401         (v) Bigint *v;
402 #else
403         (Bigint *v)
404 #endif
405 {
406         free(v);
407 }
408
409 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
410 y->wds*sizeof(long) + 2*sizeof(int))
411
412  static Bigint *
413 multadd
414 #ifdef KR_headers
415         (b, m, a) Bigint *b; int m, a;
416 #else
417         (Bigint *b, int m, int a)       /* multiply by m and add a */
418 #endif
419 {
420         int i, wds;
421         unsigned long *x, y;
422 #ifdef Pack_32
423         unsigned long xi, z;
424 #endif
425         Bigint *b1;
426
427         wds = b->wds;
428         x = b->x;
429         i = 0;
430         do {
431 #ifdef Pack_32
432                 xi = *x;
433                 y = (xi & 0xffff) * m + a;
434                 z = (xi >> 16) * m + (y >> 16);
435                 a = (int)(z >> 16);
436                 *x++ = (z << 16) + (y & 0xffff);
437 #else
438                 y = *x * m + a;
439                 a = (int)(y >> 16);
440                 *x++ = y & 0xffff;
441 #endif
442         } while (++i < wds);
443         if (a) {
444                 if (wds >= b->maxwds) {
445                         b1 = Balloc(b->k+1);
446                         Bcopy(b1, b);
447                         Bfree(b);
448                         b = b1;
449                         }
450                 b->x[wds++] = a;
451                 b->wds = wds;
452         }
453         return b;
454 }
455
456  static Bigint *
457 s2b
458 #ifdef KR_headers
459         (s, nd0, nd, y9) CONST char *s; int nd0, nd; unsigned long y9;
460 #else
461         (CONST char *s, int nd0, int nd, unsigned long y9)
462 #endif
463 {
464         Bigint *b;
465         int i, k;
466         long x, y;
467
468         x = (nd + 8) / 9;
469         for (k = 0, y = 1; x > y; y <<= 1, k++) ;
470 #ifdef Pack_32
471         b = Balloc(k);
472         b->x[0] = y9;
473         b->wds = 1;
474 #else
475         b = Balloc(k+1);
476         b->x[0] = y9 & 0xffff;
477         b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
478 #endif
479
480         i = 9;
481         if (9 < nd0) {
482                 s += 9;
483                 do
484                         b = multadd(b, 10, *s++ - '0');
485                 while (++i < nd0);
486                 s++;
487         } else
488                 s += 10;
489         for (; i < nd; i++)
490                 b = multadd(b, 10, *s++ - '0');
491         return b;
492 }
493
494  static int
495 hi0bits
496 #ifdef KR_headers
497         (x) register unsigned long x;
498 #else
499         (register unsigned long x)
500 #endif
501 {
502         register int k = 0;
503
504         if (!(x & 0xffff0000)) {
505                 k = 16;
506                 x <<= 16;
507         }
508         if (!(x & 0xff000000)) {
509                 k += 8;
510                 x <<= 8;
511         }
512         if (!(x & 0xf0000000)) {
513                 k += 4;
514                 x <<= 4;
515         }
516         if (!(x & 0xc0000000)) {
517                 k += 2;
518                 x <<= 2;
519         }
520         if (!(x & 0x80000000)) {
521                 k++;
522                 if (!(x & 0x40000000))
523                         return 32;
524         }
525         return k;
526 }
527
528  static int
529 lo0bits
530 #ifdef KR_headers
531         (y) unsigned long *y;
532 #else
533         (unsigned long *y)
534 #endif
535 {
536         register int k;
537         register unsigned long x = *y;
538
539         if (x & 7) {
540                 if (x & 1)
541                         return 0;
542                 if (x & 2) {
543                         *y = x >> 1;
544                         return 1;
545                 }
546                 *y = x >> 2;
547                 return 2;
548         }
549         k = 0;
550         if (!(x & 0xffff)) {
551                 k = 16;
552                 x >>= 16;
553         }
554         if (!(x & 0xff)) {
555                 k += 8;
556                 x >>= 8;
557         }
558         if (!(x & 0xf)) {
559                 k += 4;
560                 x >>= 4;
561         }
562         if (!(x & 0x3)) {
563                 k += 2;
564                 x >>= 2;
565         }
566         if (!(x & 1)) {
567                 k++;
568                 x >>= 1;
569                 if (!x & 1)
570                         return 32;
571         }
572         *y = x;
573         return k;
574 }
575
576  static Bigint *
577 i2b
578 #ifdef KR_headers
579         (i) int i;
580 #else
581         (int i)
582 #endif
583 {
584         Bigint *b;
585
586         b = Balloc(1);
587         b->x[0] = i;
588         b->wds = 1;
589         return b;
590         }
591
592  static Bigint *
593 mult
594 #ifdef KR_headers
595         (a, b) Bigint *a, *b;
596 #else
597         (Bigint *a, Bigint *b)
598 #endif
599 {
600         Bigint *c;
601         int k, wa, wb, wc;
602         unsigned long carry, y, z;
603         unsigned long *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
604 #ifdef Pack_32
605         unsigned long z2;
606 #endif
607
608         if (a->wds < b->wds) {
609                 c = a;
610                 a = b;
611                 b = c;
612         }
613         k = a->k;
614         wa = a->wds;
615         wb = b->wds;
616         wc = wa + wb;
617         if (wc > a->maxwds)
618                 k++;
619         c = Balloc(k);
620         for (x = c->x, xa = x + wc; x < xa; x++)
621                 *x = 0;
622         xa = a->x;
623         xae = xa + wa;
624         xb = b->x;
625         xbe = xb + wb;
626         xc0 = c->x;
627 #ifdef Pack_32
628         for (; xb < xbe; xb++, xc0++) {
629                 if ( (y = *xb & 0xffff) ) {
630                         x = xa;
631                         xc = xc0;
632                         carry = 0;
633                         do {
634                                 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
635                                 carry = z >> 16;
636                                 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
637                                 carry = z2 >> 16;
638                                 Storeinc(xc, z2, z);
639                         } while (x < xae);
640                         *xc = carry;
641                 }
642                 if ( (y = *xb >> 16) ) {
643                         x = xa;
644                         xc = xc0;
645                         carry = 0;
646                         z2 = *xc;
647                         do {
648                                 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
649                                 carry = z >> 16;
650                                 Storeinc(xc, z, z2);
651                                 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
652                                 carry = z2 >> 16;
653                         } while (x < xae);
654                         *xc = z2;
655                 }
656         }
657 #else
658         for (; xb < xbe; xc0++) {
659                 if (y = *xb++) {
660                         x = xa;
661                         xc = xc0;
662                         carry = 0;
663                         do {
664                                 z = *x++ * y + *xc + carry;
665                                 carry = z >> 16;
666                                 *xc++ = z & 0xffff;
667                         } while (x < xae);
668                         *xc = carry;
669                 }
670         }
671 #endif
672         for (xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
673         c->wds = wc;
674         return c;
675 }
676
677  static Bigint *p5s;
678
679  static Bigint *
680 pow5mult
681 #ifdef KR_headers
682         (b, k) Bigint *b; int k;
683 #else
684         (Bigint *b, int k)
685 #endif
686 {
687         Bigint *b1, *p5, *p51;
688         int i;
689         static int p05[3] = { 5, 25, 125 };
690
691         if ( (i = k & 3) )
692                 b = multadd(b, p05[i-1], 0);
693
694         if (!(k >>= 2))
695                 return b;
696         if (!(p5 = p5s)) {
697                 /* first time */
698                 p5 = p5s = i2b(625);
699                 p5->next = 0;
700         }
701         for (;;) {
702                 if (k & 1) {
703                         b1 = mult(b, p5);
704                         Bfree(b);
705                         b = b1;
706                 }
707                 if (!(k >>= 1))
708                         break;
709                 if (!(p51 = p5->next)) {
710                         p51 = p5->next = mult(p5,p5);
711                         p51->next = 0;
712                 }
713                 p5 = p51;
714         }
715         return b;
716 }
717
718  static Bigint *
719 lshift
720 #ifdef KR_headers
721         (b, k) Bigint *b; int k;
722 #else
723         (Bigint *b, int k)
724 #endif
725 {
726         int i, k1, n, n1;
727         Bigint *b1;
728         unsigned long *x, *x1, *xe, z;
729
730 #ifdef Pack_32
731         n = k >> 5;
732 #else
733         n = k >> 4;
734 #endif
735         k1 = b->k;
736         n1 = n + b->wds + 1;
737         for (i = b->maxwds; n1 > i; i <<= 1)
738                 k1++;
739         b1 = Balloc(k1);
740         x1 = b1->x;
741         for (i = 0; i < n; i++)
742                 *x1++ = 0;
743         x = b->x;
744         xe = x + b->wds;
745 #ifdef Pack_32
746         if (k &= 0x1f) {
747                 k1 = 32 - k;
748                 z = 0;
749                 do {
750                         *x1++ = *x << k | z;
751                         z = *x++ >> k1;
752                 } while (x < xe);
753                 if ( (*x1 = z) )
754                         ++n1;
755         }
756 #else
757         if (k &= 0xf) {
758                 k1 = 16 - k;
759                 z = 0;
760                 do {
761                         *x1++ = *x << k  & 0xffff | z;
762                         z = *x++ >> k1;
763                 } while (x < xe);
764                 if (*x1 = z)
765                         ++n1;
766         }
767 #endif
768         else
769                 do
770                         *x1++ = *x++;
771                 while (x < xe);
772         b1->wds = n1 - 1;
773         Bfree(b);
774         return b1;
775 }
776
777  static int
778 cmp
779 #ifdef KR_headers
780         (a, b) Bigint *a, *b;
781 #else
782         (Bigint *a, Bigint *b)
783 #endif
784 {
785         unsigned long *xa, *xa0, *xb, *xb0;
786         int i, j;
787
788         i = a->wds;
789         j = b->wds;
790 #ifdef DEBUG
791         if (i > 1 && !a->x[i-1])
792                 Bug("cmp called with a->x[a->wds-1] == 0");
793         if (j > 1 && !b->x[j-1])
794                 Bug("cmp called with b->x[b->wds-1] == 0");
795 #endif
796         if (i -= j)
797                 return i;
798         xa0 = a->x;
799         xa = xa0 + j;
800         xb0 = b->x;
801         xb = xb0 + j;
802         for (;;) {
803                 if (*--xa != *--xb)
804                         return *xa < *xb ? -1 : 1;
805                 if (xa <= xa0)
806                         break;
807         }
808         return 0;
809 }
810
811  static Bigint *
812 diff
813 #ifdef KR_headers
814         (a, b) Bigint *a, *b;
815 #else
816         (Bigint *a, Bigint *b)
817 #endif
818 {
819         Bigint *c;
820         int i, wa, wb;
821         long borrow, y; /* We need signed shifts here. */
822         unsigned long *xa, *xae, *xb, *xbe, *xc;
823 #ifdef Pack_32
824         long z;
825 #endif
826
827         i = cmp(a,b);
828         if (!i) {
829                 c = Balloc(0);
830                 c->wds = 1;
831                 c->x[0] = 0;
832                 return c;
833         }
834         if (i < 0) {
835                 c = a;
836                 a = b;
837                 b = c;
838                 i = 1;
839         } else
840                 i = 0;
841         c = Balloc(a->k);
842         c->sign = i;
843         wa = a->wds;
844         xa = a->x;
845         xae = xa + wa;
846         wb = b->wds;
847         xb = b->x;
848         xbe = xb + wb;
849         xc = c->x;
850         borrow = 0;
851 #ifdef Pack_32
852         do {
853                 y = (*xa & 0xffff) - (*xb & 0xffff) + borrow;
854                 borrow = y >> 16;
855                 Sign_Extend(borrow, y);
856                 z = (*xa++ >> 16) - (*xb++ >> 16) + borrow;
857                 borrow = z >> 16;
858                 Sign_Extend(borrow, z);
859                 Storeinc(xc, z, y);
860         } while (xb < xbe);
861         while (xa < xae) {
862                 y = (*xa & 0xffff) + borrow;
863                 borrow = y >> 16;
864                 Sign_Extend(borrow, y);
865                 z = (*xa++ >> 16) + borrow;
866                 borrow = z >> 16;
867                 Sign_Extend(borrow, z);
868                 Storeinc(xc, z, y);
869         }
870 #else
871         do {
872                 y = *xa++ - *xb++ + borrow;
873                 borrow = y >> 16;
874                 Sign_Extend(borrow, y);
875                 *xc++ = y & 0xffff;
876         } while (xb < xbe);
877         while (xa < xae) {
878                 y = *xa++ + borrow;
879                 borrow = y >> 16;
880                 Sign_Extend(borrow, y);
881                 *xc++ = y & 0xffff;
882         }
883 #endif
884         while (!*--xc)
885                 wa--;
886         c->wds = wa;
887         return c;
888 }
889
890  static double
891 ulp
892 #ifdef KR_headers
893         (x) double x;
894 #else
895         (double x)
896 #endif
897 {
898         register long L;
899         double a;
900
901         L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
902 #ifndef Sudden_Underflow
903         if (L > 0) {
904 #endif
905 #ifdef IBM
906                 L |= Exp_msk1 >> 4;
907 #endif
908                 word0(a) = L;
909                 word1(a) = 0;
910 #ifndef Sudden_Underflow
911         } else {
912                 L = -L >> Exp_shift;
913                 if (L < Exp_shift) {
914                         word0(a) = 0x80000 >> L;
915                         word1(a) = 0;
916                 } else {
917                         word0(a) = 0;
918                         L -= Exp_shift;
919                         word1(a) = L >= 31 ? 1 : 1 << (31 - L);
920                 }
921         }
922 #endif
923         return a;
924 }
925
926  static double
927 b2d
928 #ifdef KR_headers
929         (a, e) Bigint *a; int *e;
930 #else
931         (Bigint *a, int *e)
932 #endif
933 {
934         unsigned long *xa, *xa0, w, y, z;
935         int k;
936         double d;
937 #ifdef VAX
938         unsigned long d0, d1;
939 #else
940 #define d0 word0(d)
941 #define d1 word1(d)
942 #endif
943
944         xa0 = a->x;
945         xa = xa0 + a->wds;
946         y = *--xa;
947 #ifdef DEBUG
948         if (!y) Bug("zero y in b2d");
949 #endif
950         k = hi0bits(y);
951         *e = 32 - k;
952 #ifdef Pack_32
953         if (k < Ebits) {
954                 d0 = Exp_1 | (y >> (Ebits - k));
955                 w = xa > xa0 ? *--xa : 0;
956                 d1 = (y << ((32-Ebits) + k)) | (w >> (Ebits - k));
957                 goto ret_d;
958                 }
959         z = xa > xa0 ? *--xa : 0;
960         if (k -= Ebits) {
961                 d0 = Exp_1 | (y << k) | (z >> (32 - k));
962                 y = xa > xa0 ? *--xa : 0;
963                 d1 = (z << k) | (y >> (32 - k));
964         } else {
965                 d0 = Exp_1 | y;
966                 d1 = z;
967         }
968 #else
969         if (k < Ebits + 16) {
970                 z = xa > xa0 ? *--xa : 0;
971                 d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
972                 w = xa > xa0 ? *--xa : 0;
973                 y = xa > xa0 ? *--xa : 0;
974                 d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
975                 goto ret_d;
976         }
977         z = xa > xa0 ? *--xa : 0;
978         w = xa > xa0 ? *--xa : 0;
979         k -= Ebits + 16;
980         d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
981         y = xa > xa0 ? *--xa : 0;
982         d1 = w << k + 16 | y << k;
983 #endif
984  ret_d:
985 #ifdef VAX
986         word0(d) = d0 >> 16 | d0 << 16;
987         word1(d) = d1 >> 16 | d1 << 16;
988 #else
989 #undef d0
990 #undef d1
991 #endif
992         return d;
993 }
994
995  static Bigint *
996 d2b
997 #ifdef KR_headers
998         (d, e, bits) double d; int *e, *bits;
999 #else
1000         (double d, int *e, int *bits)
1001 #endif
1002 {
1003         Bigint *b;
1004         int de, i, k;
1005         unsigned long *x, y, z;
1006 #ifdef VAX
1007         unsigned long d0, d1;
1008         d0 = word0(d) >> 16 | word0(d) << 16;
1009         d1 = word1(d) >> 16 | word1(d) << 16;
1010 #else
1011 #define d0 word0(d)
1012 #define d1 word1(d)
1013 #endif
1014
1015 #ifdef Pack_32
1016         b = Balloc(1);
1017 #else
1018         b = Balloc(2);
1019 #endif
1020         x = b->x;
1021
1022         z = d0 & Frac_mask;
1023         d0 &= 0x7fffffff;       /* clear sign bit, which we ignore */
1024 #ifdef Sudden_Underflow
1025         de = (int)(d0 >> Exp_shift);
1026 #ifndef IBM
1027         z |= Exp_msk11;
1028 #endif
1029 #else
1030         if ( (de = (int)(d0 >> Exp_shift)) )
1031                 z |= Exp_msk1;
1032 #endif
1033 #ifdef Pack_32
1034         if ( (y = d1) ) {
1035                 if ( (k = lo0bits(&y)) ) {
1036                         x[0] = y | (z << (32 - k));
1037                         z >>= k;
1038                         }
1039                 else
1040                         x[0] = y;
1041                 i = b->wds = (x[1] = z) ? 2 : 1;
1042         } else {
1043 #ifdef DEBUG
1044                 if (!z)
1045                         Bug("Zero passed to d2b");
1046 #endif
1047                 k = lo0bits(&z);
1048                 x[0] = z;
1049                 i = b->wds = 1;
1050                 k += 32;
1051         }
1052 #else
1053         if (y = d1) {
1054                 if (k = lo0bits(&y))
1055                         if (k >= 16) {
1056                                 x[0] = y | z << 32 - k & 0xffff;
1057                                 x[1] = z >> k - 16 & 0xffff;
1058                                 x[2] = z >> k;
1059                                 i = 2;
1060                         } else {
1061                                 x[0] = y & 0xffff;
1062                                 x[1] = y >> 16 | z << 16 - k & 0xffff;
1063                                 x[2] = z >> k & 0xffff;
1064                                 x[3] = z >> k+16;
1065                                 i = 3;
1066                         }
1067                 else {
1068                         x[0] = y & 0xffff;
1069                         x[1] = y >> 16;
1070                         x[2] = z & 0xffff;
1071                         x[3] = z >> 16;
1072                         i = 3;
1073                 }
1074         } else {
1075 #ifdef DEBUG
1076                 if (!z)
1077                         Bug("Zero passed to d2b");
1078 #endif
1079                 k = lo0bits(&z);
1080                 if (k >= 16) {
1081                         x[0] = z;
1082                         i = 0;
1083                 } else {
1084                         x[0] = z & 0xffff;
1085                         x[1] = z >> 16;
1086                         i = 1;
1087                 }
1088                 k += 32;
1089         }
1090         while (!x[i])
1091                 --i;
1092         b->wds = i + 1;
1093 #endif
1094 #ifndef Sudden_Underflow
1095         if (de) {
1096 #endif
1097 #ifdef IBM
1098                 *e = (de - Bias - (P-1) << 2) + k;
1099                 *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
1100 #else
1101                 *e = de - Bias - (P-1) + k;
1102                 *bits = P - k;
1103 #endif
1104 #ifndef Sudden_Underflow
1105         } else {
1106                 *e = de - Bias - (P-1) + 1 + k;
1107 #ifdef Pack_32
1108                 *bits = 32*i - hi0bits(x[i-1]);
1109 #else
1110                 *bits = (i+2)*16 - hi0bits(x[i]);
1111 #endif
1112         }
1113 #endif
1114         return b;
1115 }
1116 #undef d0
1117 #undef d1
1118
1119  static double
1120 ratio
1121 #ifdef KR_headers
1122         (a, b) Bigint *a, *b;
1123 #else
1124         (Bigint *a, Bigint *b)
1125 #endif
1126 {
1127         double da, db;
1128         int k, ka, kb;
1129
1130         da = b2d(a, &ka);
1131         db = b2d(b, &kb);
1132 #ifdef Pack_32
1133         k = ka - kb + 32*(a->wds - b->wds);
1134 #else
1135         k = ka - kb + 16*(a->wds - b->wds);
1136 #endif
1137 #ifdef IBM
1138         if (k > 0) {
1139                 word0(da) += (k >> 2)*Exp_msk1;
1140                 if (k &= 3)
1141                         da *= 1 << k;
1142         } else {
1143                 k = -k;
1144                 word0(db) += (k >> 2)*Exp_msk1;
1145                 if (k &= 3)
1146                         db *= 1 << k;
1147         }
1148 #else
1149         if (k > 0)
1150                 word0(da) += k*Exp_msk1;
1151         else {
1152                 k = -k;
1153                 word0(db) += k*Exp_msk1;
1154         }
1155 #endif
1156         return da / db;
1157 }
1158
1159  static double
1160 tens[] = {
1161                 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1162                 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1163                 1e20, 1e21, 1e22
1164 #ifdef VAX
1165                 , 1e23, 1e24
1166 #endif
1167                 };
1168
1169  static double
1170 #ifdef IEEE_Arith
1171 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1172 static double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
1173 #define n_bigtens 5
1174 #else
1175 #ifdef IBM
1176 bigtens[] = { 1e16, 1e32, 1e64 };
1177 static double tinytens[] = { 1e-16, 1e-32, 1e-64 };
1178 #define n_bigtens 3
1179 #else
1180 bigtens[] = { 1e16, 1e32 };
1181 static double tinytens[] = { 1e-16, 1e-32 };
1182 #define n_bigtens 2
1183 #endif
1184 #endif
1185
1186  double
1187 strtod
1188 #ifdef KR_headers
1189         (s00, se) CONST char *s00; char **se;
1190 #else
1191         (CONST char *s00, char **se)
1192 #endif
1193 {
1194         int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
1195                  e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1196         CONST char *s, *s0, *s1;
1197         double aadj, aadj1, adj, rv, rv0;
1198         long L;
1199         unsigned long y, z;
1200         Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
1201         char decimal_point = localeconv()->decimal_point[0];
1202
1203         sign = nz0 = nz = 0;
1204         rv = 0.;
1205         for (s = s00;;s++) switch(*s) {
1206                 case '-':
1207                         sign = 1;
1208                         /* no break */
1209                 case '+':
1210                         if (*++s)
1211                                 goto break2;
1212                         /* no break */
1213                 case 0:
1214                         s = s00;
1215                         goto ret;
1216                 default:
1217                         if (isspace((unsigned char)*s))
1218                                 continue;
1219                         goto break2;
1220         }
1221  break2:
1222         if (*s == '0') {
1223                 nz0 = 1;
1224                 while (*++s == '0') ;
1225                 if (!*s)
1226                         goto ret;
1227         }
1228         s0 = s;
1229         y = z = 0;
1230         for (nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
1231                 if (nd < 9)
1232                         y = 10*y + c - '0';
1233                 else if (nd < 16)
1234                         z = 10*z + c - '0';
1235         nd0 = nd;
1236         if ((char)c == decimal_point) {
1237                 c = *++s;
1238                 if (!nd) {
1239                         for (; c == '0'; c = *++s)
1240                                 nz++;
1241                         if (c > '0' && c <= '9') {
1242                                 s0 = s;
1243                                 nf += nz;
1244                                 nz = 0;
1245                                 goto have_dig;
1246                         }
1247                         goto dig_done;
1248                 }
1249                 for (; c >= '0' && c <= '9'; c = *++s) {
1250  have_dig:
1251                         nz++;
1252                         if (c -= '0') {
1253                                 nf += nz;
1254                                 for (i = 1; i < nz; i++)
1255                                         if (nd++ < 9)
1256                                                 y *= 10;
1257                                         else if (nd <= DBL_DIG + 1)
1258                                                 z *= 10;
1259                                 if (nd++ < 9)
1260                                         y = 10*y + c;
1261                                 else if (nd <= DBL_DIG + 1)
1262                                         z = 10*z + c;
1263                                 nz = 0;
1264                         }
1265                 }
1266         }
1267  dig_done:
1268         e = 0;
1269         if (c == 'e' || c == 'E') {
1270                 if (!nd && !nz && !nz0) {
1271                         s = s00;
1272                         goto ret;
1273                 }
1274                 s00 = s;
1275                 esign = 0;
1276                 switch(c = *++s) {
1277                         case '-':
1278                                 esign = 1;
1279                         case '+':
1280                                 c = *++s;
1281                 }
1282                 if (c >= '0' && c <= '9') {
1283                         while (c == '0')
1284                                 c = *++s;
1285                         if (c > '0' && c <= '9') {
1286                                 L = c - '0';
1287                                 s1 = s;
1288                                 while ((c = *++s) >= '0' && c <= '9')
1289                                         L = 10*L + c - '0';
1290                                 if (s - s1 > 8 || L > 19999)
1291                                         /* Avoid confusion from exponents
1292                                          * so large that e might overflow.
1293                                          */
1294                                         e = 19999; /* safe for 16 bit ints */
1295                                 else
1296                                         e = (int)L;
1297                                 if (esign)
1298                                         e = -e;
1299                         } else
1300                                 e = 0;
1301                 } else
1302                         s = s00;
1303         }
1304         if (!nd) {
1305                 if (!nz && !nz0)
1306                         s = s00;
1307                 goto ret;
1308         }
1309         e1 = e -= nf;
1310
1311         /* Now we have nd0 digits, starting at s0, followed by a
1312          * decimal point, followed by nd-nd0 digits.  The number we're
1313          * after is the integer represented by those digits times
1314          * 10**e */
1315
1316         if (!nd0)
1317                 nd0 = nd;
1318         k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1319         rv = y;
1320         if (k > 9)
1321                 rv = tens[k - 9] * rv + z;
1322         if (nd <= DBL_DIG
1323 #ifndef RND_PRODQUOT
1324                 && FLT_ROUNDS == 1
1325 #endif
1326                         ) {
1327                 if (!e)
1328                         goto ret;
1329                 if (e > 0) {
1330                         if (e <= Ten_pmax) {
1331 #ifdef VAX
1332                                 goto vax_ovfl_check;
1333 #else
1334                                 /* rv = */ rounded_product(rv, tens[e]);
1335                                 goto ret;
1336 #endif
1337                                 }
1338                         i = DBL_DIG - nd;
1339                         if (e <= Ten_pmax + i) {
1340                                 /* A fancier test would sometimes let us do
1341                                  * this for larger i values.
1342                                  */
1343                                 e -= i;
1344                                 rv *= tens[i];
1345 #ifdef VAX
1346                                 /* VAX exponent range is so narrow we must
1347                                  * worry about overflow here...
1348                                  */
1349  vax_ovfl_check:
1350                                 word0(rv) -= P*Exp_msk1;
1351                                 /* rv = */ rounded_product(rv, tens[e]);
1352                                 if ((word0(rv) & Exp_mask)
1353                                  > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
1354                                         goto ovfl;
1355                                 word0(rv) += P*Exp_msk1;
1356 #else
1357                                 /* rv = */ rounded_product(rv, tens[e]);
1358 #endif
1359                                 goto ret;
1360                         }
1361                 }
1362 #ifndef Inaccurate_Divide
1363                 else if (e >= -Ten_pmax) {
1364                         /* rv = */ rounded_quotient(rv, tens[-e]);
1365                         goto ret;
1366                 }
1367 #endif
1368         }
1369         e1 += nd - k;
1370
1371         /* Get starting approximation = rv * 10**e1 */
1372
1373         if (e1 > 0) {
1374                 if ( (i = e1 & 15) )
1375                         rv *= tens[i];
1376                 if ( (e1 &= ~15) ) {
1377                         if (e1 > DBL_MAX_10_EXP) {
1378  ovfl:
1379                                 errno = ERANGE;
1380 #ifdef __STDC__
1381                                 rv = HUGE_VAL;
1382 #else
1383                                 /* Can't trust HUGE_VAL */
1384 #ifdef IEEE_Arith
1385                                 word0(rv) = Exp_mask;
1386                                 word1(rv) = 0;
1387 #else
1388                                 word0(rv) = Big0;
1389                                 word1(rv) = Big1;
1390 #endif
1391 #endif
1392                                 goto ret;
1393                         }
1394                         if (e1 >>= 4) {
1395                                 for (j = 0; e1 > 1; j++, e1 >>= 1)
1396                                         if (e1 & 1)
1397                                                 rv *= bigtens[j];
1398                         /* The last multiplication could overflow. */
1399                                 word0(rv) -= P*Exp_msk1;
1400                                 rv *= bigtens[j];
1401                                 if ((z = word0(rv) & Exp_mask)
1402                                  > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1403                                         goto ovfl;
1404                                 if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1405                                         /* set to largest number */
1406                                         /* (Can't trust DBL_MAX) */
1407                                         word0(rv) = Big0;
1408                                         word1(rv) = Big1;
1409                                         }
1410                                 else
1411                                         word0(rv) += P*Exp_msk1;
1412                         }
1413                 }
1414         } else if (e1 < 0) {
1415                 e1 = -e1;
1416                 if ( (i = e1 & 15) )
1417                         rv /= tens[i];
1418                 if ( (e1 &= ~15) ) {
1419                         e1 >>= 4;
1420                         for (j = 0; e1 > 1; j++, e1 >>= 1)
1421                                 if (e1 & 1)
1422                                         rv *= tinytens[j];
1423                         /* The last multiplication could underflow. */
1424                         rv0 = rv;
1425                         rv *= tinytens[j];
1426                         if (!rv) {
1427                                 rv = 2.*rv0;
1428                                 rv *= tinytens[j];
1429                                 if (!rv) {
1430  undfl:
1431                                         rv = 0.;
1432                                         errno = ERANGE;
1433                                         goto ret;
1434                                         }
1435                                 word0(rv) = Tiny0;
1436                                 word1(rv) = Tiny1;
1437                                 /* The refinement below will clean
1438                                  * this approximation up.
1439                                  */
1440                         }
1441                 }
1442         }
1443
1444         /* Now the hard part -- adjusting rv to the correct value.*/
1445
1446         /* Put digits into bd: true value = bd * 10^e */
1447
1448         bd0 = s2b(s0, nd0, nd, y);
1449
1450         for (;;) {
1451                 bd = Balloc(bd0->k);
1452                 Bcopy(bd, bd0);
1453                 bb = d2b(rv, &bbe, &bbbits);    /* rv = bb * 2^bbe */
1454                 bs = i2b(1);
1455
1456                 if (e >= 0) {
1457                         bb2 = bb5 = 0;
1458                         bd2 = bd5 = e;
1459                 } else {
1460                         bb2 = bb5 = -e;
1461                         bd2 = bd5 = 0;
1462                 }
1463                 if (bbe >= 0)
1464                         bb2 += bbe;
1465                 else
1466                         bd2 -= bbe;
1467                 bs2 = bb2;
1468 #ifdef Sudden_Underflow
1469 #ifdef IBM
1470                 j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
1471 #else
1472                 j = P + 1 - bbbits;
1473 #endif
1474 #else
1475                 i = bbe + bbbits - 1;   /* logb(rv) */
1476                 if (i < Emin)   /* denormal */
1477                         j = bbe + (P-Emin);
1478                 else
1479                         j = P + 1 - bbbits;
1480 #endif
1481                 bb2 += j;
1482                 bd2 += j;
1483                 i = bb2 < bd2 ? bb2 : bd2;
1484                 if (i > bs2)
1485                         i = bs2;
1486                 if (i > 0) {
1487                         bb2 -= i;
1488                         bd2 -= i;
1489                         bs2 -= i;
1490                         }
1491                 if (bb5 > 0) {
1492                         bs = pow5mult(bs, bb5);
1493                         bb1 = mult(bs, bb);
1494                         Bfree(bb);
1495                         bb = bb1;
1496                         }
1497                 if (bb2 > 0)
1498                         bb = lshift(bb, bb2);
1499                 if (bd5 > 0)
1500                         bd = pow5mult(bd, bd5);
1501                 if (bd2 > 0)
1502                         bd = lshift(bd, bd2);
1503                 if (bs2 > 0)
1504                         bs = lshift(bs, bs2);
1505                 delta = diff(bb, bd);
1506                 dsign = delta->sign;
1507                 delta->sign = 0;
1508                 i = cmp(delta, bs);
1509                 if (i < 0) {
1510                         /* Error is less than half an ulp -- check for
1511                          * special case of mantissa a power of two.
1512                          */
1513                         if (dsign || word1(rv) || word0(rv) & Bndry_mask)
1514                                 break;
1515                         delta = lshift(delta,Log2P);
1516                         if (cmp(delta, bs) > 0)
1517                                 goto drop_down;
1518                         break;
1519                 }
1520                 if (i == 0) {
1521                         /* exactly half-way between */
1522                         if (dsign) {
1523                                 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
1524                                  &&  word1(rv) == 0xffffffff) {
1525                                         /*boundary case -- increment exponent*/
1526                                         word0(rv) = (word0(rv) & Exp_mask)
1527                                                 + Exp_msk1
1528 #ifdef IBM
1529                                                 | Exp_msk1 >> 4
1530 #endif
1531                                                 ;
1532                                         word1(rv) = 0;
1533                                         break;
1534                                 }
1535                         } else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
1536  drop_down:
1537                                 /* boundary case -- decrement exponent */
1538 #ifdef Sudden_Underflow
1539                                 L = word0(rv) & Exp_mask;
1540 #ifdef IBM
1541                                 if (L <  Exp_msk1)
1542 #else
1543                                 if (L <= Exp_msk1)
1544 #endif
1545                                         goto undfl;
1546                                 L -= Exp_msk1;
1547 #else
1548                                 L = (word0(rv) & Exp_mask) - Exp_msk1;
1549 #endif
1550                                 word0(rv) = L | Bndry_mask1;
1551                                 word1(rv) = 0xffffffff;
1552 #ifdef IBM
1553                                 goto cont;
1554 #else
1555                                 break;
1556 #endif
1557                         }
1558 #ifndef ROUND_BIASED
1559                         if (!(word1(rv) & LSB))
1560                                 break;
1561 #endif
1562                         if (dsign)
1563                                 rv += ulp(rv);
1564 #ifndef ROUND_BIASED
1565                         else {
1566                                 rv -= ulp(rv);
1567 #ifndef Sudden_Underflow
1568                                 if (!rv)
1569                                         goto undfl;
1570 #endif
1571                         }
1572 #endif
1573                         break;
1574                 }
1575                 if ((aadj = ratio(delta, bs)) <= 2.) {
1576                         if (dsign)
1577                                 aadj = aadj1 = 1.;
1578                         else if (word1(rv) || word0(rv) & Bndry_mask) {
1579 #ifndef Sudden_Underflow
1580                                 if (word1(rv) == Tiny1 && !word0(rv))
1581                                         goto undfl;
1582 #endif
1583                                 aadj = 1.;
1584                                 aadj1 = -1.;
1585                         } else {
1586                                 /* special case -- power of FLT_RADIX to be */
1587                                 /* rounded down... */
1588
1589                                 if (aadj < 2./FLT_RADIX)
1590                                         aadj = 1./FLT_RADIX;
1591                                 else
1592                                         aadj *= 0.5;
1593                                 aadj1 = -aadj;
1594                         }
1595                 } else {
1596                         aadj *= 0.5;
1597                         aadj1 = dsign ? aadj : -aadj;
1598 #ifdef Check_FLT_ROUNDS
1599                         switch(FLT_ROUNDS) {
1600                                 case 2: /* towards +infinity */
1601                                         aadj1 -= 0.5;
1602                                         break;
1603                                 case 0: /* towards 0 */
1604                                 case 3: /* towards -infinity */
1605                                         aadj1 += 0.5;
1606                         }
1607 #else
1608                         if (FLT_ROUNDS == 0)
1609                                 aadj1 += 0.5;
1610 #endif
1611                 }
1612                 y = word0(rv) & Exp_mask;
1613
1614                 /* Check for overflow */
1615
1616                 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
1617                         rv0 = rv;
1618                         word0(rv) -= P*Exp_msk1;
1619                         adj = aadj1 * ulp(rv);
1620                         rv += adj;
1621                         if ((word0(rv) & Exp_mask) >=
1622                                         Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
1623                                 if (word0(rv0) == Big0 && word1(rv0) == Big1)
1624                                         goto ovfl;
1625                                 word0(rv) = Big0;
1626                                 word1(rv) = Big1;
1627                                 goto cont;
1628                         } else
1629                                 word0(rv) += P*Exp_msk1;
1630                 } else {
1631 #ifdef Sudden_Underflow
1632                         if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
1633                                 rv0 = rv;
1634                                 word0(rv) += P*Exp_msk1;
1635                                 adj = aadj1 * ulp(rv);
1636                                 rv += adj;
1637 #ifdef IBM
1638                                 if ((word0(rv) & Exp_mask) <  P*Exp_msk1)
1639 #else
1640                                 if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
1641 #endif
1642                                 {
1643                                         if (word0(rv0) == Tiny0
1644                                          && word1(rv0) == Tiny1)
1645                                                 goto undfl;
1646                                         word0(rv) = Tiny0;
1647                                         word1(rv) = Tiny1;
1648                                         goto cont;
1649                                 } else
1650                                         word0(rv) -= P*Exp_msk1;
1651                         } else {
1652                                 adj = aadj1 * ulp(rv);
1653                                 rv += adj;
1654                         }
1655 #else
1656                         /* Compute adj so that the IEEE rounding rules will
1657                          * correctly round rv + adj in some half-way cases.
1658                          * If rv * ulp(rv) is denormalized (i.e.,
1659                          * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
1660                          * trouble from bits lost to denormalization;
1661                          * example: 1.2e-307 .
1662                          */
1663                         if (y <= (P-1)*Exp_msk1 && aadj >= 1.) {
1664                                 aadj1 = (double)(int)(aadj + 0.5);
1665                                 if (!dsign)
1666                                         aadj1 = -aadj1;
1667                         }
1668                         adj = aadj1 * ulp(rv);
1669                         rv += adj;
1670 #endif
1671                 }
1672                 z = word0(rv) & Exp_mask;
1673                 if (y == z) {
1674                         /* Can we stop now? */
1675                         L = aadj;
1676                         aadj -= L;
1677                         /* The tolerances below are conservative. */
1678                         if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
1679                                 if (aadj < .4999999 || aadj > .5000001)
1680                                         break;
1681                         } else if (aadj < .4999999/FLT_RADIX)
1682                                 break;
1683                 }
1684  cont:
1685                 Bfree(bb);
1686                 Bfree(bd);
1687                 Bfree(bs);
1688                 Bfree(delta);
1689         }
1690         Bfree(bb);
1691         Bfree(bd);
1692         Bfree(bs);
1693         Bfree(bd0);
1694         Bfree(delta);
1695  ret:
1696         if (se)
1697                 *se = (char *)s;
1698         return sign ? -rv : rv;
1699 }
1700
1701  static int
1702 quorem
1703 #ifdef KR_headers
1704         (b, S) Bigint *b, *S;
1705 #else
1706         (Bigint *b, Bigint *S)
1707 #endif
1708 {
1709         int n;
1710         long borrow, y;
1711         unsigned long carry, q, ys;
1712         unsigned long *bx, *bxe, *sx, *sxe;
1713 #ifdef Pack_32
1714         long z;
1715         unsigned long si, zs;
1716 #endif
1717
1718         n = S->wds;
1719 #ifdef DEBUG
1720         /*debug*/ if (b->wds > n)
1721         /*debug*/       Bug("oversize b in quorem");
1722 #endif
1723         if (b->wds < n)
1724                 return 0;
1725         sx = S->x;
1726         sxe = sx + --n;
1727         bx = b->x;
1728         bxe = bx + n;
1729         q = *bxe / (*sxe + 1);  /* ensure q <= true quotient */
1730 #ifdef DEBUG
1731         /*debug*/ if (q > 9)
1732         /*debug*/       Bug("oversized quotient in quorem");
1733 #endif
1734         if (q) {
1735                 borrow = 0;
1736                 carry = 0;
1737                 do {
1738 #ifdef Pack_32
1739                         si = *sx++;
1740                         ys = (si & 0xffff) * q + carry;
1741                         zs = (si >> 16) * q + (ys >> 16);
1742                         carry = zs >> 16;
1743                         y = (*bx & 0xffff) - (ys & 0xffff) + borrow;
1744                         borrow = y >> 16;
1745                         Sign_Extend(borrow, y);
1746                         z = (*bx >> 16) - (zs & 0xffff) + borrow;
1747                         borrow = z >> 16;
1748                         Sign_Extend(borrow, z);
1749                         Storeinc(bx, z, y);
1750 #else
1751                         ys = *sx++ * q + carry;
1752                         carry = ys >> 16;
1753                         y = *bx - (ys & 0xffff) + borrow;
1754                         borrow = y >> 16;
1755                         Sign_Extend(borrow, y);
1756                         *bx++ = y & 0xffff;
1757 #endif
1758                 } while (sx <= sxe);
1759                 if (!*bxe) {
1760                         bx = b->x;
1761                         while (--bxe > bx && !*bxe)
1762                                 --n;
1763                         b->wds = n;
1764                 }
1765         }
1766         if (cmp(b, S) >= 0) {
1767                 q++;
1768                 borrow = 0;
1769                 carry = 0;
1770                 bx = b->x;
1771                 sx = S->x;
1772                 do {
1773 #ifdef Pack_32
1774                         si = *sx++;
1775                         ys = (si & 0xffff) + carry;
1776                         zs = (si >> 16) + (ys >> 16);
1777                         carry = zs >> 16;
1778                         y = (*bx & 0xffff) - (ys & 0xffff) + borrow;
1779                         borrow = y >> 16;
1780                         Sign_Extend(borrow, y);
1781                         z = (*bx >> 16) - (zs & 0xffff) + borrow;
1782                         borrow = z >> 16;
1783                         Sign_Extend(borrow, z);
1784                         Storeinc(bx, z, y);
1785 #else
1786                         ys = *sx++ + carry;
1787                         carry = ys >> 16;
1788                         y = *bx - (ys & 0xffff) + borrow;
1789                         borrow = y >> 16;
1790                         Sign_Extend(borrow, y);
1791                         *bx++ = y & 0xffff;
1792 #endif
1793                 } while (sx <= sxe);
1794                 bx = b->x;
1795                 bxe = bx + n;
1796                 if (!*bxe) {
1797                         while (--bxe > bx && !*bxe)
1798                                 --n;
1799                         b->wds = n;
1800                 }
1801         }
1802         return q;
1803 }
1804
1805 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
1806  *
1807  * Inspired by "How to Print Floating-Point Numbers Accurately" by
1808  * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 92-101].
1809  *
1810  * Modifications:
1811  *      1. Rather than iterating, we use a simple numeric overestimate
1812  *         to determine k = floor(log10(d)).  We scale relevant
1813  *         quantities using O(log2(k)) rather than O(k) multiplications.
1814  *      2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
1815  *         try to generate digits strictly left to right.  Instead, we
1816  *         compute with fewer bits and propagate the carry if necessary
1817  *         when rounding the final digit up.  This is often faster.
1818  *      3. Under the assumption that input will be rounded nearest,
1819  *         mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
1820  *         That is, we allow equality in stopping tests when the
1821  *         round-nearest rule will give the same floating-point value
1822  *         as would satisfaction of the stopping test with strict
1823  *         inequality.
1824  *      4. We remove common factors of powers of 2 from relevant
1825  *         quantities.
1826  *      5. When converting floating-point integers less than 1e16,
1827  *         we use floating-point arithmetic rather than resorting
1828  *         to multiple-precision integers.
1829  *      6. When asked to produce fewer than 15 digits, we first try
1830  *         to get by with floating-point arithmetic; we resort to
1831  *         multiple-precision integer arithmetic only if we cannot
1832  *         guarantee that the floating-point calculation has given
1833  *         the correctly rounded result.  For k requested digits and
1834  *         "uniformly" distributed input, the probability is
1835  *         something like 10^(k-15) that we must resort to the long
1836  *         calculation.
1837  */
1838
1839 char *
1840 __dtoa
1841 #ifdef KR_headers
1842         (d, mode, ndigits, decpt, sign, rve, resultp)
1843         double d; int mode, ndigits, *decpt, *sign; char **rve, **resultp;
1844 #else
1845         (double d, int mode, int ndigits, int *decpt, int *sign, char **rve,
1846          char **resultp)
1847 #endif
1848 {
1849  /*     Arguments ndigits, decpt, sign are similar to those
1850         of ecvt and fcvt; trailing zeros are suppressed from
1851         the returned string.  If not null, *rve is set to point
1852         to the end of the return value.  If d is +-Infinity or NaN,
1853         then *decpt is set to 9999.
1854
1855         mode:
1856                 0 ==> shortest string that yields d when read in
1857                         and rounded to nearest.
1858                 1 ==> like 0, but with Steele & White stopping rule;
1859                         e.g. with IEEE P754 arithmetic , mode 0 gives
1860                         1e23 whereas mode 1 gives 9.999999999999999e22.
1861                 2 ==> max(1,ndigits) significant digits.  This gives a
1862                         return value similar to that of ecvt, except
1863                         that trailing zeros are suppressed.
1864                 3 ==> through ndigits past the decimal point.  This
1865                         gives a return value similar to that from fcvt,
1866                         except that trailing zeros are suppressed, and
1867                         ndigits can be negative.
1868                 4-9 should give the same return values as 2-3, i.e.,
1869                         4 <= mode <= 9 ==> same return as mode
1870                         2 + (mode & 1).  These modes are mainly for
1871                         debugging; often they run slower but sometimes
1872                         faster than modes 2-3.
1873                 4,5,8,9 ==> left-to-right digit generation.
1874                 6-9 ==> don't try fast floating-point estimate
1875                         (if applicable).
1876
1877                 Values of mode other than 0-9 are treated as mode 0.
1878
1879                 Sufficient space is allocated to the return value
1880                 to hold the suppressed trailing zeros.
1881         */
1882
1883         int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
1884                 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
1885                 spec_case, try_quick;
1886         long L;
1887 #ifndef Sudden_Underflow
1888         int denorm;
1889         unsigned long x;
1890 #endif
1891         Bigint *b, *b1, *delta, *mlo, *mhi, *S;
1892         double d2, ds, eps;
1893         char *s, *s0;
1894
1895         if (word0(d) & Sign_bit) {
1896                 /* set sign for everything, including 0's and NaNs */
1897                 *sign = 1;
1898                 word0(d) &= ~Sign_bit;  /* clear sign bit */
1899         }
1900         else
1901                 *sign = 0;
1902
1903 #if defined(IEEE_Arith) + defined(VAX)
1904 #ifdef IEEE_Arith
1905         if ((word0(d) & Exp_mask) == Exp_mask)
1906 #else
1907         if (word0(d)  == 0x8000)
1908 #endif
1909         {
1910                 /* Infinity or NaN */
1911                 *decpt = 9999;
1912                 s =
1913 #ifdef IEEE_Arith
1914                         !word1(d) && !(word0(d) & 0xfffff) ? "Infinity" :
1915 #endif
1916                                 "NaN";
1917                 if (rve)
1918                         *rve =
1919 #ifdef IEEE_Arith
1920                                 s[3] ? s + 8 :
1921 #endif
1922                                                 s + 3;
1923                 return s;
1924         }
1925 #endif
1926 #ifdef IBM
1927         d += 0; /* normalize */
1928 #endif
1929         if (!d) {
1930                 *decpt = 1;
1931                 s = "0";
1932                 if (rve)
1933                         *rve = s + 1;
1934                 return s;
1935         }
1936
1937         b = d2b(d, &be, &bbits);
1938 #ifdef Sudden_Underflow
1939         i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
1940 #else
1941         if ( (i = (int)((word0(d) >> Exp_shift1) & (Exp_mask>>Exp_shift1))) ) {
1942 #endif
1943                 d2 = d;
1944                 word0(d2) &= Frac_mask1;
1945                 word0(d2) |= Exp_11;
1946 #ifdef IBM
1947                 if ( (j = 11 - hi0bits(word0(d2) & Frac_mask)) )
1948                         d2 /= 1 << j;
1949 #endif
1950
1951                 /* log(x)       ~=~ log(1.5) + (x-1.5)/1.5
1952                  * log10(x)      =  log(x) / log(10)
1953                  *              ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
1954                  * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
1955                  *
1956                  * This suggests computing an approximation k to log10(d) by
1957                  *
1958                  * k = (i - Bias)*0.301029995663981
1959                  *      + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
1960                  *
1961                  * We want k to be too large rather than too small.
1962                  * The error in the first-order Taylor series approximation
1963                  * is in our favor, so we just round up the constant enough
1964                  * to compensate for any error in the multiplication of
1965                  * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
1966                  * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
1967                  * adding 1e-13 to the constant term more than suffices.
1968                  * Hence we adjust the constant term to 0.1760912590558.
1969                  * (We could get a more accurate k by invoking log10,
1970                  *  but this is probably not worthwhile.)
1971                  */
1972
1973                 i -= Bias;
1974 #ifdef IBM
1975                 i <<= 2;
1976                 i += j;
1977 #endif
1978 #ifndef Sudden_Underflow
1979                 denorm = 0;
1980         } else {
1981                 /* d is denormalized */
1982
1983                 i = bbits + be + (Bias + (P-1) - 1);
1984                 x = i > 32  ? ((word0(d) << (64 - i)) | (word1(d) >> (i - 32)))
1985                             : (word1(d) << (32 - i));
1986                 d2 = x;
1987                 word0(d2) -= 31*Exp_msk1; /* adjust exponent */
1988                 i -= (Bias + (P-1) - 1) + 1;
1989                 denorm = 1;
1990         }
1991 #endif
1992         ds = (d2-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
1993         k = (int)ds;
1994         if (ds < 0. && ds != k)
1995                 k--;    /* want k = floor(ds) */
1996         k_check = 1;
1997         if (k >= 0 && k <= Ten_pmax) {
1998                 if (d < tens[k])
1999                         k--;
2000                 k_check = 0;
2001         }
2002         j = bbits - i - 1;
2003         if (j >= 0) {
2004                 b2 = 0;
2005                 s2 = j;
2006         } else {
2007                 b2 = -j;
2008                 s2 = 0;
2009         }
2010         if (k >= 0) {
2011                 b5 = 0;
2012                 s5 = k;
2013                 s2 += k;
2014         } else {
2015                 b2 -= k;
2016                 b5 = -k;
2017                 s5 = 0;
2018         }
2019         if (mode < 0 || mode > 9)
2020                 mode = 0;
2021         try_quick = 1;
2022         if (mode > 5) {
2023                 mode -= 4;
2024                 try_quick = 0;
2025         }
2026         leftright = 1;
2027         switch(mode) {
2028                 case 0:
2029                 case 1:
2030                         ilim = ilim1 = -1;
2031                         i = 18;
2032                         ndigits = 0;
2033                         break;
2034                 case 2:
2035                         leftright = 0;
2036                         /* no break */
2037                 case 4:
2038                         if (ndigits <= 0)
2039                                 ndigits = 1;
2040                         ilim = ilim1 = i = ndigits;
2041                         break;
2042                 case 3:
2043                         leftright = 0;
2044                         /* no break */
2045                 case 5:
2046                         i = ndigits + k + 1;
2047                         ilim = i;
2048                         ilim1 = i - 1;
2049                         if (i <= 0)
2050                                 i = 1;
2051         }
2052         *resultp = (char *) malloc(i + 1);
2053         s = s0 = *resultp;
2054
2055         if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2056
2057                 /* Try to get by with floating-point arithmetic. */
2058
2059                 i = 0;
2060                 d2 = d;
2061                 k0 = k;
2062                 ilim0 = ilim;
2063                 ieps = 2; /* conservative */
2064                 if (k > 0) {
2065                         ds = tens[k&0xf];
2066                         j = k >> 4;
2067                         if (j & Bletch) {
2068                                 /* prevent overflows */
2069                                 j &= Bletch - 1;
2070                                 d /= bigtens[n_bigtens-1];
2071                                 ieps++;
2072                         }
2073                         for (; j; j >>= 1, i++)
2074                                 if (j & 1) {
2075                                         ieps++;
2076                                         ds *= bigtens[i];
2077                                 }
2078                         d /= ds;
2079                 } else if ( (j1 = -k) ) {
2080                         d *= tens[j1 & 0xf];
2081                         for (j = j1 >> 4; j; j >>= 1, i++)
2082                                 if (j & 1) {
2083                                         ieps++;
2084                                         d *= bigtens[i];
2085                                 }
2086                 }
2087                 if (k_check && d < 1. && ilim > 0) {
2088                         if (ilim1 <= 0)
2089                                 goto fast_failed;
2090                         ilim = ilim1;
2091                         k--;
2092                         d *= 10.;
2093                         ieps++;
2094                 }
2095                 eps = ieps*d + 7.;
2096                 word0(eps) -= (P-1)*Exp_msk1;
2097                 if (ilim == 0) {
2098                         S = mhi = 0;
2099                         d -= 5.;
2100                         if (d > eps)
2101                                 goto one_digit;
2102                         if (d < -eps)
2103                                 goto no_digits;
2104                         goto fast_failed;
2105                 }
2106 #ifndef No_leftright
2107                 if (leftright) {
2108                         /* Use Steele & White method of only
2109                          * generating digits needed.
2110                          */
2111                         eps = 0.5/tens[ilim-1] - eps;
2112                         for (i = 0;;) {
2113                                 L = d;
2114                                 d -= L;
2115                                 *s++ = '0' + (int)L;
2116                                 if (d < eps)
2117                                         goto ret1;
2118                                 if (1. - d < eps)
2119                                         goto bump_up;
2120                                 if (++i >= ilim)
2121                                         break;
2122                                 eps *= 10.;
2123                                 d *= 10.;
2124                         }
2125                 } else {
2126 #endif
2127                         /* Generate ilim digits, then fix them up. */
2128                         eps *= tens[ilim-1];
2129                         for (i = 1;; i++, d *= 10.) {
2130                                 L = d;
2131                                 d -= L;
2132                                 *s++ = '0' + (int)L;
2133                                 if (i == ilim) {
2134                                         if (d > 0.5 + eps)
2135                                                 goto bump_up;
2136                                         else if (d < 0.5 - eps) {
2137                                                 while (*--s == '0');
2138                                                 s++;
2139                                                 goto ret1;
2140                                         }
2141                                         break;
2142                                 }
2143                         }
2144 #ifndef No_leftright
2145                 }
2146 #endif
2147  fast_failed:
2148                 s = s0;
2149                 d = d2;
2150                 k = k0;
2151                 ilim = ilim0;
2152         }
2153
2154         /* Do we have a "small" integer? */
2155
2156         if (be >= 0 && k <= Int_max) {
2157                 /* Yes. */
2158                 ds = tens[k];
2159                 if (ndigits < 0 && ilim <= 0) {
2160                         S = mhi = 0;
2161                         if (ilim < 0 || d <= 5*ds)
2162                                 goto no_digits;
2163                         goto one_digit;
2164                 }
2165                 for (i = 1;; i++) {
2166                         L = d / ds;
2167                         d -= L*ds;
2168 #ifdef Check_FLT_ROUNDS
2169                         /* If FLT_ROUNDS == 2, L will usually be high by 1 */
2170                         if (d < 0) {
2171                                 L--;
2172                                 d += ds;
2173                         }
2174 #endif
2175                         *s++ = '0' + (int)L;
2176                         if (i == ilim) {
2177                                 d += d;
2178                                 if (d > ds || (d == ds && L & 1)) {
2179  bump_up:
2180                                         while (*--s == '9')
2181                                                 if (s == s0) {
2182                                                         k++;
2183                                                         *s = '0';
2184                                                         break;
2185                                                 }
2186                                         ++*s++;
2187                                 }
2188                                 break;
2189                         }
2190                         if (!(d *= 10.))
2191                                 break;
2192                 }
2193                 goto ret1;
2194         }
2195
2196         m2 = b2;
2197         m5 = b5;
2198         mhi = mlo = 0;
2199         if (leftright) {
2200                 if (mode < 2) {
2201                         i =
2202 #ifndef Sudden_Underflow
2203                                 denorm ? be + (Bias + (P-1) - 1 + 1) :
2204 #endif
2205 #ifdef IBM
2206                                 1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
2207 #else
2208                                 1 + P - bbits;
2209 #endif
2210                 } else {
2211                         j = ilim - 1;
2212                         if (m5 >= j)
2213                                 m5 -= j;
2214                         else {
2215                                 s5 += j -= m5;
2216                                 b5 += j;
2217                                 m5 = 0;
2218                         }
2219                         if ((i = ilim) < 0) {
2220                                 m2 -= i;
2221                                 i = 0;
2222                         }
2223                 }
2224                 b2 += i;
2225                 s2 += i;
2226                 mhi = i2b(1);
2227         }
2228         if (m2 > 0 && s2 > 0) {
2229                 i = m2 < s2 ? m2 : s2;
2230                 b2 -= i;
2231                 m2 -= i;
2232                 s2 -= i;
2233         }
2234         if (b5 > 0) {
2235                 if (leftright) {
2236                         if (m5 > 0) {
2237                                 mhi = pow5mult(mhi, m5);
2238                                 b1 = mult(mhi, b);
2239                                 Bfree(b);
2240                                 b = b1;
2241                                 }
2242                         if ( (j = b5 - m5) )
2243                                 b = pow5mult(b, j);
2244                 } else
2245                         b = pow5mult(b, b5);
2246         }
2247         S = i2b(1);
2248         if (s5 > 0)
2249                 S = pow5mult(S, s5);
2250
2251         /* Check for special case that d is a normalized power of 2. */
2252
2253         if (mode < 2) {
2254                 if (!word1(d) && !(word0(d) & Bndry_mask)
2255 #ifndef Sudden_Underflow
2256                  && word0(d) & Exp_mask
2257 #endif
2258                                 ) {
2259                         /* The special case */
2260                         b2 += Log2P;
2261                         s2 += Log2P;
2262                         spec_case = 1;
2263                 } else
2264                         spec_case = 0;
2265         }
2266
2267         /* Arrange for convenient computation of quotients:
2268          * shift left if necessary so divisor has 4 leading 0 bits.
2269          *
2270          * Perhaps we should just compute leading 28 bits of S once
2271          * and for all and pass them and a shift to quorem, so it
2272          * can do shifts and ors to compute the numerator for q.
2273          */
2274 #ifdef Pack_32
2275         if ( (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f) )
2276                 i = 32 - i;
2277 #else
2278         if ( (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf) )
2279                 i = 16 - i;
2280 #endif
2281         if (i > 4) {
2282                 i -= 4;
2283                 b2 += i;
2284                 m2 += i;
2285                 s2 += i;
2286         } else if (i < 4) {
2287                 i += 28;
2288                 b2 += i;
2289                 m2 += i;
2290                 s2 += i;
2291         }
2292         if (b2 > 0)
2293                 b = lshift(b, b2);
2294         if (s2 > 0)
2295                 S = lshift(S, s2);
2296         if (k_check) {
2297                 if (cmp(b,S) < 0) {
2298                         k--;
2299                         b = multadd(b, 10, 0);  /* we botched the k estimate */
2300                         if (leftright)
2301                                 mhi = multadd(mhi, 10, 0);
2302                         ilim = ilim1;
2303                 }
2304         }
2305         if (ilim <= 0 && mode > 2) {
2306                 if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
2307                         /* no digits, fcvt style */
2308  no_digits:
2309                         k = -1 - ndigits;
2310                         goto ret;
2311                 }
2312  one_digit:
2313                 *s++ = '1';
2314                 k++;
2315                 goto ret;
2316         }
2317         if (leftright) {
2318                 if (m2 > 0)
2319                         mhi = lshift(mhi, m2);
2320
2321                 /* Compute mlo -- check for special case
2322                  * that d is a normalized power of 2.
2323                  */
2324
2325                 mlo = mhi;
2326                 if (spec_case) {
2327                         mhi = Balloc(mhi->k);
2328                         Bcopy(mhi, mlo);
2329                         mhi = lshift(mhi, Log2P);
2330                 }
2331
2332                 for (i = 1;;i++) {
2333                         dig = quorem(b,S) + '0';
2334                         /* Do we yet have the shortest decimal string
2335                          * that will round to d?
2336                          */
2337                         j = cmp(b, mlo);
2338                         delta = diff(S, mhi);
2339                         j1 = delta->sign ? 1 : cmp(b, delta);
2340                         Bfree(delta);
2341 #ifndef ROUND_BIASED
2342                         if (j1 == 0 && !mode && !(word1(d) & 1)) {
2343                                 if (dig == '9')
2344                                         goto round_9_up;
2345                                 if (j > 0)
2346                                         dig++;
2347                                 *s++ = dig;
2348                                 goto ret;
2349                         }
2350 #endif
2351                         if (j < 0 || (j == 0 && !mode
2352 #ifndef ROUND_BIASED
2353                                                         && !(word1(d) & 1)
2354 #endif
2355                                         )) {
2356                                 if (j1 > 0) {
2357                                         b = lshift(b, 1);
2358                                         j1 = cmp(b, S);
2359                                         if ((j1 > 0 || (j1 == 0 && dig & 1))
2360                                         && dig++ == '9')
2361                                                 goto round_9_up;
2362                                 }
2363                                 *s++ = dig;
2364                                 goto ret;
2365                         }
2366                         if (j1 > 0) {
2367                                 if (dig == '9') { /* possible if i == 1 */
2368  round_9_up:
2369                                         *s++ = '9';
2370                                         goto roundoff;
2371                                 }
2372                                 *s++ = dig + 1;
2373                                 goto ret;
2374                         }
2375                         *s++ = dig;
2376                         if (i == ilim)
2377                                 break;
2378                         b = multadd(b, 10, 0);
2379                         if (mlo == mhi)
2380                                 mlo = mhi = multadd(mhi, 10, 0);
2381                         else {
2382                                 mlo = multadd(mlo, 10, 0);
2383                                 mhi = multadd(mhi, 10, 0);
2384                         }
2385                 }
2386         } else
2387                 for (i = 1;; i++) {
2388                         *s++ = dig = quorem(b,S) + '0';
2389                         if (i >= ilim)
2390                                 break;
2391                         b = multadd(b, 10, 0);
2392                 }
2393
2394         /* Round off last digit */
2395
2396         b = lshift(b, 1);
2397         j = cmp(b, S);
2398         if (j > 0 || (j == 0 && dig & 1)) {
2399  roundoff:
2400                 while (*--s == '9')
2401                         if (s == s0) {
2402                                 k++;
2403                                 *s++ = '1';
2404                                 goto ret;
2405                         }
2406                 ++*s++;
2407         } else {
2408                 while (*--s == '0');
2409                 s++;
2410         }
2411  ret:
2412         Bfree(S);
2413         if (mhi) {
2414                 if (mlo && mlo != mhi)
2415                         Bfree(mlo);
2416                 Bfree(mhi);
2417         }
2418  ret1:
2419         Bfree(b);
2420         if (s == s0) {  /* don't return empty string */
2421                 *s++ = '0';
2422                 k = 0;
2423         }
2424         *s = 0;
2425         *decpt = k + 1;
2426         if (rve)
2427                 *rve = s;
2428         return s0;
2429         }
2430 #ifdef __cplusplus
2431 }
2432 #endif