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