2009-01-16 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / utils / strtod.c
1 /****************************************************************
2  *
3  * The author of this software is David M. Gay.
4  *
5  * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose without fee is hereby granted, provided that this entire notice
9  * is included in all copies of any software which is or includes a copy
10  * or modification of this software and in all copies of the supporting
11  * documentation for such software.
12  *
13  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
14  * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
15  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
16  * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
17  *
18  ***************************************************************/
19 #include "strtod.h"
20 #include <glib.h>
21 #define freedtoa __freedtoa
22 #define dtoa __dtoa
23
24 G_LOCK_DEFINE_STATIC(str_mutex0);
25 G_LOCK_DEFINE_STATIC(str_mutex1);
26 #define MULTIPLE_THREADS 1
27 #define ACQUIRE_DTOA_LOCK(n)    G_LOCK (str_mutex##n)
28 #define FREE_DTOA_LOCK(n)               G_UNLOCK (str_mutex##n)
29
30 /* Please send bug reports to David M. Gay (dmg at acm dot org,
31  * with " at " changed at "@" and " dot " changed to ".").      */
32
33 /* On a machine with IEEE extended-precision registers, it is
34  * necessary to specify double-precision (53-bit) rounding precision
35  * before invoking strtod or dtoa.  If the machine uses (the equivalent
36  * of) Intel 80x87 arithmetic, the call
37  *      _control87(PC_53, MCW_PC);
38  * does this with many compilers.  Whether this or another call is
39  * appropriate depends on the compiler; for this to work, it may be
40  * necessary to #include "float.h" or another system-dependent header
41  * file.
42  */
43
44 /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
45  *
46  * This strtod returns a nearest machine number to the input decimal
47  * string (or sets errno to ERANGE).  With IEEE arithmetic, ties are
48  * broken by the IEEE round-even rule.  Otherwise ties are broken by
49  * biased rounding (add half and chop).
50  *
51  * Inspired loosely by William D. Clinger's paper "How to Read Floating
52  * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
53  *
54  * Modifications:
55  *
56  *      1. We only require IEEE, IBM, or VAX double-precision
57  *              arithmetic (not IEEE double-extended).
58  *      2. We get by with floating-point arithmetic in a case that
59  *              Clinger missed -- when we're computing d * 10^n
60  *              for a small integer d and the integer n is not too
61  *              much larger than 22 (the maximum integer k for which
62  *              we can represent 10^k exactly), we may be able to
63  *              compute (d*10^k) * 10^(e-k) with just one roundoff.
64  *      3. Rather than a bit-at-a-time adjustment of the binary
65  *              result in the hard case, we use floating-point
66  *              arithmetic to determine the adjustment to within
67  *              one bit; only in really hard cases do we need to
68  *              compute a second residual.
69  *      4. Because of 3., we don't need a large table of powers of 10
70  *              for ten-to-e (just some small tables, e.g. of 10^k
71  *              for 0 <= k <= 22).
72  */
73
74 /*
75  * #define IEEE_8087 for IEEE-arithmetic machines where the least
76  *      significant byte has the lowest address.
77  * #define IEEE_MC68k for IEEE-arithmetic machines where the most
78  *      significant byte has the lowest address.
79  * #define Long int on machines with 32-bit ints and 64-bit longs.
80  * #define IBM for IBM mainframe-style floating-point arithmetic.
81  * #define VAX for VAX-style floating-point arithmetic (D_floating).
82  * #define No_leftright to omit left-right logic in fast floating-point
83  *      computation of dtoa.
84  * #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
85  *      and strtod and dtoa should round accordingly.
86  * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
87  *      and Honor_FLT_ROUNDS is not #defined.
88  * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
89  *      that use extended-precision instructions to compute rounded
90  *      products and quotients) with IBM.
91  * #define ROUND_BIASED for IEEE-format with biased rounding.
92  * #define Inaccurate_Divide for IEEE-format with correctly rounded
93  *      products but inaccurate quotients, e.g., for Intel i860.
94  * #define NO_LONG_LONG on machines that do not have a "long long"
95  *      integer type (of >= 64 bits).  On such machines, you can
96  *      #define Just_16 to store 16 bits per 32-bit Long when doing
97  *      high-precision integer arithmetic.  Whether this speeds things
98  *      up or slows things down depends on the machine and the number
99  *      being converted.  If long long is available and the name is
100  *      something other than "long long", #define Llong to be the name,
101  *      and if "unsigned Llong" does not work as an unsigned version of
102  *      Llong, #define #ULLong to be the corresponding unsigned type.
103  * #define KR_headers for old-style C function headers.
104  * #define Bad_float_h if your system lacks a float.h or if it does not
105  *      define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
106  *      FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
107  * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
108  *      if memory is available and otherwise does something you deem
109  *      appropriate.  If MALLOC is undefined, malloc will be invoked
110  *      directly -- and assumed always to succeed.
111  * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
112  *      memory allocations from a private pool of memory when possible.
113  *      When used, the private pool is PRIVATE_MEM bytes long:  2304 bytes,
114  *      unless #defined to be a different length.  This default length
115  *      suffices to get rid of MALLOC calls except for unusual cases,
116  *      such as decimal-to-binary conversion of a very long string of
117  *      digits.  The longest string dtoa can return is about 751 bytes
118  *      long.  For conversions by strtod of strings of 800 digits and
119  *      all dtoa conversions in single-threaded executions with 8-byte
120  *      pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
121  *      pointers, PRIVATE_MEM >= 7112 appears adequate.
122  * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
123  *      Infinity and NaN (case insensitively).  On some systems (e.g.,
124  *      some HP systems), it may be necessary to #define NAN_WORD0
125  *      appropriately -- to the most significant word of a quiet NaN.
126  *      (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
127  *      When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
128  *      strtod also accepts (case insensitively) strings of the form
129  *      NaN(x), where x is a string of hexadecimal digits and spaces;
130  *      if there is only one string of hexadecimal digits, it is taken
131  *      for the 52 fraction bits of the resulting NaN; if there are two
132  *      or more strings of hex digits, the first is for the high 20 bits,
133  *      the second and subsequent for the low 32 bits, with intervening
134  *      white space ignored; but if this results in none of the 52
135  *      fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
136  *      and NAN_WORD1 are used instead.
137  * #define MULTIPLE_THREADS if the system offers preemptively scheduled
138  *      multiple threads.  In this case, you must provide (or suitably
139  *      #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
140  *      by FREE_DTOA_LOCK(n) for n = 0 or 1.  (The second lock, accessed
141  *      in pow5mult, ensures lazy evaluation of only one copy of high
142  *      powers of 5; omitting this lock would introduce a small
143  *      probability of wasting memory, but would otherwise be harmless.)
144  *      You must also invoke freedtoa(s) to free the value s returned by
145  *      dtoa.  You may do so whether or not MULTIPLE_THREADS is #defined.
146  * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
147  *      avoids underflows on inputs whose result does not underflow.
148  *      If you #define NO_IEEE_Scale on a machine that uses IEEE-format
149  *      floating-point numbers and flushes underflows to zero rather
150  *      than implementing gradual underflow, then you must also #define
151  *      Sudden_Underflow.
152  * #define YES_ALIAS to permit aliasing certain double values with
153  *      arrays of ULongs.  This leads to slightly better code with
154  *      some compilers and was always used prior to 19990916, but it
155  *      is not strictly legal and can cause trouble with aggressively
156  *      optimizing compilers (e.g., gcc 2.95.1 under -O2).
157  * #define USE_LOCALE to use the current locale's decimal_point value.
158  * #define SET_INEXACT if IEEE arithmetic is being used and extra
159  *      computation should be done to set the inexact flag when the
160  *      result is inexact and avoid setting inexact when the result
161  *      is exact.  In this case, dtoa.c must be compiled in
162  *      an environment, perhaps provided by #include "dtoa.c" in a
163  *      suitable wrapper, that defines two functions,
164  *              int get_inexact(void);
165  *              void clear_inexact(void);
166  *      such that get_inexact() returns a nonzero value if the
167  *      inexact bit is already set, and clear_inexact() sets the
168  *      inexact bit to 0.  When SET_INEXACT is #defined, strtod
169  *      also does extra computations to set the underflow and overflow
170  *      flags when appropriate (i.e., when the result is tiny and
171  *      inexact or when it is a numeric value rounded to +-infinity).
172  * #define NO_ERRNO if strtod should not assign errno = ERANGE when
173  *      the result overflows to +-Infinity or underflows to 0.
174  */
175 #if defined(i386) || defined(mips) && defined(MIPSEL) || defined (__arm__)
176
177 #   define IEEE_8087
178
179 #elif defined(__x86_64__) || defined(__alpha__)
180
181 #   define IEEE_8087
182
183 #elif defined(__ia64)
184
185 #   ifdef __hpux
186 #       define IEEE_MC68k
187 #   else
188 #       define IEEE_8087
189 #   endif
190
191 #elif defined(__hppa)
192
193 #   define IEEE_MC68k
194
195 #else
196 #define IEEE_MC68k
197 #endif
198
199 #define Long gint32
200 #define ULong guint32
201
202 #ifdef DEBUG
203 #include "stdio.h"
204 #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
205 #endif
206
207 #include "stdlib.h"
208 #include "string.h"
209
210 #undef USE_LOCALE
211 #ifdef USE_LOCALE
212 #include "locale.h"
213 #endif
214
215 #ifdef MALLOC
216 #ifdef KR_headers
217 extern char *MALLOC();
218 #else
219 extern void *MALLOC(size_t);
220 #endif
221 #else
222 #define MALLOC malloc
223 #endif
224
225 #define Omit_Private_Memory
226 #ifndef Omit_Private_Memory
227 #ifndef PRIVATE_MEM
228 #define PRIVATE_MEM 2304
229 #endif
230 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
231 static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
232 #endif
233
234 #undef IEEE_Arith
235 #undef Avoid_Underflow
236 #ifdef IEEE_MC68k
237 #define IEEE_Arith
238 #endif
239 #ifdef IEEE_8087
240 #define IEEE_Arith
241 #endif
242
243 #include "errno.h"
244
245 #ifdef Bad_float_h
246
247 #ifdef IEEE_Arith
248 #define DBL_DIG 15
249 #define DBL_MAX_10_EXP 308
250 #define DBL_MAX_EXP 1024
251 #define FLT_RADIX 2
252 #endif /*IEEE_Arith*/
253
254 #ifdef IBM
255 #define DBL_DIG 16
256 #define DBL_MAX_10_EXP 75
257 #define DBL_MAX_EXP 63
258 #define FLT_RADIX 16
259 #define DBL_MAX 7.2370055773322621e+75
260 #endif
261
262 #ifdef VAX
263 #define DBL_DIG 16
264 #define DBL_MAX_10_EXP 38
265 #define DBL_MAX_EXP 127
266 #define FLT_RADIX 2
267 #define DBL_MAX 1.7014118346046923e+38
268 #endif
269
270 #ifndef LONG_MAX
271 #define LONG_MAX 2147483647
272 #endif
273
274 #else /* ifndef Bad_float_h */
275 #include "float.h"
276 #endif /* Bad_float_h */
277
278 #ifndef __MATH_H__
279 #include "math.h"
280 #endif
281
282 #ifdef __cplusplus
283 extern "C" {
284 #endif
285
286 #ifndef CONST
287 #ifdef KR_headers
288 #define CONST /* blank */
289 #else
290 #define CONST const
291 #endif
292 #endif
293
294 #if defined(IEEE_8087) + defined(IEEE_MC68k) + defined(VAX) + defined(IBM) != 1
295 Exactly one of IEEE_8087, IEEE_MC68k, VAX, or IBM should be defined.
296 #endif
297
298 typedef union { double d; ULong L[2]; } U;
299
300 #ifdef YES_ALIAS
301 #define dval(x) x
302 #ifdef IEEE_8087
303 #define word0(x) ((ULong *)&x)[1]
304 #define word1(x) ((ULong *)&x)[0]
305 #else
306 #define word0(x) ((ULong *)&x)[0]
307 #define word1(x) ((ULong *)&x)[1]
308 #endif
309 #else
310 #ifdef IEEE_8087
311 #define word0(x) ((U*)&x)->L[1]
312 #define word1(x) ((U*)&x)->L[0]
313 #else
314 #define word0(x) ((U*)&x)->L[0]
315 #define word1(x) ((U*)&x)->L[1]
316 #endif
317 #define dval(x) ((U*)&x)->d
318 #endif
319
320 /* The following definition of Storeinc is appropriate for MIPS processors.
321  * An alternative that might be better on some machines is
322  * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
323  */
324 #if defined(IEEE_8087) + defined(VAX)
325 #define Storeinc(a,b,c) do { (((unsigned short *)a)[1] = (unsigned short)b, \
326 ((unsigned short *)a)[0] = (unsigned short)c, a++) } while (0)
327 #else
328 #define Storeinc(a,b,c) do { (((unsigned short *)a)[0] = (unsigned short)b, \
329 ((unsigned short *)a)[1] = (unsigned short)c, a++) } while (0)
330 #endif
331
332 /* #define P DBL_MANT_DIG */
333 /* Ten_pmax = floor(P*log(2)/log(5)) */
334 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
335 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
336 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
337
338 #ifdef IEEE_Arith
339 #define Exp_shift  20
340 #define Exp_shift1 20
341 #define Exp_msk1    0x100000
342 #define Exp_msk11   0x100000
343 #define Exp_mask  0x7ff00000
344 #define P 53
345 #define Bias 1023
346 #define Emin (-1022)
347 #define Exp_1  0x3ff00000
348 #define Exp_11 0x3ff00000
349 #define Ebits 11
350 #define Frac_mask  0xfffff
351 #define Frac_mask1 0xfffff
352 #define Ten_pmax 22
353 #define Bletch 0x10
354 #define Bndry_mask  0xfffff
355 #define Bndry_mask1 0xfffff
356 #define LSB 1
357 #define Sign_bit 0x80000000
358 #define Log2P 1
359 #define Tiny0 0
360 #define Tiny1 1
361 #define Quick_max 14
362 #define Int_max 14
363 #ifndef NO_IEEE_Scale
364 #define Avoid_Underflow
365 #ifdef Flush_Denorm     /* debugging option */
366 #undef Sudden_Underflow
367 #endif
368 #endif
369
370 #ifndef Flt_Rounds
371 #ifdef FLT_ROUNDS
372 #define Flt_Rounds FLT_ROUNDS
373 #else
374 #define Flt_Rounds 1
375 #endif
376 #endif /*Flt_Rounds*/
377
378 #ifdef Honor_FLT_ROUNDS
379 #define Rounding rounding
380 #undef Check_FLT_ROUNDS
381 #define Check_FLT_ROUNDS
382 #else
383 #define Rounding Flt_Rounds
384 #endif
385
386 #else /* ifndef IEEE_Arith */
387 #undef Check_FLT_ROUNDS
388 #undef Honor_FLT_ROUNDS
389 #undef SET_INEXACT
390 #undef  Sudden_Underflow
391 #define Sudden_Underflow
392 #ifdef IBM
393 #undef Flt_Rounds
394 #define Flt_Rounds 0
395 #define Exp_shift  24
396 #define Exp_shift1 24
397 #define Exp_msk1   0x1000000
398 #define Exp_msk11  0x1000000
399 #define Exp_mask  0x7f000000
400 #define P 14
401 #define Bias 65
402 #define Exp_1  0x41000000
403 #define Exp_11 0x41000000
404 #define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
405 #define Frac_mask  0xffffff
406 #define Frac_mask1 0xffffff
407 #define Bletch 4
408 #define Ten_pmax 22
409 #define Bndry_mask  0xefffff
410 #define Bndry_mask1 0xffffff
411 #define LSB 1
412 #define Sign_bit 0x80000000
413 #define Log2P 4
414 #define Tiny0 0x100000
415 #define Tiny1 0
416 #define Quick_max 14
417 #define Int_max 15
418 #else /* VAX */
419 #undef Flt_Rounds
420 #define Flt_Rounds 1
421 #define Exp_shift  23
422 #define Exp_shift1 7
423 #define Exp_msk1    0x80
424 #define Exp_msk11   0x800000
425 #define Exp_mask  0x7f80
426 #define P 56
427 #define Bias 129
428 #define Exp_1  0x40800000
429 #define Exp_11 0x4080
430 #define Ebits 8
431 #define Frac_mask  0x7fffff
432 #define Frac_mask1 0xffff007f
433 #define Ten_pmax 24
434 #define Bletch 2
435 #define Bndry_mask  0xffff007f
436 #define Bndry_mask1 0xffff007f
437 #define LSB 0x10000
438 #define Sign_bit 0x8000
439 #define Log2P 1
440 #define Tiny0 0x80
441 #define Tiny1 0
442 #define Quick_max 15
443 #define Int_max 15
444 #endif /* IBM, VAX */
445 #endif /* IEEE_Arith */
446
447 #ifndef IEEE_Arith
448 #define ROUND_BIASED
449 #endif
450
451 #ifdef RND_PRODQUOT
452 #define rounded_product(a,b) a = rnd_prod(a, b)
453 #define rounded_quotient(a,b) a = rnd_quot(a, b)
454 #ifdef KR_headers
455 extern double rnd_prod(), rnd_quot();
456 #else
457 extern double rnd_prod(double, double), rnd_quot(double, double);
458 #endif
459 #else
460 #define rounded_product(a,b) a *= b
461 #define rounded_quotient(a,b) a /= b
462 #endif
463
464 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
465 #define Big1 0xffffffff
466
467 #ifndef Pack_32
468 #define Pack_32
469 #endif
470
471 #ifdef KR_headers
472 #define FFFFFFFF ((((unsigned long)0xffff)<<16)|(unsigned long)0xffff)
473 #else
474 #define FFFFFFFF 0xffffffffUL
475 #endif
476
477 #ifdef NO_LONG_LONG
478 #undef ULLong
479 #ifdef Just_16
480 #undef Pack_32
481 /* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
482  * This makes some inner loops simpler and sometimes saves work
483  * during multiplications, but it often seems to make things slightly
484  * slower.  Hence the default is now to store 32 bits per Long.
485  */
486 #endif
487 #else   /* long long available */
488 #ifndef Llong
489 #define Llong long long
490 #endif
491 #ifndef ULLong
492 #define ULLong unsigned Llong
493 #endif
494 #endif /* NO_LONG_LONG */
495
496 #ifndef MULTIPLE_THREADS
497 #define ACQUIRE_DTOA_LOCK(n)    /*nothing*/
498 #define FREE_DTOA_LOCK(n)       /*nothing*/
499 #endif
500
501 #define Kmax 15
502
503 #ifdef __cplusplus
504 extern "C" double strtod(const char *s00, char **se);
505 extern "C" char *dtoa(double d, int mode, int ndigits,
506                         int *decpt, int *sign, char **rve);
507 #endif
508
509  struct
510 Bigint {
511         struct Bigint *next;
512         int k, maxwds, sign, wds;
513         ULong x[1];
514         };
515
516  typedef struct Bigint Bigint;
517
518  static Bigint *freelist[Kmax+1];
519
520  static Bigint *
521 Balloc
522 #ifdef KR_headers
523         (k) int k;
524 #else
525         (int k)
526 #endif
527 {
528         int x;
529         Bigint *rv;
530 #ifndef Omit_Private_Memory
531         unsigned int len;
532 #endif
533
534         ACQUIRE_DTOA_LOCK(0);
535         if ((rv = freelist[k])) {
536                 freelist[k] = rv->next;
537                 }
538         else {
539                 x = 1 << k;
540 #ifdef Omit_Private_Memory
541                 rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
542 #else
543                 len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
544                         /sizeof(double);
545                 if (pmem_next - private_mem + len <= PRIVATE_mem) {
546                         rv = (Bigint*)pmem_next;
547                         pmem_next += len;
548                         }
549                 else
550                         rv = (Bigint*)MALLOC(len*sizeof(double));
551 #endif
552                 rv->k = k;
553                 rv->maxwds = x;
554                 }
555         FREE_DTOA_LOCK(0);
556         rv->sign = rv->wds = 0;
557         return rv;
558         }
559
560  static void
561 Bfree
562 #ifdef KR_headers
563         (v) Bigint *v;
564 #else
565         (Bigint *v)
566 #endif
567 {
568         if (v) {
569                 ACQUIRE_DTOA_LOCK(0);
570                 v->next = freelist[v->k];
571                 freelist[v->k] = v;
572                 FREE_DTOA_LOCK(0);
573                 }
574         }
575
576 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
577 y->wds*sizeof(Long) + 2*sizeof(int))
578
579  static Bigint *
580 multadd
581 #ifdef KR_headers
582         (b, m, a) Bigint *b; int m, a;
583 #else
584         (Bigint *b, int m, int a)       /* multiply by m and add a */
585 #endif
586 {
587         int i, wds;
588 #ifdef ULLong
589         ULong *x;
590         ULLong carry, y;
591 #else
592         ULong carry, *x, y;
593 #ifdef Pack_32
594         ULong xi, z;
595 #endif
596 #endif
597         Bigint *b1;
598
599         wds = b->wds;
600         x = b->x;
601         i = 0;
602         carry = a;
603         do {
604 #ifdef ULLong
605                 y = *x * (ULLong)m + carry;
606                 carry = y >> 32;
607                 *x++ = y & FFFFFFFF;
608 #else
609 #ifdef Pack_32
610                 xi = *x;
611                 y = (xi & 0xffff) * m + carry;
612                 z = (xi >> 16) * m + (y >> 16);
613                 carry = z >> 16;
614                 *x++ = (z << 16) + (y & 0xffff);
615 #else
616                 y = *x * m + carry;
617                 carry = y >> 16;
618                 *x++ = y & 0xffff;
619 #endif
620 #endif
621                 }
622                 while(++i < wds);
623         if (carry) {
624                 if (wds >= b->maxwds) {
625                         b1 = Balloc(b->k+1);
626                         Bcopy(b1, b);
627                         Bfree(b);
628                         b = b1;
629                         }
630                 b->x[wds++] = carry;
631                 b->wds = wds;
632                 }
633         return b;
634         }
635
636  static Bigint *
637 s2b
638 #ifdef KR_headers
639         (s, nd0, nd, y9) CONST char *s; int nd0, nd; ULong y9;
640 #else
641         (CONST char *s, int nd0, int nd, ULong y9)
642 #endif
643 {
644         Bigint *b;
645         int i, k;
646         Long x, y;
647
648         x = (nd + 8) / 9;
649         for(k = 0, y = 1; x > y; y <<= 1, k++) ;
650 #ifdef Pack_32
651         b = Balloc(k);
652         b->x[0] = y9;
653         b->wds = 1;
654 #else
655         b = Balloc(k+1);
656         b->x[0] = y9 & 0xffff;
657         b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
658 #endif
659
660         i = 9;
661         if (9 < nd0) {
662                 s += 9;
663                 do b = multadd(b, 10, *s++ - '0');
664                         while(++i < nd0);
665                 s++;
666                 }
667         else
668                 s += 10;
669         for(; i < nd; i++)
670                 b = multadd(b, 10, *s++ - '0');
671         return b;
672         }
673
674  static int
675 hi0bits
676 #ifdef KR_headers
677         (x) register ULong x;
678 #else
679         (register ULong x)
680 #endif
681 {
682         register int k = 0;
683
684         if (!(x & 0xffff0000)) {
685                 k = 16;
686                 x <<= 16;
687                 }
688         if (!(x & 0xff000000)) {
689                 k += 8;
690                 x <<= 8;
691                 }
692         if (!(x & 0xf0000000)) {
693                 k += 4;
694                 x <<= 4;
695                 }
696         if (!(x & 0xc0000000)) {
697                 k += 2;
698                 x <<= 2;
699                 }
700         if (!(x & 0x80000000)) {
701                 k++;
702                 if (!(x & 0x40000000))
703                         return 32;
704                 }
705         return k;
706         }
707
708  static int
709 lo0bits
710 #ifdef KR_headers
711         (y) ULong *y;
712 #else
713         (ULong *y)
714 #endif
715 {
716         register int k;
717         register ULong x = *y;
718
719         if (x & 7) {
720                 if (x & 1)
721                         return 0;
722                 if (x & 2) {
723                         *y = x >> 1;
724                         return 1;
725                         }
726                 *y = x >> 2;
727                 return 2;
728                 }
729         k = 0;
730         if (!(x & 0xffff)) {
731                 k = 16;
732                 x >>= 16;
733                 }
734         if (!(x & 0xff)) {
735                 k += 8;
736                 x >>= 8;
737                 }
738         if (!(x & 0xf)) {
739                 k += 4;
740                 x >>= 4;
741                 }
742         if (!(x & 0x3)) {
743                 k += 2;
744                 x >>= 2;
745                 }
746         if (!(x & 1)) {
747                 k++;
748                 x >>= 1;
749                 if (!x)
750                         return 32;
751                 }
752         *y = x;
753         return k;
754         }
755
756  static Bigint *
757 i2b
758 #ifdef KR_headers
759         (i) int i;
760 #else
761         (int i)
762 #endif
763 {
764         Bigint *b;
765
766         b = Balloc(1);
767         b->x[0] = i;
768         b->wds = 1;
769         return b;
770         }
771
772  static Bigint *
773 mult
774 #ifdef KR_headers
775         (a, b) Bigint *a, *b;
776 #else
777         (Bigint *a, Bigint *b)
778 #endif
779 {
780         Bigint *c;
781         int k, wa, wb, wc;
782         ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
783         ULong y;
784 #ifdef ULLong
785         ULLong carry, z;
786 #else
787         ULong carry, z;
788 #ifdef Pack_32
789         ULong z2;
790 #endif
791 #endif
792
793         if (a->wds < b->wds) {
794                 c = a;
795                 a = b;
796                 b = c;
797                 }
798         k = a->k;
799         wa = a->wds;
800         wb = b->wds;
801         wc = wa + wb;
802         if (wc > a->maxwds)
803                 k++;
804         c = Balloc(k);
805         for(x = c->x, xa = x + wc; x < xa; x++)
806                 *x = 0;
807         xa = a->x;
808         xae = xa + wa;
809         xb = b->x;
810         xbe = xb + wb;
811         xc0 = c->x;
812 #ifdef ULLong
813         for(; xb < xbe; xc0++) {
814                 if ((y = *xb++)) {
815                         x = xa;
816                         xc = xc0;
817                         carry = 0;
818                         do {
819                                 z = *x++ * (ULLong)y + *xc + carry;
820                                 carry = z >> 32;
821                                 *xc++ = z & FFFFFFFF;
822                                 }
823                                 while(x < xae);
824                         *xc = carry;
825                         }
826                 }
827 #else
828 #ifdef Pack_32
829         for(; xb < xbe; xb++, xc0++) {
830                 if (y = *xb & 0xffff) {
831                         x = xa;
832                         xc = xc0;
833                         carry = 0;
834                         do {
835                                 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
836                                 carry = z >> 16;
837                                 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
838                                 carry = z2 >> 16;
839                                 Storeinc(xc, z2, z);
840                                 }
841                                 while(x < xae);
842                         *xc = carry;
843                         }
844                 if (y = *xb >> 16) {
845                         x = xa;
846                         xc = xc0;
847                         carry = 0;
848                         z2 = *xc;
849                         do {
850                                 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
851                                 carry = z >> 16;
852                                 Storeinc(xc, z, z2);
853                                 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
854                                 carry = z2 >> 16;
855                                 }
856                                 while(x < xae);
857                         *xc = z2;
858                         }
859                 }
860 #else
861         for(; xb < xbe; xc0++) {
862                 if (y = *xb++) {
863                         x = xa;
864                         xc = xc0;
865                         carry = 0;
866                         do {
867                                 z = *x++ * y + *xc + carry;
868                                 carry = z >> 16;
869                                 *xc++ = z & 0xffff;
870                                 }
871                                 while(x < xae);
872                         *xc = carry;
873                         }
874                 }
875 #endif
876 #endif
877         for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
878         c->wds = wc;
879         return c;
880         }
881
882  static Bigint *p5s;
883
884  static Bigint *
885 pow5mult
886 #ifdef KR_headers
887         (b, k) Bigint *b; int k;
888 #else
889         (Bigint *b, int k)
890 #endif
891 {
892         Bigint *b1, *p5, *p51;
893         int i;
894         static int p05[3] = { 5, 25, 125 };
895
896         if ((i = k & 3))
897                 b = multadd(b, p05[i-1], 0);
898
899         if (!(k >>= 2))
900                 return b;
901         if (!(p5 = p5s)) {
902                 /* first time */
903 #ifdef MULTIPLE_THREADS
904                 ACQUIRE_DTOA_LOCK(1);
905                 if (!(p5 = p5s)) {
906                         p5 = p5s = i2b(625);
907                         p5->next = 0;
908                         }
909                 FREE_DTOA_LOCK(1);
910 #else
911                 p5 = p5s = i2b(625);
912                 p5->next = 0;
913 #endif
914                 }
915         for(;;) {
916                 if (k & 1) {
917                         b1 = mult(b, p5);
918                         Bfree(b);
919                         b = b1;
920                         }
921                 if (!(k >>= 1))
922                         break;
923                 if (!(p51 = p5->next)) {
924 #ifdef MULTIPLE_THREADS
925                         ACQUIRE_DTOA_LOCK(1);
926                         if (!(p51 = p5->next)) {
927                                 p51 = p5->next = mult(p5,p5);
928                                 p51->next = 0;
929                                 }
930                         FREE_DTOA_LOCK(1);
931 #else
932                         p51 = p5->next = mult(p5,p5);
933                         p51->next = 0;
934 #endif
935                         }
936                 p5 = p51;
937                 }
938         return b;
939         }
940
941  static Bigint *
942 lshift
943 #ifdef KR_headers
944         (b, k) Bigint *b; int k;
945 #else
946         (Bigint *b, int k)
947 #endif
948 {
949         int i, k1, n, n1;
950         Bigint *b1;
951         ULong *x, *x1, *xe, z;
952
953 #ifdef Pack_32
954         n = k >> 5;
955 #else
956         n = k >> 4;
957 #endif
958         k1 = b->k;
959         n1 = n + b->wds + 1;
960         for(i = b->maxwds; n1 > i; i <<= 1)
961                 k1++;
962         b1 = Balloc(k1);
963         x1 = b1->x;
964         for(i = 0; i < n; i++)
965                 *x1++ = 0;
966         x = b->x;
967         xe = x + b->wds;
968 #ifdef Pack_32
969         if (k &= 0x1f) {
970                 k1 = 32 - k;
971                 z = 0;
972                 do {
973                         *x1++ = *x << k | z;
974                         z = *x++ >> k1;
975                         }
976                         while(x < xe);
977                 if ((*x1 = z))
978                         ++n1;
979                 }
980 #else
981         if (k &= 0xf) {
982                 k1 = 16 - k;
983                 z = 0;
984                 do {
985                         *x1++ = *x << k  & 0xffff | z;
986                         z = *x++ >> k1;
987                         }
988                         while(x < xe);
989                 if (*x1 = z)
990                         ++n1;
991                 }
992 #endif
993         else do
994                 *x1++ = *x++;
995                 while(x < xe);
996         b1->wds = n1 - 1;
997         Bfree(b);
998         return b1;
999         }
1000
1001  static int
1002 cmp
1003 #ifdef KR_headers
1004         (a, b) Bigint *a, *b;
1005 #else
1006         (Bigint *a, Bigint *b)
1007 #endif
1008 {
1009         ULong *xa, *xa0, *xb, *xb0;
1010         int i, j;
1011
1012         i = a->wds;
1013         j = b->wds;
1014 #ifdef DEBUG
1015         if (i > 1 && !a->x[i-1])
1016                 Bug("cmp called with a->x[a->wds-1] == 0");
1017         if (j > 1 && !b->x[j-1])
1018                 Bug("cmp called with b->x[b->wds-1] == 0");
1019 #endif
1020         if (i -= j)
1021                 return i;
1022         xa0 = a->x;
1023         xa = xa0 + j;
1024         xb0 = b->x;
1025         xb = xb0 + j;
1026         for(;;) {
1027                 if (*--xa != *--xb)
1028                         return *xa < *xb ? -1 : 1;
1029                 if (xa <= xa0)
1030                         break;
1031                 }
1032         return 0;
1033         }
1034
1035  static Bigint *
1036 diff
1037 #ifdef KR_headers
1038         (a, b) Bigint *a, *b;
1039 #else
1040         (Bigint *a, Bigint *b)
1041 #endif
1042 {
1043         Bigint *c;
1044         int i, wa, wb;
1045         ULong *xa, *xae, *xb, *xbe, *xc;
1046 #ifdef ULLong
1047         ULLong borrow, y;
1048 #else
1049         ULong borrow, y;
1050 #ifdef Pack_32
1051         ULong z;
1052 #endif
1053 #endif
1054
1055         i = cmp(a,b);
1056         if (!i) {
1057                 c = Balloc(0);
1058                 c->wds = 1;
1059                 c->x[0] = 0;
1060                 return c;
1061                 }
1062         if (i < 0) {
1063                 c = a;
1064                 a = b;
1065                 b = c;
1066                 i = 1;
1067                 }
1068         else
1069                 i = 0;
1070         c = Balloc(a->k);
1071         c->sign = i;
1072         wa = a->wds;
1073         xa = a->x;
1074         xae = xa + wa;
1075         wb = b->wds;
1076         xb = b->x;
1077         xbe = xb + wb;
1078         xc = c->x;
1079         borrow = 0;
1080 #ifdef ULLong
1081         do {
1082                 y = (ULLong)*xa++ - *xb++ - borrow;
1083                 borrow = y >> 32 & (ULong)1;
1084                 *xc++ = y & FFFFFFFF;
1085                 }
1086                 while(xb < xbe);
1087         while(xa < xae) {
1088                 y = *xa++ - borrow;
1089                 borrow = y >> 32 & (ULong)1;
1090                 *xc++ = y & FFFFFFFF;
1091                 }
1092 #else
1093 #ifdef Pack_32
1094         do {
1095                 y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
1096                 borrow = (y & 0x10000) >> 16;
1097                 z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
1098                 borrow = (z & 0x10000) >> 16;
1099                 Storeinc(xc, z, y);
1100                 }
1101                 while(xb < xbe);
1102         while(xa < xae) {
1103                 y = (*xa & 0xffff) - borrow;
1104                 borrow = (y & 0x10000) >> 16;
1105                 z = (*xa++ >> 16) - borrow;
1106                 borrow = (z & 0x10000) >> 16;
1107                 Storeinc(xc, z, y);
1108                 }
1109 #else
1110         do {
1111                 y = *xa++ - *xb++ - borrow;
1112                 borrow = (y & 0x10000) >> 16;
1113                 *xc++ = y & 0xffff;
1114                 }
1115                 while(xb < xbe);
1116         while(xa < xae) {
1117                 y = *xa++ - borrow;
1118                 borrow = (y & 0x10000) >> 16;
1119                 *xc++ = y & 0xffff;
1120                 }
1121 #endif
1122 #endif
1123         while(!*--xc)
1124                 wa--;
1125         c->wds = wa;
1126         return c;
1127         }
1128
1129  static double
1130 ulp
1131 #ifdef KR_headers
1132         (x) double x;
1133 #else
1134         (double x)
1135 #endif
1136 {
1137         register Long L;
1138         double a;
1139
1140         L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
1141 #ifndef Avoid_Underflow
1142 #ifndef Sudden_Underflow
1143         if (L > 0) {
1144 #endif
1145 #endif
1146 #ifdef IBM
1147                 L |= Exp_msk1 >> 4;
1148 #endif
1149                 word0(a) = L;
1150                 word1(a) = 0;
1151 #ifndef Avoid_Underflow
1152 #ifndef Sudden_Underflow
1153                 }
1154         else {
1155                 L = -L >> Exp_shift;
1156                 if (L < Exp_shift) {
1157                         word0(a) = 0x80000 >> L;
1158                         word1(a) = 0;
1159                         }
1160                 else {
1161                         word0(a) = 0;
1162                         L -= Exp_shift;
1163                         word1(a) = L >= 31 ? 1 : 1 << 31 - L;
1164                         }
1165                 }
1166 #endif
1167 #endif
1168         return dval(a);
1169         }
1170
1171  static double
1172 b2d
1173 #ifdef KR_headers
1174         (a, e) Bigint *a; int *e;
1175 #else
1176         (Bigint *a, int *e)
1177 #endif
1178 {
1179         ULong *xa, *xa0, w, y, z;
1180         int k;
1181         double d;
1182 #ifdef VAX
1183         ULong d0, d1;
1184 #else
1185 #define d0 word0(d)
1186 #define d1 word1(d)
1187 #endif
1188
1189         xa0 = a->x;
1190         xa = xa0 + a->wds;
1191         y = *--xa;
1192 #ifdef DEBUG
1193         if (!y) Bug("zero y in b2d");
1194 #endif
1195         k = hi0bits(y);
1196         *e = 32 - k;
1197 #ifdef Pack_32
1198         if (k < Ebits) {
1199                 d0 = Exp_1 | (y >> (Ebits - k));
1200                 w = xa > xa0 ? *--xa : 0;
1201                 d1 = y << ((32-Ebits) + k) | (w >> (Ebits - k));
1202                 goto ret_d;
1203                 }
1204         z = xa > xa0 ? *--xa : 0;
1205         if (k -= Ebits) {
1206                 d0 = Exp_1 | y << k | (z >> (32 - k));
1207                 y = xa > xa0 ? *--xa : 0;
1208                 d1 = z << k | (y >> (32 - k));
1209                 }
1210         else {
1211                 d0 = Exp_1 | y;
1212                 d1 = z;
1213                 }
1214 #else
1215         if (k < Ebits + 16) {
1216                 z = xa > xa0 ? *--xa : 0;
1217                 d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
1218                 w = xa > xa0 ? *--xa : 0;
1219                 y = xa > xa0 ? *--xa : 0;
1220                 d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
1221                 goto ret_d;
1222                 }
1223         z = xa > xa0 ? *--xa : 0;
1224         w = xa > xa0 ? *--xa : 0;
1225         k -= Ebits + 16;
1226         d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
1227         y = xa > xa0 ? *--xa : 0;
1228         d1 = w << k + 16 | y << k;
1229 #endif
1230  ret_d:
1231 #ifdef VAX
1232         word0(d) = d0 >> 16 | d0 << 16;
1233         word1(d) = d1 >> 16 | d1 << 16;
1234 #else
1235 #undef d0
1236 #undef d1
1237 #endif
1238         return dval(d);
1239         }
1240
1241  static Bigint *
1242 d2b
1243 #ifdef KR_headers
1244         (d, e, bits) double d; int *e, *bits;
1245 #else
1246         (double d, int *e, int *bits)
1247 #endif
1248 {
1249         Bigint *b;
1250         int de, k;
1251         ULong *x, y, z;
1252 #ifndef Sudden_Underflow
1253         int i;
1254 #endif
1255 #ifdef VAX
1256         ULong d0, d1;
1257         d0 = word0(d) >> 16 | word0(d) << 16;
1258         d1 = word1(d) >> 16 | word1(d) << 16;
1259 #else
1260 #define d0 word0(d)
1261 #define d1 word1(d)
1262 #endif
1263
1264 #ifdef Pack_32
1265         b = Balloc(1);
1266 #else
1267         b = Balloc(2);
1268 #endif
1269         x = b->x;
1270
1271         z = d0 & Frac_mask;
1272         d0 &= 0x7fffffff;       /* clear sign bit, which we ignore */
1273 #ifdef Sudden_Underflow
1274         de = (int)(d0 >> Exp_shift);
1275 #ifndef IBM
1276         z |= Exp_msk11;
1277 #endif
1278 #else
1279         if ((de = (int)(d0 >> Exp_shift)))
1280                 z |= Exp_msk1;
1281 #endif
1282 #ifdef Pack_32
1283         if ((y = d1)) {
1284                 if ((k = lo0bits(&y))) {
1285                         x[0] = y | (z << (32 - k));
1286                         z >>= k;
1287                         }
1288                 else
1289                         x[0] = y;
1290 #ifndef Sudden_Underflow
1291                 i =
1292 #endif
1293                     b->wds = (x[1] = z) ? 2 : 1;
1294                 }
1295         else {
1296 #ifdef DEBUG
1297                 if (!z)
1298                         Bug("Zero passed to d2b");
1299 #endif
1300                 k = lo0bits(&z);
1301                 x[0] = z;
1302 #ifndef Sudden_Underflow
1303                 i =
1304 #endif
1305                     b->wds = 1;
1306                 k += 32;
1307                 }
1308 #else
1309         if (y = d1) {
1310                 if (k = lo0bits(&y))
1311                         if (k >= 16) {
1312                                 x[0] = y | z << 32 - k & 0xffff;
1313                                 x[1] = z >> k - 16 & 0xffff;
1314                                 x[2] = z >> k;
1315                                 i = 2;
1316                                 }
1317                         else {
1318                                 x[0] = y & 0xffff;
1319                                 x[1] = y >> 16 | z << 16 - k & 0xffff;
1320                                 x[2] = z >> k & 0xffff;
1321                                 x[3] = z >> k+16;
1322                                 i = 3;
1323                                 }
1324                 else {
1325                         x[0] = y & 0xffff;
1326                         x[1] = y >> 16;
1327                         x[2] = z & 0xffff;
1328                         x[3] = z >> 16;
1329                         i = 3;
1330                         }
1331                 }
1332         else {
1333 #ifdef DEBUG
1334                 if (!z)
1335                         Bug("Zero passed to d2b");
1336 #endif
1337                 k = lo0bits(&z);
1338                 if (k >= 16) {
1339                         x[0] = z;
1340                         i = 0;
1341                         }
1342                 else {
1343                         x[0] = z & 0xffff;
1344                         x[1] = z >> 16;
1345                         i = 1;
1346                         }
1347                 k += 32;
1348                 }
1349         while(!x[i])
1350                 --i;
1351         b->wds = i + 1;
1352 #endif
1353 #ifndef Sudden_Underflow
1354         if (de) {
1355 #endif
1356 #ifdef IBM
1357                 *e = (de - Bias - (P-1) << 2) + k;
1358                 *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
1359 #else
1360                 *e = de - Bias - (P-1) + k;
1361                 *bits = P - k;
1362 #endif
1363 #ifndef Sudden_Underflow
1364                 }
1365         else {
1366                 *e = de - Bias - (P-1) + 1 + k;
1367 #ifdef Pack_32
1368                 *bits = 32*i - hi0bits(x[i-1]);
1369 #else
1370                 *bits = (i+2)*16 - hi0bits(x[i]);
1371 #endif
1372                 }
1373 #endif
1374         return b;
1375         }
1376 #undef d0
1377 #undef d1
1378
1379  static double
1380 ratio
1381 #ifdef KR_headers
1382         (a, b) Bigint *a, *b;
1383 #else
1384         (Bigint *a, Bigint *b)
1385 #endif
1386 {
1387         double da, db;
1388         int k, ka, kb;
1389
1390         dval(da) = b2d(a, &ka);
1391         dval(db) = b2d(b, &kb);
1392 #ifdef Pack_32
1393         k = ka - kb + 32*(a->wds - b->wds);
1394 #else
1395         k = ka - kb + 16*(a->wds - b->wds);
1396 #endif
1397 #ifdef IBM
1398         if (k > 0) {
1399                 word0(da) += (k >> 2)*Exp_msk1;
1400                 if (k &= 3)
1401                         dval(da) *= 1 << k;
1402                 }
1403         else {
1404                 k = -k;
1405                 word0(db) += (k >> 2)*Exp_msk1;
1406                 if (k &= 3)
1407                         dval(db) *= 1 << k;
1408                 }
1409 #else
1410         if (k > 0)
1411                 word0(da) += k*Exp_msk1;
1412         else {
1413                 k = -k;
1414                 word0(db) += k*Exp_msk1;
1415                 }
1416 #endif
1417         return dval(da) / dval(db);
1418         }
1419
1420  static CONST double
1421 tens[] = {
1422                 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1423                 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1424                 1e20, 1e21, 1e22
1425 #ifdef VAX
1426                 , 1e23, 1e24
1427 #endif
1428                 };
1429
1430  static CONST double
1431 #ifdef IEEE_Arith
1432 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1433 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
1434 #ifdef Avoid_Underflow
1435                 9007199254740992.*9007199254740992.e-256
1436                 /* = 2^106 * 1e-53 */
1437 #else
1438                 1e-256
1439 #endif
1440                 };
1441 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
1442 /* flag unnecessarily.  It leads to a song and dance at the end of strtod. */
1443 #define Scale_Bit 0x10
1444 #define n_bigtens 5
1445 #else
1446 #ifdef IBM
1447 bigtens[] = { 1e16, 1e32, 1e64 };
1448 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 };
1449 #define n_bigtens 3
1450 #else
1451 bigtens[] = { 1e16, 1e32 };
1452 static CONST double tinytens[] = { 1e-16, 1e-32 };
1453 #define n_bigtens 2
1454 #endif
1455 #endif
1456
1457 #ifndef IEEE_Arith
1458 #undef INFNAN_CHECK
1459 #endif
1460
1461 #ifdef INFNAN_CHECK
1462
1463 #ifndef NAN_WORD0
1464 #define NAN_WORD0 0x7ff80000
1465 #endif
1466
1467 #ifndef NAN_WORD1
1468 #define NAN_WORD1 0
1469 #endif
1470
1471  static int
1472 match
1473 #ifdef KR_headers
1474         (sp, t) char **sp, *t;
1475 #else
1476         (CONST char **sp, char *t)
1477 #endif
1478 {
1479         int c, d;
1480         CONST char *s = *sp;
1481
1482         while(d = *t++) {
1483                 if ((c = *++s) >= 'A' && c <= 'Z')
1484                         c += 'a' - 'A';
1485                 if (c != d)
1486                         return 0;
1487                 }
1488         *sp = s + 1;
1489         return 1;
1490         }
1491
1492 #ifndef No_Hex_NaN
1493  static void
1494 hexnan
1495 #ifdef KR_headers
1496         (rvp, sp) double *rvp; CONST char **sp;
1497 #else
1498         (double *rvp, CONST char **sp)
1499 #endif
1500 {
1501         ULong c, x[2];
1502         CONST char *s;
1503         int havedig, udx0, xshift;
1504
1505         x[0] = x[1] = 0;
1506         havedig = xshift = 0;
1507         udx0 = 1;
1508         s = *sp;
1509         while(c = *(CONST unsigned char*)++s) {
1510                 if (c >= '0' && c <= '9')
1511                         c -= '0';
1512                 else if (c >= 'a' && c <= 'f')
1513                         c += 10 - 'a';
1514                 else if (c >= 'A' && c <= 'F')
1515                         c += 10 - 'A';
1516                 else if (c <= ' ') {
1517                         if (udx0 && havedig) {
1518                                 udx0 = 0;
1519                                 xshift = 1;
1520                                 }
1521                         continue;
1522                         }
1523                 else if (/*(*/ c == ')' && havedig) {
1524                         *sp = s + 1;
1525                         break;
1526                         }
1527                 else
1528                         return; /* invalid form: don't change *sp */
1529                 havedig = 1;
1530                 if (xshift) {
1531                         xshift = 0;
1532                         x[0] = x[1];
1533                         x[1] = 0;
1534                         }
1535                 if (udx0)
1536                         x[0] = (x[0] << 4) | (x[1] >> 28);
1537                 x[1] = (x[1] << 4) | c;
1538                 }
1539         if ((x[0] &= 0xfffff) || x[1]) {
1540                 word0(*rvp) = Exp_mask | x[0];
1541                 word1(*rvp) = x[1];
1542                 }
1543         }
1544 #endif /*No_Hex_NaN*/
1545 #endif /* INFNAN_CHECK */
1546
1547  double
1548 mono_strtod
1549 #ifdef KR_headers
1550         (s00, se) CONST char *s00; char **se;
1551 #else
1552         (CONST char *s00, char **se)
1553 #endif
1554 {
1555 #ifdef Avoid_Underflow
1556         int scale;
1557 #endif
1558         int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
1559                  e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1560         CONST char *s, *s0, *s1;
1561         double aadj, aadj1, adj, rv, rv0;
1562         Long L;
1563         ULong y, z;
1564         Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
1565 #ifdef SET_INEXACT
1566         int inexact, oldinexact;
1567 #endif
1568 #ifdef Honor_FLT_ROUNDS
1569         int rounding;
1570 #endif
1571 #ifdef USE_LOCALE
1572         CONST char *s2;
1573 #endif
1574
1575         sign = nz0 = nz = 0;
1576         dval(rv) = 0.;
1577         for(s = s00;;s++) switch(*s) {
1578                 case '-':
1579                         sign = 1;
1580                         /* no break */
1581                 case '+':
1582                         if (*++s)
1583                                 goto break2;
1584                         /* no break */
1585                 case 0:
1586                         goto ret0;
1587                 case '\t':
1588                 case '\n':
1589                 case '\v':
1590                 case '\f':
1591                 case '\r':
1592                 case ' ':
1593                         continue;
1594                 default:
1595                         goto break2;
1596                 }
1597  break2:
1598         if (*s == '0') {
1599                 nz0 = 1;
1600                 while(*++s == '0') ;
1601                 if (!*s)
1602                         goto ret;
1603                 }
1604         s0 = s;
1605         y = z = 0;
1606         for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
1607                 if (nd < 9)
1608                         y = 10*y + c - '0';
1609                 else if (nd < 16)
1610                         z = 10*z + c - '0';
1611         nd0 = nd;
1612 #ifdef USE_LOCALE
1613         s1 = localeconv()->decimal_point;
1614         if (c == *s1) {
1615                 c = '.';
1616                 if (*++s1) {
1617                         s2 = s;
1618                         for(;;) {
1619                                 if (*++s2 != *s1) {
1620                                         c = 0;
1621                                         break;
1622                                         }
1623                                 if (!*++s1) {
1624                                         s = s2;
1625                                         break;
1626                                         }
1627                                 }
1628                         }
1629                 }
1630 #endif
1631         if (c == '.') {
1632                 c = *++s;
1633                 if (!nd) {
1634                         for(; c == '0'; c = *++s)
1635                                 nz++;
1636                         if (c > '0' && c <= '9') {
1637                                 s0 = s;
1638                                 nf += nz;
1639                                 nz = 0;
1640                                 goto have_dig;
1641                                 }
1642                         goto dig_done;
1643                         }
1644                 for(; c >= '0' && c <= '9'; c = *++s) {
1645  have_dig:
1646                         nz++;
1647                         if (c -= '0') {
1648                                 nf += nz;
1649                                 for(i = 1; i < nz; i++)
1650                                         if (nd++ < 9)
1651                                                 y *= 10;
1652                                         else if (nd <= DBL_DIG + 1)
1653                                                 z *= 10;
1654                                 if (nd++ < 9)
1655                                         y = 10*y + c;
1656                                 else if (nd <= DBL_DIG + 1)
1657                                         z = 10*z + c;
1658                                 nz = 0;
1659                                 }
1660                         }
1661                 }
1662  dig_done:
1663         e = 0;
1664         if (c == 'e' || c == 'E') {
1665                 if (!nd && !nz && !nz0) {
1666                         goto ret0;
1667                         }
1668                 s00 = s;
1669                 esign = 0;
1670                 switch(c = *++s) {
1671                         case '-':
1672                                 esign = 1;
1673                         case '+':
1674                                 c = *++s;
1675                         }
1676                 if (c >= '0' && c <= '9') {
1677                         while(c == '0')
1678                                 c = *++s;
1679                         if (c > '0' && c <= '9') {
1680                                 L = c - '0';
1681                                 s1 = s;
1682                                 while((c = *++s) >= '0' && c <= '9')
1683                                         L = 10*L + c - '0';
1684                                 if (s - s1 > 8 || L > 19999)
1685                                         /* Avoid confusion from exponents
1686                                          * so large that e might overflow.
1687                                          */
1688                                         e = 19999; /* safe for 16 bit ints */
1689                                 else
1690                                         e = (int)L;
1691                                 if (esign)
1692                                         e = -e;
1693                                 }
1694                         else
1695                                 e = 0;
1696                         }
1697                 else
1698                         s = s00;
1699                 }
1700         if (!nd) {
1701                 if (!nz && !nz0) {
1702 #ifdef INFNAN_CHECK
1703                         /* Check for Nan and Infinity */
1704                         switch(c) {
1705                           case 'i':
1706                           case 'I':
1707                                 if (match(&s,"nf")) {
1708                                         --s;
1709                                         if (!match(&s,"inity"))
1710                                                 ++s;
1711                                         word0(rv) = 0x7ff00000;
1712                                         word1(rv) = 0;
1713                                         goto ret;
1714                                         }
1715                                 break;
1716                           case 'n':
1717                           case 'N':
1718                                 if (match(&s, "an")) {
1719                                         word0(rv) = NAN_WORD0;
1720                                         word1(rv) = NAN_WORD1;
1721 #ifndef No_Hex_NaN
1722                                         if (*s == '(') /*)*/
1723                                                 hexnan(&rv, &s);
1724 #endif
1725                                         goto ret;
1726                                         }
1727                           }
1728 #endif /* INFNAN_CHECK */
1729  ret0:
1730                         s = s00;
1731                         sign = 0;
1732                         }
1733                 goto ret;
1734                 }
1735         e1 = e -= nf;
1736
1737         /* Now we have nd0 digits, starting at s0, followed by a
1738          * decimal point, followed by nd-nd0 digits.  The number we're
1739          * after is the integer represented by those digits times
1740          * 10**e */
1741
1742         if (!nd0)
1743                 nd0 = nd;
1744         k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1745         dval(rv) = y;
1746         if (k > 9) {
1747 #ifdef SET_INEXACT
1748                 if (k > DBL_DIG)
1749                         oldinexact = get_inexact();
1750 #endif
1751                 dval(rv) = tens[k - 9] * dval(rv) + z;
1752                 }
1753         bd0 = 0;
1754         if (nd <= DBL_DIG
1755 #ifndef RND_PRODQUOT
1756 #ifndef Honor_FLT_ROUNDS
1757                 && Flt_Rounds == 1
1758 #endif
1759 #endif
1760                         ) {
1761                 if (!e)
1762                         goto ret;
1763                 if (e > 0) {
1764                         if (e <= Ten_pmax) {
1765 #ifdef VAX
1766                                 goto vax_ovfl_check;
1767 #else
1768 #ifdef Honor_FLT_ROUNDS
1769                                 /* round correctly FLT_ROUNDS = 2 or 3 */
1770                                 if (sign) {
1771                                         rv = -rv;
1772                                         sign = 0;
1773                                         }
1774 #endif
1775                                 /* rv = */ rounded_product(dval(rv), tens[e]);
1776                                 goto ret;
1777 #endif
1778                                 }
1779                         i = DBL_DIG - nd;
1780                         if (e <= Ten_pmax + i) {
1781                                 /* A fancier test would sometimes let us do
1782                                  * this for larger i values.
1783                                  */
1784 #ifdef Honor_FLT_ROUNDS
1785                                 /* round correctly FLT_ROUNDS = 2 or 3 */
1786                                 if (sign) {
1787                                         rv = -rv;
1788                                         sign = 0;
1789                                         }
1790 #endif
1791                                 e -= i;
1792                                 dval(rv) *= tens[i];
1793 #ifdef VAX
1794                                 /* VAX exponent range is so narrow we must
1795                                  * worry about overflow here...
1796                                  */
1797  vax_ovfl_check:
1798                                 word0(rv) -= P*Exp_msk1;
1799                                 /* rv = */ rounded_product(dval(rv), tens[e]);
1800                                 if ((word0(rv) & Exp_mask)
1801                                  > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
1802                                         goto ovfl;
1803                                 word0(rv) += P*Exp_msk1;
1804 #else
1805                                 /* rv = */ rounded_product(dval(rv), tens[e]);
1806 #endif
1807                                 goto ret;
1808                                 }
1809                         }
1810 #ifndef Inaccurate_Divide
1811                 else if (e >= -Ten_pmax) {
1812 #ifdef Honor_FLT_ROUNDS
1813                         /* round correctly FLT_ROUNDS = 2 or 3 */
1814                         if (sign) {
1815                                 rv = -rv;
1816                                 sign = 0;
1817                                 }
1818 #endif
1819                         /* rv = */ rounded_quotient(dval(rv), tens[-e]);
1820                         goto ret;
1821                         }
1822 #endif
1823                 }
1824         e1 += nd - k;
1825
1826 #ifdef IEEE_Arith
1827 #ifdef SET_INEXACT
1828         inexact = 1;
1829         if (k <= DBL_DIG)
1830                 oldinexact = get_inexact();
1831 #endif
1832 #ifdef Avoid_Underflow
1833         scale = 0;
1834 #endif
1835 #ifdef Honor_FLT_ROUNDS
1836         if ((rounding = Flt_Rounds) >= 2) {
1837                 if (sign)
1838                         rounding = rounding == 2 ? 0 : 2;
1839                 else
1840                         if (rounding != 2)
1841                                 rounding = 0;
1842                 }
1843 #endif
1844 #endif /*IEEE_Arith*/
1845
1846         /* Get starting approximation = rv * 10**e1 */
1847
1848         if (e1 > 0) {
1849                 if ((i = e1 & 15))
1850                         dval(rv) *= tens[i];
1851                 if (e1 &= ~15) {
1852                         if (e1 > DBL_MAX_10_EXP) {
1853  ovfl:
1854 #ifndef NO_ERRNO
1855                                 errno = ERANGE;
1856 #endif
1857                                 /* Can't trust HUGE_VAL */
1858 #ifdef IEEE_Arith
1859 #ifdef Honor_FLT_ROUNDS
1860                                 switch(rounding) {
1861                                   case 0: /* toward 0 */
1862                                   case 3: /* toward -infinity */
1863                                         word0(rv) = Big0;
1864                                         word1(rv) = Big1;
1865                                         break;
1866                                   default:
1867                                         word0(rv) = Exp_mask;
1868                                         word1(rv) = 0;
1869                                   }
1870 #else /*Honor_FLT_ROUNDS*/
1871                                 word0(rv) = Exp_mask;
1872                                 word1(rv) = 0;
1873 #endif /*Honor_FLT_ROUNDS*/
1874 #ifdef SET_INEXACT
1875                                 /* set overflow bit */
1876                                 dval(rv0) = 1e300;
1877                                 dval(rv0) *= dval(rv0);
1878 #endif
1879 #else /*IEEE_Arith*/
1880                                 word0(rv) = Big0;
1881                                 word1(rv) = Big1;
1882 #endif /*IEEE_Arith*/
1883                                 if (bd0)
1884                                         goto retfree;
1885                                 goto ret;
1886                                 }
1887                         e1 >>= 4;
1888                         for(j = 0; e1 > 1; j++, e1 >>= 1)
1889                                 if (e1 & 1)
1890                                         dval(rv) *= bigtens[j];
1891                 /* The last multiplication could overflow. */
1892                         word0(rv) -= P*Exp_msk1;
1893                         dval(rv) *= bigtens[j];
1894                         if ((z = word0(rv) & Exp_mask)
1895                          > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1896                                 goto ovfl;
1897                         if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1898                                 /* set to largest number */
1899                                 /* (Can't trust DBL_MAX) */
1900                                 word0(rv) = Big0;
1901                                 word1(rv) = Big1;
1902                                 }
1903                         else
1904                                 word0(rv) += P*Exp_msk1;
1905                         }
1906                 }
1907         else if (e1 < 0) {
1908                 e1 = -e1;
1909                 if ((i = e1 & 15))
1910                         dval(rv) /= tens[i];
1911                 if (e1 >>= 4) {
1912                         if (e1 >= 1 << n_bigtens)
1913                                 goto undfl;
1914 #ifdef Avoid_Underflow
1915                         if (e1 & Scale_Bit)
1916                                 scale = 2*P;
1917                         for(j = 0; e1 > 0; j++, e1 >>= 1)
1918                                 if (e1 & 1)
1919                                         dval(rv) *= tinytens[j];
1920                         if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask)
1921                                                 >> Exp_shift)) > 0) {
1922                                 /* scaled rv is denormal; zap j low bits */
1923                                 if (j >= 32) {
1924                                         word1(rv) = 0;
1925                                         if (j >= 53)
1926                                          word0(rv) = (P+2)*Exp_msk1;
1927                                         else
1928                                          word0(rv) &= 0xffffffff << (j-32);
1929                                         }
1930                                 else
1931                                         word1(rv) &= 0xffffffff << j;
1932                                 }
1933 #else
1934                         for(j = 0; e1 > 1; j++, e1 >>= 1)
1935                                 if (e1 & 1)
1936                                         dval(rv) *= tinytens[j];
1937                         /* The last multiplication could underflow. */
1938                         dval(rv0) = dval(rv);
1939                         dval(rv) *= tinytens[j];
1940                         if (!dval(rv)) {
1941                                 dval(rv) = 2.*dval(rv0);
1942                                 dval(rv) *= tinytens[j];
1943 #endif
1944                                 if (!dval(rv)) {
1945  undfl:
1946                                         dval(rv) = 0.;
1947 #ifndef NO_ERRNO
1948                                         errno = ERANGE;
1949 #endif
1950                                         if (bd0)
1951                                                 goto retfree;
1952                                         goto ret;
1953                                         }
1954 #ifndef Avoid_Underflow
1955                                 word0(rv) = Tiny0;
1956                                 word1(rv) = Tiny1;
1957                                 /* The refinement below will clean
1958                                  * this approximation up.
1959                                  */
1960                                 }
1961 #endif
1962                         }
1963                 }
1964
1965         /* Now the hard part -- adjusting rv to the correct value.*/
1966
1967         /* Put digits into bd: true value = bd * 10^e */
1968
1969         bd0 = s2b(s0, nd0, nd, y);
1970
1971         for(;;) {
1972                 bd = Balloc(bd0->k);
1973                 Bcopy(bd, bd0);
1974                 bb = d2b(dval(rv), &bbe, &bbbits);      /* rv = bb * 2^bbe */
1975                 bs = i2b(1);
1976
1977                 if (e >= 0) {
1978                         bb2 = bb5 = 0;
1979                         bd2 = bd5 = e;
1980                         }
1981                 else {
1982                         bb2 = bb5 = -e;
1983                         bd2 = bd5 = 0;
1984                         }
1985                 if (bbe >= 0)
1986                         bb2 += bbe;
1987                 else
1988                         bd2 -= bbe;
1989                 bs2 = bb2;
1990 #ifdef Honor_FLT_ROUNDS
1991                 if (rounding != 1)
1992                         bs2++;
1993 #endif
1994 #ifdef Avoid_Underflow
1995                 j = bbe - scale;
1996                 i = j + bbbits - 1;     /* logb(rv) */
1997                 if (i < Emin)   /* denormal */
1998                         j += P - Emin;
1999                 else
2000                         j = P + 1 - bbbits;
2001 #else /*Avoid_Underflow*/
2002 #ifdef Sudden_Underflow
2003 #ifdef IBM
2004                 j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
2005 #else
2006                 j = P + 1 - bbbits;
2007 #endif
2008 #else /*Sudden_Underflow*/
2009                 j = bbe;
2010                 i = j + bbbits - 1;     /* logb(rv) */
2011                 if (i < Emin)   /* denormal */
2012                         j += P - Emin;
2013                 else
2014                         j = P + 1 - bbbits;
2015 #endif /*Sudden_Underflow*/
2016 #endif /*Avoid_Underflow*/
2017                 bb2 += j;
2018                 bd2 += j;
2019 #ifdef Avoid_Underflow
2020                 bd2 += scale;
2021 #endif
2022                 i = bb2 < bd2 ? bb2 : bd2;
2023                 if (i > bs2)
2024                         i = bs2;
2025                 if (i > 0) {
2026                         bb2 -= i;
2027                         bd2 -= i;
2028                         bs2 -= i;
2029                         }
2030                 if (bb5 > 0) {
2031                         bs = pow5mult(bs, bb5);
2032                         bb1 = mult(bs, bb);
2033                         Bfree(bb);
2034                         bb = bb1;
2035                         }
2036                 if (bb2 > 0)
2037                         bb = lshift(bb, bb2);
2038                 if (bd5 > 0)
2039                         bd = pow5mult(bd, bd5);
2040                 if (bd2 > 0)
2041                         bd = lshift(bd, bd2);
2042                 if (bs2 > 0)
2043                         bs = lshift(bs, bs2);
2044                 delta = diff(bb, bd);
2045                 dsign = delta->sign;
2046                 delta->sign = 0;
2047                 i = cmp(delta, bs);
2048 #ifdef Honor_FLT_ROUNDS
2049                 if (rounding != 1) {
2050                         if (i < 0) {
2051                                 /* Error is less than an ulp */
2052                                 if (!delta->x[0] && delta->wds <= 1) {
2053                                         /* exact */
2054 #ifdef SET_INEXACT
2055                                         inexact = 0;
2056 #endif
2057                                         break;
2058                                         }
2059                                 if (rounding) {
2060                                         if (dsign) {
2061                                                 adj = 1.;
2062                                                 goto apply_adj;
2063                                                 }
2064                                         }
2065                                 else if (!dsign) {
2066                                         adj = -1.;
2067                                         if (!word1(rv)
2068                                          && !(word0(rv) & Frac_mask)) {
2069                                                 y = word0(rv) & Exp_mask;
2070 #ifdef Avoid_Underflow
2071                                                 if (!scale || y > 2*P*Exp_msk1)
2072 #else
2073                                                 if (y)
2074 #endif
2075                                                   {
2076                                                   delta = lshift(delta,Log2P);
2077                                                   if (cmp(delta, bs) <= 0)
2078                                                         adj = -0.5;
2079                                                   }
2080                                                 }
2081  apply_adj:
2082 #ifdef Avoid_Underflow
2083                                         if (scale && (y = word0(rv) & Exp_mask)
2084                                                 <= 2*P*Exp_msk1)
2085                                           word0(adj) += (2*P+1)*Exp_msk1 - y;
2086 #else
2087 #ifdef Sudden_Underflow
2088                                         if ((word0(rv) & Exp_mask) <=
2089                                                         P*Exp_msk1) {
2090                                                 word0(rv) += P*Exp_msk1;
2091                                                 dval(rv) += adj*ulp(dval(rv));
2092                                                 word0(rv) -= P*Exp_msk1;
2093                                                 }
2094                                         else
2095 #endif /*Sudden_Underflow*/
2096 #endif /*Avoid_Underflow*/
2097                                         dval(rv) += adj*ulp(dval(rv));
2098                                         }
2099                                 break;
2100                                 }
2101                         adj = ratio(delta, bs);
2102                         if (adj < 1.)
2103                                 adj = 1.;
2104                         if (adj <= 0x7ffffffe) {
2105                                 /* adj = rounding ? ceil(adj) : floor(adj); */
2106                                 y = adj;
2107                                 if (y != adj) {
2108                                         if (!((rounding>>1) ^ dsign))
2109                                                 y++;
2110                                         adj = y;
2111                                         }
2112                                 }
2113 #ifdef Avoid_Underflow
2114                         if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2115                                 word0(adj) += (2*P+1)*Exp_msk1 - y;
2116 #else
2117 #ifdef Sudden_Underflow
2118                         if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2119                                 word0(rv) += P*Exp_msk1;
2120                                 adj *= ulp(dval(rv));
2121                                 if (dsign)
2122                                         dval(rv) += adj;
2123                                 else
2124                                         dval(rv) -= adj;
2125                                 word0(rv) -= P*Exp_msk1;
2126                                 goto cont;
2127                                 }
2128 #endif /*Sudden_Underflow*/
2129 #endif /*Avoid_Underflow*/
2130                         adj *= ulp(dval(rv));
2131                         if (dsign)
2132                                 dval(rv) += adj;
2133                         else
2134                                 dval(rv) -= adj;
2135                         goto cont;
2136                         }
2137 #endif /*Honor_FLT_ROUNDS*/
2138
2139                 if (i < 0) {
2140                         /* Error is less than half an ulp -- check for
2141                          * special case of mantissa a power of two.
2142                          */
2143                         if (dsign || word1(rv) || word0(rv) & Bndry_mask
2144 #ifdef IEEE_Arith
2145 #ifdef Avoid_Underflow
2146                          || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
2147 #else
2148                          || (word0(rv) & Exp_mask) <= Exp_msk1
2149 #endif
2150 #endif
2151                                 ) {
2152 #ifdef SET_INEXACT
2153                                 if (!delta->x[0] && delta->wds <= 1)
2154                                         inexact = 0;
2155 #endif
2156                                 break;
2157                                 }
2158                         if (!delta->x[0] && delta->wds <= 1) {
2159                                 /* exact result */
2160 #ifdef SET_INEXACT
2161                                 inexact = 0;
2162 #endif
2163                                 break;
2164                                 }
2165                         delta = lshift(delta,Log2P);
2166                         if (cmp(delta, bs) > 0)
2167                                 goto drop_down;
2168                         break;
2169                         }
2170                 if (i == 0) {
2171                         /* exactly half-way between */
2172                         if (dsign) {
2173                                 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
2174                                  &&  word1(rv) == (
2175 #ifdef Avoid_Underflow
2176                         (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2177                 ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
2178 #endif
2179                                                    0xffffffff)) {
2180                                         /*boundary case -- increment exponent*/
2181                                         word0(rv) = (word0(rv) & Exp_mask)
2182                                                 + Exp_msk1
2183 #ifdef IBM
2184                                                 | Exp_msk1 >> 4
2185 #endif
2186                                                 ;
2187                                         word1(rv) = 0;
2188 #ifdef Avoid_Underflow
2189                                         dsign = 0;
2190 #endif
2191                                         break;
2192                                         }
2193                                 }
2194                         else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
2195  drop_down:
2196                                 /* boundary case -- decrement exponent */
2197 #ifdef Sudden_Underflow /*{{*/
2198                                 L = word0(rv) & Exp_mask;
2199 #ifdef IBM
2200                                 if (L <  Exp_msk1)
2201 #else
2202 #ifdef Avoid_Underflow
2203                                 if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
2204 #else
2205                                 if (L <= Exp_msk1)
2206 #endif /*Avoid_Underflow*/
2207 #endif /*IBM*/
2208                                         goto undfl;
2209                                 L -= Exp_msk1;
2210 #else /*Sudden_Underflow}{*/
2211 #ifdef Avoid_Underflow
2212                                 if (scale) {
2213                                         L = word0(rv) & Exp_mask;
2214                                         if (L <= (2*P+1)*Exp_msk1) {
2215                                                 if (L > (P+2)*Exp_msk1)
2216                                                         /* round even ==> */
2217                                                         /* accept rv */
2218                                                         break;
2219                                                 /* rv = smallest denormal */
2220                                                 goto undfl;
2221                                                 }
2222                                         }
2223 #endif /*Avoid_Underflow*/
2224                                 L = (word0(rv) & Exp_mask) - Exp_msk1;
2225 #endif /*Sudden_Underflow}}*/
2226                                 word0(rv) = L | Bndry_mask1;
2227                                 word1(rv) = 0xffffffff;
2228 #ifdef IBM
2229                                 goto cont;
2230 #else
2231                                 break;
2232 #endif
2233                                 }
2234 #ifndef ROUND_BIASED
2235                         if (!(word1(rv) & LSB))
2236                                 break;
2237 #endif
2238                         if (dsign)
2239                                 dval(rv) += ulp(dval(rv));
2240 #ifndef ROUND_BIASED
2241                         else {
2242                                 dval(rv) -= ulp(dval(rv));
2243 #ifndef Sudden_Underflow
2244                                 if (!dval(rv))
2245                                         goto undfl;
2246 #endif
2247                                 }
2248 #ifdef Avoid_Underflow
2249                         dsign = 1 - dsign;
2250 #endif
2251 #endif
2252                         break;
2253                         }
2254                 if ((aadj = ratio(delta, bs)) <= 2.) {
2255                         if (dsign)
2256                                 aadj = aadj1 = 1.;
2257                         else if (word1(rv) || word0(rv) & Bndry_mask) {
2258 #ifndef Sudden_Underflow
2259                                 if (word1(rv) == Tiny1 && !word0(rv))
2260                                         goto undfl;
2261 #endif
2262                                 aadj = 1.;
2263                                 aadj1 = -1.;
2264                                 }
2265                         else {
2266                                 /* special case -- power of FLT_RADIX to be */
2267                                 /* rounded down... */
2268
2269                                 if (aadj < 2./FLT_RADIX)
2270                                         aadj = 1./FLT_RADIX;
2271                                 else
2272                                         aadj *= 0.5;
2273                                 aadj1 = -aadj;
2274                                 }
2275                         }
2276                 else {
2277                         aadj *= 0.5;
2278                         aadj1 = dsign ? aadj : -aadj;
2279 #ifdef Check_FLT_ROUNDS
2280                         switch(Rounding) {
2281                                 case 2: /* towards +infinity */
2282                                         aadj1 -= 0.5;
2283                                         break;
2284                                 case 0: /* towards 0 */
2285                                 case 3: /* towards -infinity */
2286                                         aadj1 += 0.5;
2287                                 }
2288 #else
2289                         if (Flt_Rounds == 0)
2290                                 aadj1 += 0.5;
2291 #endif /*Check_FLT_ROUNDS*/
2292                         }
2293                 y = word0(rv) & Exp_mask;
2294
2295                 /* Check for overflow */
2296
2297                 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2298                         dval(rv0) = dval(rv);
2299                         word0(rv) -= P*Exp_msk1;
2300                         adj = aadj1 * ulp(dval(rv));
2301                         dval(rv) += adj;
2302                         if ((word0(rv) & Exp_mask) >=
2303                                         Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2304                                 if (word0(rv0) == Big0 && word1(rv0) == Big1)
2305                                         goto ovfl;
2306                                 word0(rv) = Big0;
2307                                 word1(rv) = Big1;
2308                                 goto cont;
2309                                 }
2310                         else
2311                                 word0(rv) += P*Exp_msk1;
2312                         }
2313                 else {
2314 #ifdef Avoid_Underflow
2315                         if (scale && y <= 2*P*Exp_msk1) {
2316                                 if (aadj <= 0x7fffffff) {
2317                                         if ((z = aadj) <= 0)
2318                                                 z = 1;
2319                                         aadj = z;
2320                                         aadj1 = dsign ? aadj : -aadj;
2321                                         }
2322                                 word0(aadj1) += (2*P+1)*Exp_msk1 - y;
2323                                 }
2324                         adj = aadj1 * ulp(dval(rv));
2325                         dval(rv) += adj;
2326 #else
2327 #ifdef Sudden_Underflow
2328                         if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2329                                 dval(rv0) = dval(rv);
2330                                 word0(rv) += P*Exp_msk1;
2331                                 adj = aadj1 * ulp(dval(rv));
2332                                 dval(rv) += adj;
2333 #ifdef IBM
2334                                 if ((word0(rv) & Exp_mask) <  P*Exp_msk1)
2335 #else
2336                                 if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
2337 #endif
2338                                         {
2339                                         if (word0(rv0) == Tiny0
2340                                          && word1(rv0) == Tiny1)
2341                                                 goto undfl;
2342                                         word0(rv) = Tiny0;
2343                                         word1(rv) = Tiny1;
2344                                         goto cont;
2345                                         }
2346                                 else
2347                                         word0(rv) -= P*Exp_msk1;
2348                                 }
2349                         else {
2350                                 adj = aadj1 * ulp(dval(rv));
2351                                 dval(rv) += adj;
2352                                 }
2353 #else /*Sudden_Underflow*/
2354                         /* Compute adj so that the IEEE rounding rules will
2355                          * correctly round rv + adj in some half-way cases.
2356                          * If rv * ulp(rv) is denormalized (i.e.,
2357                          * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
2358                          * trouble from bits lost to denormalization;
2359                          * example: 1.2e-307 .
2360                          */
2361                         if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
2362                                 aadj1 = (double)(int)(aadj + 0.5);
2363                                 if (!dsign)
2364                                         aadj1 = -aadj1;
2365                                 }
2366                         adj = aadj1 * ulp(dval(rv));
2367                         dval(rv) += adj;
2368 #endif /*Sudden_Underflow*/
2369 #endif /*Avoid_Underflow*/
2370                         }
2371                 z = word0(rv) & Exp_mask;
2372 #ifndef SET_INEXACT
2373 #ifdef Avoid_Underflow
2374                 if (!scale)
2375 #endif
2376                 if (y == z) {
2377                         /* Can we stop now? */
2378                         L = (Long)aadj;
2379                         aadj -= L;
2380                         /* The tolerances below are conservative. */
2381                         if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
2382                                 if (aadj < .4999999 || aadj > .5000001)
2383                                         break;
2384                                 }
2385                         else if (aadj < .4999999/FLT_RADIX)
2386                                 break;
2387                         }
2388 #endif
2389  cont:
2390                 Bfree(bb);
2391                 Bfree(bd);
2392                 Bfree(bs);
2393                 Bfree(delta);
2394                 }
2395 #ifdef SET_INEXACT
2396         if (inexact) {
2397                 if (!oldinexact) {
2398                         word0(rv0) = Exp_1 + (70 << Exp_shift);
2399                         word1(rv0) = 0;
2400                         dval(rv0) += 1.;
2401                         }
2402                 }
2403         else if (!oldinexact)
2404                 clear_inexact();
2405 #endif
2406 #ifdef Avoid_Underflow
2407         if (scale) {
2408                 word0(rv0) = Exp_1 - 2*P*Exp_msk1;
2409                 word1(rv0) = 0;
2410                 dval(rv) *= dval(rv0);
2411 #ifndef NO_ERRNO
2412                 /* try to avoid the bug of testing an 8087 register value */
2413                 if (word0(rv) == 0 && word1(rv) == 0)
2414                         errno = ERANGE;
2415 #endif
2416                 }
2417 #endif /* Avoid_Underflow */
2418 #ifdef SET_INEXACT
2419         if (inexact && !(word0(rv) & Exp_mask)) {
2420                 /* set underflow bit */
2421                 dval(rv0) = 1e-300;
2422                 dval(rv0) *= dval(rv0);
2423                 }
2424 #endif
2425  retfree:
2426         Bfree(bb);
2427         Bfree(bd);
2428         Bfree(bs);
2429         Bfree(bd0);
2430         Bfree(delta);
2431  ret:
2432         if (se)
2433                 *se = (char *)s;
2434         return sign ? -dval(rv) : dval(rv);
2435         }
2436
2437  static int
2438 quorem
2439 #ifdef KR_headers
2440         (b, S) Bigint *b, *S;
2441 #else
2442         (Bigint *b, Bigint *S)
2443 #endif
2444 {
2445         int n;
2446         ULong *bx, *bxe, q, *sx, *sxe;
2447 #ifdef ULLong
2448         ULLong borrow, carry, y, ys;
2449 #else
2450         ULong borrow, carry, y, ys;
2451 #ifdef Pack_32
2452         ULong si, z, zs;
2453 #endif
2454 #endif
2455
2456         n = S->wds;
2457 #ifdef DEBUG
2458         /*debug*/ if (b->wds > n)
2459         /*debug*/       Bug("oversize b in quorem");
2460 #endif
2461         if (b->wds < n)
2462                 return 0;
2463         sx = S->x;
2464         sxe = sx + --n;
2465         bx = b->x;
2466         bxe = bx + n;
2467         q = *bxe / (*sxe + 1);  /* ensure q <= true quotient */
2468 #ifdef DEBUG
2469         /*debug*/ if (q > 9)
2470         /*debug*/       Bug("oversized quotient in quorem");
2471 #endif
2472         if (q) {
2473                 borrow = 0;
2474                 carry = 0;
2475                 do {
2476 #ifdef ULLong
2477                         ys = *sx++ * (ULLong)q + carry;
2478                         carry = ys >> 32;
2479                         y = *bx - (ys & FFFFFFFF) - borrow;
2480                         borrow = y >> 32 & (ULong)1;
2481                         *bx++ = y & FFFFFFFF;
2482 #else
2483 #ifdef Pack_32
2484                         si = *sx++;
2485                         ys = (si & 0xffff) * q + carry;
2486                         zs = (si >> 16) * q + (ys >> 16);
2487                         carry = zs >> 16;
2488                         y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2489                         borrow = (y & 0x10000) >> 16;
2490                         z = (*bx >> 16) - (zs & 0xffff) - borrow;
2491                         borrow = (z & 0x10000) >> 16;
2492                         Storeinc(bx, z, y);
2493 #else
2494                         ys = *sx++ * q + carry;
2495                         carry = ys >> 16;
2496                         y = *bx - (ys & 0xffff) - borrow;
2497                         borrow = (y & 0x10000) >> 16;
2498                         *bx++ = y & 0xffff;
2499 #endif
2500 #endif
2501                         }
2502                         while(sx <= sxe);
2503                 if (!*bxe) {
2504                         bx = b->x;
2505                         while(--bxe > bx && !*bxe)
2506                                 --n;
2507                         b->wds = n;
2508                         }
2509                 }
2510         if (cmp(b, S) >= 0) {
2511                 q++;
2512                 borrow = 0;
2513                 carry = 0;
2514                 bx = b->x;
2515                 sx = S->x;
2516                 do {
2517 #ifdef ULLong
2518                         ys = *sx++ + carry;
2519                         carry = ys >> 32;
2520                         y = *bx - (ys & FFFFFFFF) - borrow;
2521                         borrow = y >> 32 & (ULong)1;
2522                         *bx++ = y & FFFFFFFF;
2523 #else
2524 #ifdef Pack_32
2525                         si = *sx++;
2526                         ys = (si & 0xffff) + carry;
2527                         zs = (si >> 16) + (ys >> 16);
2528                         carry = zs >> 16;
2529                         y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2530                         borrow = (y & 0x10000) >> 16;
2531                         z = (*bx >> 16) - (zs & 0xffff) - borrow;
2532                         borrow = (z & 0x10000) >> 16;
2533                         Storeinc(bx, z, y);
2534 #else
2535                         ys = *sx++ + carry;
2536                         carry = ys >> 16;
2537                         y = *bx - (ys & 0xffff) - borrow;
2538                         borrow = (y & 0x10000) >> 16;
2539                         *bx++ = y & 0xffff;
2540 #endif
2541 #endif
2542                         }
2543                         while(sx <= sxe);
2544                 bx = b->x;
2545                 bxe = bx + n;
2546                 if (!*bxe) {
2547                         while(--bxe > bx && !*bxe)
2548                                 --n;
2549                         b->wds = n;
2550                         }
2551                 }
2552         return q;
2553         }
2554
2555 #ifndef MULTIPLE_THREADS
2556  static char *dtoa_result;
2557 #endif
2558
2559  static char *
2560 #ifdef KR_headers
2561 rv_alloc(i) int i;
2562 #else
2563 rv_alloc(int i)
2564 #endif
2565 {
2566         int j, k, *r;
2567
2568         j = sizeof(ULong);
2569         for(k = 0;
2570                 sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i;
2571                 j <<= 1)
2572                         k++;
2573         r = (int*)Balloc(k);
2574         *r = k;
2575         return
2576 #ifndef MULTIPLE_THREADS
2577         dtoa_result =
2578 #endif
2579                 (char *)(r+1);
2580         }
2581
2582  static char *
2583 #ifdef KR_headers
2584 nrv_alloc(s, rve, n) char *s, **rve; int n;
2585 #else
2586 nrv_alloc(char *s, char **rve, int n)
2587 #endif
2588 {
2589         char *rv, *t;
2590
2591         t = rv = rv_alloc(n);
2592         while((*t = *s++)) t++;
2593         if (rve)
2594                 *rve = t;
2595         return rv;
2596         }
2597
2598 /* freedtoa(s) must be used to free values s returned by dtoa
2599  * when MULTIPLE_THREADS is #defined.  It should be used in all cases,
2600  * but for consistency with earlier versions of dtoa, it is optional
2601  * when MULTIPLE_THREADS is not defined.
2602  */
2603
2604 static void freedtoa (char *s);
2605
2606 static void
2607 #ifdef KR_headers
2608 freedtoa(s) char *s;
2609 #else
2610 freedtoa(char *s)
2611 #endif
2612 {
2613         Bigint *b = (Bigint *)((int *)s - 1);
2614         b->maxwds = 1 << (b->k = *(int*)b);
2615         Bfree(b);
2616 #ifndef MULTIPLE_THREADS
2617         if (s == dtoa_result)
2618                 dtoa_result = 0;
2619 #endif
2620         }
2621
2622 #if 0
2623 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
2624  *
2625  * Inspired by "How to Print Floating-Point Numbers Accurately" by
2626  * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
2627  *
2628  * Modifications:
2629  *      1. Rather than iterating, we use a simple numeric overestimate
2630  *         to determine k = floor(log10(d)).  We scale relevant
2631  *         quantities using O(log2(k)) rather than O(k) multiplications.
2632  *      2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
2633  *         try to generate digits strictly left to right.  Instead, we
2634  *         compute with fewer bits and propagate the carry if necessary
2635  *         when rounding the final digit up.  This is often faster.
2636  *      3. Under the assumption that input will be rounded nearest,
2637  *         mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
2638  *         That is, we allow equality in stopping tests when the
2639  *         round-nearest rule will give the same floating-point value
2640  *         as would satisfaction of the stopping test with strict
2641  *         inequality.
2642  *      4. We remove common factors of powers of 2 from relevant
2643  *         quantities.
2644  *      5. When converting floating-point integers less than 1e16,
2645  *         we use floating-point arithmetic rather than resorting
2646  *         to multiple-precision integers.
2647  *      6. When asked to produce fewer than 15 digits, we first try
2648  *         to get by with floating-point arithmetic; we resort to
2649  *         multiple-precision integer arithmetic only if we cannot
2650  *         guarantee that the floating-point calculation has given
2651  *         the correctly rounded result.  For k requested digits and
2652  *         "uniformly" distributed input, the probability is
2653  *         something like 10^(k-15) that we must resort to the Long
2654  *         calculation.
2655  */
2656
2657  char *
2658 dtoa
2659 #ifdef KR_headers
2660         (d, mode, ndigits, decpt, sign, rve)
2661         double d; int mode, ndigits, *decpt, *sign; char **rve;
2662 #else
2663         (double d, int mode, int ndigits, int *decpt, int *sign, char **rve)
2664 #endif
2665 {
2666  /*     Arguments ndigits, decpt, sign are similar to those
2667         of ecvt and fcvt; trailing zeros are suppressed from
2668         the returned string.  If not null, *rve is set to point
2669         to the end of the return value.  If d is +-Infinity or NaN,
2670         then *decpt is set to 9999.
2671
2672         mode:
2673                 0 ==> shortest string that yields d when read in
2674                         and rounded to nearest.
2675                 1 ==> like 0, but with Steele & White stopping rule;
2676                         e.g. with IEEE P754 arithmetic , mode 0 gives
2677                         1e23 whereas mode 1 gives 9.999999999999999e22.
2678                 2 ==> max(1,ndigits) significant digits.  This gives a
2679                         return value similar to that of ecvt, except
2680                         that trailing zeros are suppressed.
2681                 3 ==> through ndigits past the decimal point.  This
2682                         gives a return value similar to that from fcvt,
2683                         except that trailing zeros are suppressed, and
2684                         ndigits can be negative.
2685                 4,5 ==> similar to 2 and 3, respectively, but (in
2686                         round-nearest mode) with the tests of mode 0 to
2687                         possibly return a shorter string that rounds to d.
2688                         With IEEE arithmetic and compilation with
2689                         -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
2690                         as modes 2 and 3 when FLT_ROUNDS != 1.
2691                 6-9 ==> Debugging modes similar to mode - 4:  don't try
2692                         fast floating-point estimate (if applicable).
2693
2694                 Values of mode other than 0-9 are treated as mode 0.
2695
2696                 Sufficient space is allocated to the return value
2697                 to hold the suppressed trailing zeros.
2698         */
2699
2700         int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2701                 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2702                 spec_case, try_quick;
2703         Long L;
2704 #ifndef Sudden_Underflow
2705         int denorm;
2706         ULong x;
2707 #endif
2708         Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2709         double d2, ds, eps;
2710         char *s, *s0;
2711 #ifdef Honor_FLT_ROUNDS
2712         int rounding;
2713 #endif
2714 #ifdef SET_INEXACT
2715         int inexact, oldinexact;
2716 #endif
2717
2718 #ifndef MULTIPLE_THREADS
2719         if (dtoa_result) {
2720                 freedtoa(dtoa_result);
2721                 dtoa_result = 0;
2722                 }
2723 #endif
2724
2725         if (word0(d) & Sign_bit) {
2726                 /* set sign for everything, including 0's and NaNs */
2727                 *sign = 1;
2728                 word0(d) &= ~Sign_bit;  /* clear sign bit */
2729                 }
2730         else
2731                 *sign = 0;
2732
2733 #if defined(IEEE_Arith) + defined(VAX)
2734 #ifdef IEEE_Arith
2735         if ((word0(d) & Exp_mask) == Exp_mask)
2736 #else
2737         if (word0(d)  == 0x8000)
2738 #endif
2739                 {
2740                 /* Infinity or NaN */
2741                 *decpt = 9999;
2742 #ifdef IEEE_Arith
2743                 if (!word1(d) && !(word0(d) & 0xfffff))
2744                         return nrv_alloc("Infinity", rve, 8);
2745 #endif
2746                 return nrv_alloc("NaN", rve, 3);
2747                 }
2748 #endif
2749 #ifdef IBM
2750         dval(d) += 0; /* normalize */
2751 #endif
2752         if (!dval(d)) {
2753                 *decpt = 1;
2754                 return nrv_alloc("0", rve, 1);
2755                 }
2756
2757 #ifdef SET_INEXACT
2758         try_quick = oldinexact = get_inexact();
2759         inexact = 1;
2760 #endif
2761 #ifdef Honor_FLT_ROUNDS
2762         if ((rounding = Flt_Rounds) >= 2) {
2763                 if (*sign)
2764                         rounding = rounding == 2 ? 0 : 2;
2765                 else
2766                         if (rounding != 2)
2767                                 rounding = 0;
2768                 }
2769 #endif
2770
2771         b = d2b(dval(d), &be, &bbits);
2772 #ifdef Sudden_Underflow
2773         i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
2774 #else
2775         if (i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) {
2776 #endif
2777                 dval(d2) = dval(d);
2778                 word0(d2) &= Frac_mask1;
2779                 word0(d2) |= Exp_11;
2780 #ifdef IBM
2781                 if (j = 11 - hi0bits(word0(d2) & Frac_mask))
2782                         dval(d2) /= 1 << j;
2783 #endif
2784
2785                 /* log(x)       ~=~ log(1.5) + (x-1.5)/1.5
2786                  * log10(x)      =  log(x) / log(10)
2787                  *              ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2788                  * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
2789                  *
2790                  * This suggests computing an approximation k to log10(d) by
2791                  *
2792                  * k = (i - Bias)*0.301029995663981
2793                  *      + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2794                  *
2795                  * We want k to be too large rather than too small.
2796                  * The error in the first-order Taylor series approximation
2797                  * is in our favor, so we just round up the constant enough
2798                  * to compensate for any error in the multiplication of
2799                  * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2800                  * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2801                  * adding 1e-13 to the constant term more than suffices.
2802                  * Hence we adjust the constant term to 0.1760912590558.
2803                  * (We could get a more accurate k by invoking log10,
2804                  *  but this is probably not worthwhile.)
2805                  */
2806
2807                 i -= Bias;
2808 #ifdef IBM
2809                 i <<= 2;
2810                 i += j;
2811 #endif
2812 #ifndef Sudden_Underflow
2813                 denorm = 0;
2814                 }
2815         else {
2816                 /* d is denormalized */
2817
2818                 i = bbits + be + (Bias + (P-1) - 1);
2819                 x = i > 32  ? word0(d) << 64 - i | word1(d) >> i - 32
2820                             : word1(d) << 32 - i;
2821                 dval(d2) = x;
2822                 word0(d2) -= 31*Exp_msk1; /* adjust exponent */
2823                 i -= (Bias + (P-1) - 1) + 1;
2824                 denorm = 1;
2825                 }
2826 #endif
2827         ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
2828         k = (int)ds;
2829         if (ds < 0. && ds != k)
2830                 k--;    /* want k = floor(ds) */
2831         k_check = 1;
2832         if (k >= 0 && k <= Ten_pmax) {
2833                 if (dval(d) < tens[k])
2834                         k--;
2835                 k_check = 0;
2836                 }
2837         j = bbits - i - 1;
2838         if (j >= 0) {
2839                 b2 = 0;
2840                 s2 = j;
2841                 }
2842         else {
2843                 b2 = -j;
2844                 s2 = 0;
2845                 }
2846         if (k >= 0) {
2847                 b5 = 0;
2848                 s5 = k;
2849                 s2 += k;
2850                 }
2851         else {
2852                 b2 -= k;
2853                 b5 = -k;
2854                 s5 = 0;
2855                 }
2856         if (mode < 0 || mode > 9)
2857                 mode = 0;
2858
2859 #ifndef SET_INEXACT
2860 #ifdef Check_FLT_ROUNDS
2861         try_quick = Rounding == 1;
2862 #else
2863         try_quick = 1;
2864 #endif
2865 #endif /*SET_INEXACT*/
2866
2867         if (mode > 5) {
2868                 mode -= 4;
2869                 try_quick = 0;
2870                 }
2871         leftright = 1;
2872         switch(mode) {
2873                 case 0:
2874                 case 1:
2875                         ilim = ilim1 = -1;
2876                         i = 18;
2877                         ndigits = 0;
2878                         break;
2879                 case 2:
2880                         leftright = 0;
2881                         /* no break */
2882                 case 4:
2883                         if (ndigits <= 0)
2884                                 ndigits = 1;
2885                         ilim = ilim1 = i = ndigits;
2886                         break;
2887                 case 3:
2888                         leftright = 0;
2889                         /* no break */
2890                 case 5:
2891                         i = ndigits + k + 1;
2892                         ilim = i;
2893                         ilim1 = i - 1;
2894                         if (i <= 0)
2895                                 i = 1;
2896                 }
2897         s = s0 = rv_alloc(i);
2898
2899 #ifdef Honor_FLT_ROUNDS
2900         if (mode > 1 && rounding != 1)
2901                 leftright = 0;
2902 #endif
2903
2904         if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2905
2906                 /* Try to get by with floating-point arithmetic. */
2907
2908                 i = 0;
2909                 dval(d2) = dval(d);
2910                 k0 = k;
2911                 ilim0 = ilim;
2912                 ieps = 2; /* conservative */
2913                 if (k > 0) {
2914                         ds = tens[k&0xf];
2915                         j = k >> 4;
2916                         if (j & Bletch) {
2917                                 /* prevent overflows */
2918                                 j &= Bletch - 1;
2919                                 dval(d) /= bigtens[n_bigtens-1];
2920                                 ieps++;
2921                                 }
2922                         for(; j; j >>= 1, i++)
2923                                 if (j & 1) {
2924                                         ieps++;
2925                                         ds *= bigtens[i];
2926                                         }
2927                         dval(d) /= ds;
2928                         }
2929                 else if (j1 = -k) {
2930                         dval(d) *= tens[j1 & 0xf];
2931                         for(j = j1 >> 4; j; j >>= 1, i++)
2932                                 if (j & 1) {
2933                                         ieps++;
2934                                         dval(d) *= bigtens[i];
2935                                         }
2936                         }
2937                 if (k_check && dval(d) < 1. && ilim > 0) {
2938                         if (ilim1 <= 0)
2939                                 goto fast_failed;
2940                         ilim = ilim1;
2941                         k--;
2942                         dval(d) *= 10.;
2943                         ieps++;
2944                         }
2945                 dval(eps) = ieps*dval(d) + 7.;
2946                 word0(eps) -= (P-1)*Exp_msk1;
2947                 if (ilim == 0) {
2948                         S = mhi = 0;
2949                         dval(d) -= 5.;
2950                         if (dval(d) > dval(eps))
2951                                 goto one_digit;
2952                         if (dval(d) < -dval(eps))
2953                                 goto no_digits;
2954                         goto fast_failed;
2955                         }
2956 #ifndef No_leftright
2957                 if (leftright) {
2958                         /* Use Steele & White method of only
2959                          * generating digits needed.
2960                          */
2961                         dval(eps) = 0.5/tens[ilim-1] - dval(eps);
2962                         for(i = 0;;) {
2963                                 L = dval(d);
2964                                 dval(d) -= L;
2965                                 *s++ = '0' + (int)L;
2966                                 if (dval(d) < dval(eps))
2967                                         goto ret1;
2968                                 if (1. - dval(d) < dval(eps))
2969                                         goto bump_up;
2970                                 if (++i >= ilim)
2971                                         break;
2972                                 dval(eps) *= 10.;
2973                                 dval(d) *= 10.;
2974                                 }
2975                         }
2976                 else {
2977 #endif
2978                         /* Generate ilim digits, then fix them up. */
2979                         dval(eps) *= tens[ilim-1];
2980                         for(i = 1;; i++, dval(d) *= 10.) {
2981                                 L = (Long)(dval(d));
2982                                 if (!(dval(d) -= L))
2983                                         ilim = i;
2984                                 *s++ = '0' + (int)L;
2985                                 if (i == ilim) {
2986                                         if (dval(d) > 0.5 + dval(eps))
2987                                                 goto bump_up;
2988                                         else if (dval(d) < 0.5 - dval(eps)) {
2989                                                 while(*--s == '0');
2990                                                 s++;
2991                                                 goto ret1;
2992                                                 }
2993                                         break;
2994                                         }
2995                                 }
2996 #ifndef No_leftright
2997                         }
2998 #endif
2999  fast_failed:
3000                 s = s0;
3001                 dval(d) = dval(d2);
3002                 k = k0;
3003                 ilim = ilim0;
3004                 }
3005
3006         /* Do we have a "small" integer? */
3007
3008         if (be >= 0 && k <= Int_max) {
3009                 /* Yes. */
3010                 ds = tens[k];
3011                 if (ndigits < 0 && ilim <= 0) {
3012                         S = mhi = 0;
3013                         if (ilim < 0 || dval(d) <= 5*ds)
3014                                 goto no_digits;
3015                         goto one_digit;
3016                         }
3017                 for(i = 1;; i++, dval(d) *= 10.) {
3018                         L = (Long)(dval(d) / ds);
3019                         dval(d) -= L*ds;
3020 #ifdef Check_FLT_ROUNDS
3021                         /* If FLT_ROUNDS == 2, L will usually be high by 1 */
3022                         if (dval(d) < 0) {
3023                                 L--;
3024                                 dval(d) += ds;
3025                                 }
3026 #endif
3027                         *s++ = '0' + (int)L;
3028                         if (!dval(d)) {
3029 #ifdef SET_INEXACT
3030                                 inexact = 0;
3031 #endif
3032                                 break;
3033                                 }
3034                         if (i == ilim) {
3035 #ifdef Honor_FLT_ROUNDS
3036                                 if (mode > 1)
3037                                 switch(rounding) {
3038                                   case 0: goto ret1;
3039                                   case 2: goto bump_up;
3040                                   }
3041 #endif
3042                                 dval(d) += dval(d);
3043                                 if (dval(d) > ds || dval(d) == ds && L & 1) {
3044  bump_up:
3045                                         while(*--s == '9')
3046                                                 if (s == s0) {
3047                                                         k++;
3048                                                         *s = '0';
3049                                                         break;
3050                                                         }
3051                                         ++*s++;
3052                                         }
3053                                 break;
3054                                 }
3055                         }
3056                 goto ret1;
3057                 }
3058
3059         m2 = b2;
3060         m5 = b5;
3061         mhi = mlo = 0;
3062         if (leftright) {
3063                 i =
3064 #ifndef Sudden_Underflow
3065                         denorm ? be + (Bias + (P-1) - 1 + 1) :
3066 #endif
3067 #ifdef IBM
3068                         1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
3069 #else
3070                         1 + P - bbits;
3071 #endif
3072                 b2 += i;
3073                 s2 += i;
3074                 mhi = i2b(1);
3075                 }
3076         if (m2 > 0 && s2 > 0) {
3077                 i = m2 < s2 ? m2 : s2;
3078                 b2 -= i;
3079                 m2 -= i;
3080                 s2 -= i;
3081                 }
3082         if (b5 > 0) {
3083                 if (leftright) {
3084                         if (m5 > 0) {
3085                                 mhi = pow5mult(mhi, m5);
3086                                 b1 = mult(mhi, b);
3087                                 Bfree(b);
3088                                 b = b1;
3089                                 }
3090                         if (j = b5 - m5)
3091                                 b = pow5mult(b, j);
3092                         }
3093                 else
3094                         b = pow5mult(b, b5);
3095                 }
3096         S = i2b(1);
3097         if (s5 > 0)
3098                 S = pow5mult(S, s5);
3099
3100         /* Check for special case that d is a normalized power of 2. */
3101
3102         spec_case = 0;
3103         if ((mode < 2 || leftright)
3104 #ifdef Honor_FLT_ROUNDS
3105                         && rounding == 1
3106 #endif
3107                                 ) {
3108                 if (!word1(d) && !(word0(d) & Bndry_mask)
3109 #ifndef Sudden_Underflow
3110                  && word0(d) & (Exp_mask & ~Exp_msk1)
3111 #endif
3112                                 ) {
3113                         /* The special case */
3114                         b2 += Log2P;
3115                         s2 += Log2P;
3116                         spec_case = 1;
3117                         }
3118                 }
3119
3120         /* Arrange for convenient computation of quotients:
3121          * shift left if necessary so divisor has 4 leading 0 bits.
3122          *
3123          * Perhaps we should just compute leading 28 bits of S once
3124          * and for all and pass them and a shift to quorem, so it
3125          * can do shifts and ors to compute the numerator for q.
3126          */
3127 #ifdef Pack_32
3128         if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)
3129                 i = 32 - i;
3130 #else
3131         if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf)
3132                 i = 16 - i;
3133 #endif
3134         if (i > 4) {
3135                 i -= 4;
3136                 b2 += i;
3137                 m2 += i;
3138                 s2 += i;
3139                 }
3140         else if (i < 4) {
3141                 i += 28;
3142                 b2 += i;
3143                 m2 += i;
3144                 s2 += i;
3145                 }
3146         if (b2 > 0)
3147                 b = lshift(b, b2);
3148         if (s2 > 0)
3149                 S = lshift(S, s2);
3150         if (k_check) {
3151                 if (cmp(b,S) < 0) {
3152                         k--;
3153                         b = multadd(b, 10, 0);  /* we botched the k estimate */
3154                         if (leftright)
3155                                 mhi = multadd(mhi, 10, 0);
3156                         ilim = ilim1;
3157                         }
3158                 }
3159         if (ilim <= 0 && (mode == 3 || mode == 5)) {
3160                 if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
3161                         /* no digits, fcvt style */
3162  no_digits:
3163                         k = -1 - ndigits;
3164                         goto ret;
3165                         }
3166  one_digit:
3167                 *s++ = '1';
3168                 k++;
3169                 goto ret;
3170                 }
3171         if (leftright) {
3172                 if (m2 > 0)
3173                         mhi = lshift(mhi, m2);
3174
3175                 /* Compute mlo -- check for special case
3176                  * that d is a normalized power of 2.
3177                  */
3178
3179                 mlo = mhi;
3180                 if (spec_case) {
3181                         mhi = Balloc(mhi->k);
3182                         Bcopy(mhi, mlo);
3183                         mhi = lshift(mhi, Log2P);
3184                         }
3185
3186                 for(i = 1;;i++) {
3187                         dig = quorem(b,S) + '0';
3188                         /* Do we yet have the shortest decimal string
3189                          * that will round to d?
3190                          */
3191                         j = cmp(b, mlo);
3192                         delta = diff(S, mhi);
3193                         j1 = delta->sign ? 1 : cmp(b, delta);
3194                         Bfree(delta);
3195 #ifndef ROUND_BIASED
3196                         if (j1 == 0 && mode != 1 && !(word1(d) & 1)
3197 #ifdef Honor_FLT_ROUNDS
3198                                 && rounding >= 1
3199 #endif
3200                                                                    ) {
3201                                 if (dig == '9')
3202                                         goto round_9_up;
3203                                 if (j > 0)
3204                                         dig++;
3205 #ifdef SET_INEXACT
3206                                 else if (!b->x[0] && b->wds <= 1)
3207                                         inexact = 0;
3208 #endif
3209                                 *s++ = dig;
3210                                 goto ret;
3211                                 }
3212 #endif
3213                         if (j < 0 || j == 0 && mode != 1
3214 #ifndef ROUND_BIASED
3215                                                         && !(word1(d) & 1)
3216 #endif
3217                                         ) {
3218                                 if (!b->x[0] && b->wds <= 1) {
3219 #ifdef SET_INEXACT
3220                                         inexact = 0;
3221 #endif
3222                                         goto accept_dig;
3223                                         }
3224 #ifdef Honor_FLT_ROUNDS
3225                                 if (mode > 1)
3226                                  switch(rounding) {
3227                                   case 0: goto accept_dig;
3228                                   case 2: goto keep_dig;
3229                                   }
3230 #endif /*Honor_FLT_ROUNDS*/
3231                                 if (j1 > 0) {
3232                                         b = lshift(b, 1);
3233                                         j1 = cmp(b, S);
3234                                         if ((j1 > 0 || j1 == 0 && dig & 1)
3235                                         && dig++ == '9')
3236                                                 goto round_9_up;
3237                                         }
3238  accept_dig:
3239                                 *s++ = dig;
3240                                 goto ret;
3241                                 }
3242                         if (j1 > 0) {
3243 #ifdef Honor_FLT_ROUNDS
3244                                 if (!rounding)
3245                                         goto accept_dig;
3246 #endif
3247                                 if (dig == '9') { /* possible if i == 1 */
3248  round_9_up:
3249                                         *s++ = '9';
3250                                         goto roundoff;
3251                                         }
3252                                 *s++ = dig + 1;
3253                                 goto ret;
3254                                 }
3255 #ifdef Honor_FLT_ROUNDS
3256  keep_dig:
3257 #endif
3258                         *s++ = dig;
3259                         if (i == ilim)
3260                                 break;
3261                         b = multadd(b, 10, 0);
3262                         if (mlo == mhi)
3263                                 mlo = mhi = multadd(mhi, 10, 0);
3264                         else {
3265                                 mlo = multadd(mlo, 10, 0);
3266                                 mhi = multadd(mhi, 10, 0);
3267                                 }
3268                         }
3269                 }
3270         else
3271                 for(i = 1;; i++) {
3272                         *s++ = dig = quorem(b,S) + '0';
3273                         if (!b->x[0] && b->wds <= 1) {
3274 #ifdef SET_INEXACT
3275                                 inexact = 0;
3276 #endif
3277                                 goto ret;
3278                                 }
3279                         if (i >= ilim)
3280                                 break;
3281                         b = multadd(b, 10, 0);
3282                         }
3283
3284         /* Round off last digit */
3285
3286 #ifdef Honor_FLT_ROUNDS
3287         switch(rounding) {
3288           case 0: goto trimzeros;
3289           case 2: goto roundoff;
3290           }
3291 #endif
3292         b = lshift(b, 1);
3293         j = cmp(b, S);
3294         if (j > 0 || j == 0 && dig & 1) {
3295  roundoff:
3296                 while(*--s == '9')
3297                         if (s == s0) {
3298                                 k++;
3299                                 *s++ = '1';
3300                                 goto ret;
3301                                 }
3302                 ++*s++;
3303                 }
3304         else {
3305  trimzeros:
3306                 while(*--s == '0');
3307                 s++;
3308                 }
3309  ret:
3310         Bfree(S);
3311         if (mhi) {
3312                 if (mlo && mlo != mhi)
3313                         Bfree(mlo);
3314                 Bfree(mhi);
3315                 }
3316  ret1:
3317 #ifdef SET_INEXACT
3318         if (inexact) {
3319                 if (!oldinexact) {
3320                         word0(d) = Exp_1 + (70 << Exp_shift);
3321                         word1(d) = 0;
3322                         dval(d) += 1.;
3323                         }
3324                 }
3325         else if (!oldinexact)
3326                 clear_inexact();
3327 #endif
3328         Bfree(b);
3329         *s = 0;
3330         *decpt = k + 1;
3331         if (rve)
3332                 *rve = s;
3333         return s0;
3334         }
3335 #endif
3336
3337 #ifdef __cplusplus
3338 }
3339 #endif