Normalize line endings.
[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 #define Omit_Private_Memory
25 #define MULTIPLE_THREADS 1
26 /* Lock 0 is not used because of USE_MALLOC, Lock 1 protects a lazy-initialized table */
27 #define ACQUIRE_DTOA_LOCK(n)
28 #define FREE_DTOA_LOCK(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 #ifdef Omit_Private_Memory
569         free (v);
570 #else
571         if (v) {
572                 ACQUIRE_DTOA_LOCK(0);
573                 v->next = freelist[v->k];
574                 freelist[v->k] = v;
575                 FREE_DTOA_LOCK(0);
576         }
577 #endif
578 }
579
580 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
581 y->wds*sizeof(Long) + 2*sizeof(int))
582
583  static Bigint *
584 multadd
585 #ifdef KR_headers
586         (b, m, a) Bigint *b; int m, a;
587 #else
588         (Bigint *b, int m, int a)       /* multiply by m and add a */
589 #endif
590 {
591         int i, wds;
592 #ifdef ULLong
593         ULong *x;
594         ULLong carry, y;
595 #else
596         ULong carry, *x, y;
597 #ifdef Pack_32
598         ULong xi, z;
599 #endif
600 #endif
601         Bigint *b1;
602
603         wds = b->wds;
604         x = b->x;
605         i = 0;
606         carry = a;
607         do {
608 #ifdef ULLong
609                 y = *x * (ULLong)m + carry;
610                 carry = y >> 32;
611                 *x++ = y & FFFFFFFF;
612 #else
613 #ifdef Pack_32
614                 xi = *x;
615                 y = (xi & 0xffff) * m + carry;
616                 z = (xi >> 16) * m + (y >> 16);
617                 carry = z >> 16;
618                 *x++ = (z << 16) + (y & 0xffff);
619 #else
620                 y = *x * m + carry;
621                 carry = y >> 16;
622                 *x++ = y & 0xffff;
623 #endif
624 #endif
625                 }
626                 while(++i < wds);
627         if (carry) {
628                 if (wds >= b->maxwds) {
629                         b1 = Balloc(b->k+1);
630                         Bcopy(b1, b);
631                         Bfree(b);
632                         b = b1;
633                         }
634                 b->x[wds++] = carry;
635                 b->wds = wds;
636                 }
637         return b;
638         }
639
640  static Bigint *
641 s2b
642 #ifdef KR_headers
643         (s, nd0, nd, y9) CONST char *s; int nd0, nd; ULong y9;
644 #else
645         (CONST char *s, int nd0, int nd, ULong y9)
646 #endif
647 {
648         Bigint *b;
649         int i, k;
650         Long x, y;
651
652         x = (nd + 8) / 9;
653         for(k = 0, y = 1; x > y; y <<= 1, k++) ;
654 #ifdef Pack_32
655         b = Balloc(k);
656         b->x[0] = y9;
657         b->wds = 1;
658 #else
659         b = Balloc(k+1);
660         b->x[0] = y9 & 0xffff;
661         b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
662 #endif
663
664         i = 9;
665         if (9 < nd0) {
666                 s += 9;
667                 do b = multadd(b, 10, *s++ - '0');
668                         while(++i < nd0);
669                 s++;
670                 }
671         else
672                 s += 10;
673         for(; i < nd; i++)
674                 b = multadd(b, 10, *s++ - '0');
675         return b;
676         }
677
678  static int
679 hi0bits
680 #ifdef KR_headers
681         (x) register ULong x;
682 #else
683         (register ULong x)
684 #endif
685 {
686         register int k = 0;
687
688         if (!(x & 0xffff0000)) {
689                 k = 16;
690                 x <<= 16;
691                 }
692         if (!(x & 0xff000000)) {
693                 k += 8;
694                 x <<= 8;
695                 }
696         if (!(x & 0xf0000000)) {
697                 k += 4;
698                 x <<= 4;
699                 }
700         if (!(x & 0xc0000000)) {
701                 k += 2;
702                 x <<= 2;
703                 }
704         if (!(x & 0x80000000)) {
705                 k++;
706                 if (!(x & 0x40000000))
707                         return 32;
708                 }
709         return k;
710         }
711
712  static int
713 lo0bits
714 #ifdef KR_headers
715         (y) ULong *y;
716 #else
717         (ULong *y)
718 #endif
719 {
720         register int k;
721         register ULong x = *y;
722
723         if (x & 7) {
724                 if (x & 1)
725                         return 0;
726                 if (x & 2) {
727                         *y = x >> 1;
728                         return 1;
729                         }
730                 *y = x >> 2;
731                 return 2;
732                 }
733         k = 0;
734         if (!(x & 0xffff)) {
735                 k = 16;
736                 x >>= 16;
737                 }
738         if (!(x & 0xff)) {
739                 k += 8;
740                 x >>= 8;
741                 }
742         if (!(x & 0xf)) {
743                 k += 4;
744                 x >>= 4;
745                 }
746         if (!(x & 0x3)) {
747                 k += 2;
748                 x >>= 2;
749                 }
750         if (!(x & 1)) {
751                 k++;
752                 x >>= 1;
753                 if (!x)
754                         return 32;
755                 }
756         *y = x;
757         return k;
758         }
759
760  static Bigint *
761 i2b
762 #ifdef KR_headers
763         (i) int i;
764 #else
765         (int i)
766 #endif
767 {
768         Bigint *b;
769
770         b = Balloc(1);
771         b->x[0] = i;
772         b->wds = 1;
773         return b;
774         }
775
776  static Bigint *
777 mult
778 #ifdef KR_headers
779         (a, b) Bigint *a, *b;
780 #else
781         (Bigint *a, Bigint *b)
782 #endif
783 {
784         Bigint *c;
785         int k, wa, wb, wc;
786         ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
787         ULong y;
788 #ifdef ULLong
789         ULLong carry, z;
790 #else
791         ULong carry, z;
792 #ifdef Pack_32
793         ULong z2;
794 #endif
795 #endif
796
797         if (a->wds < b->wds) {
798                 c = a;
799                 a = b;
800                 b = c;
801                 }
802         k = a->k;
803         wa = a->wds;
804         wb = b->wds;
805         wc = wa + wb;
806         if (wc > a->maxwds)
807                 k++;
808         c = Balloc(k);
809         for(x = c->x, xa = x + wc; x < xa; x++)
810                 *x = 0;
811         xa = a->x;
812         xae = xa + wa;
813         xb = b->x;
814         xbe = xb + wb;
815         xc0 = c->x;
816 #ifdef ULLong
817         for(; xb < xbe; xc0++) {
818                 if ((y = *xb++)) {
819                         x = xa;
820                         xc = xc0;
821                         carry = 0;
822                         do {
823                                 z = *x++ * (ULLong)y + *xc + carry;
824                                 carry = z >> 32;
825                                 *xc++ = z & FFFFFFFF;
826                                 }
827                                 while(x < xae);
828                         *xc = carry;
829                         }
830                 }
831 #else
832 #ifdef Pack_32
833         for(; xb < xbe; xb++, xc0++) {
834                 if (y = *xb & 0xffff) {
835                         x = xa;
836                         xc = xc0;
837                         carry = 0;
838                         do {
839                                 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
840                                 carry = z >> 16;
841                                 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
842                                 carry = z2 >> 16;
843                                 Storeinc(xc, z2, z);
844                                 }
845                                 while(x < xae);
846                         *xc = carry;
847                         }
848                 if (y = *xb >> 16) {
849                         x = xa;
850                         xc = xc0;
851                         carry = 0;
852                         z2 = *xc;
853                         do {
854                                 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
855                                 carry = z >> 16;
856                                 Storeinc(xc, z, z2);
857                                 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
858                                 carry = z2 >> 16;
859                                 }
860                                 while(x < xae);
861                         *xc = z2;
862                         }
863                 }
864 #else
865         for(; xb < xbe; xc0++) {
866                 if (y = *xb++) {
867                         x = xa;
868                         xc = xc0;
869                         carry = 0;
870                         do {
871                                 z = *x++ * y + *xc + carry;
872                                 carry = z >> 16;
873                                 *xc++ = z & 0xffff;
874                                 }
875                                 while(x < xae);
876                         *xc = carry;
877                         }
878                 }
879 #endif
880 #endif
881         for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
882         c->wds = wc;
883         return c;
884         }
885
886  static Bigint *p5s;
887
888  static Bigint *
889 pow5mult
890 #ifdef KR_headers
891         (b, k) Bigint *b; int k;
892 #else
893         (Bigint *b, int k)
894 #endif
895 {
896         Bigint *b1, *p5, *p51;
897         int i;
898         static int p05[3] = { 5, 25, 125 };
899
900         if ((i = k & 3))
901                 b = multadd(b, p05[i-1], 0);
902
903         if (!(k >>= 2))
904                 return b;
905         if (!(p5 = p5s)) {
906                 /* first time */
907 #ifdef MULTIPLE_THREADS
908                 ACQUIRE_DTOA_LOCK(1);
909                 if (!(p5 = p5s)) {
910                         p5 = p5s = i2b(625);
911                         p5->next = 0;
912                         }
913                 FREE_DTOA_LOCK(1);
914 #else
915                 p5 = p5s = i2b(625);
916                 p5->next = 0;
917 #endif
918                 }
919         for(;;) {
920                 if (k & 1) {
921                         b1 = mult(b, p5);
922                         Bfree(b);
923                         b = b1;
924                         }
925                 if (!(k >>= 1))
926                         break;
927                 if (!(p51 = p5->next)) {
928 #ifdef MULTIPLE_THREADS
929                         ACQUIRE_DTOA_LOCK(1);
930                         if (!(p51 = p5->next)) {
931                                 p51 = p5->next = mult(p5,p5);
932                                 p51->next = 0;
933                                 }
934                         FREE_DTOA_LOCK(1);
935 #else
936                         p51 = p5->next = mult(p5,p5);
937                         p51->next = 0;
938 #endif
939                         }
940                 p5 = p51;
941                 }
942         return b;
943         }
944
945  static Bigint *
946 lshift
947 #ifdef KR_headers
948         (b, k) Bigint *b; int k;
949 #else
950         (Bigint *b, int k)
951 #endif
952 {
953         int i, k1, n, n1;
954         Bigint *b1;
955         ULong *x, *x1, *xe, z;
956
957 #ifdef Pack_32
958         n = k >> 5;
959 #else
960         n = k >> 4;
961 #endif
962         k1 = b->k;
963         n1 = n + b->wds + 1;
964         for(i = b->maxwds; n1 > i; i <<= 1)
965                 k1++;
966         b1 = Balloc(k1);
967         x1 = b1->x;
968         for(i = 0; i < n; i++)
969                 *x1++ = 0;
970         x = b->x;
971         xe = x + b->wds;
972 #ifdef Pack_32
973         if (k &= 0x1f) {
974                 k1 = 32 - k;
975                 z = 0;
976                 do {
977                         *x1++ = *x << k | z;
978                         z = *x++ >> k1;
979                         }
980                         while(x < xe);
981                 if ((*x1 = z))
982                         ++n1;
983                 }
984 #else
985         if (k &= 0xf) {
986                 k1 = 16 - k;
987                 z = 0;
988                 do {
989                         *x1++ = *x << k  & 0xffff | z;
990                         z = *x++ >> k1;
991                         }
992                         while(x < xe);
993                 if (*x1 = z)
994                         ++n1;
995                 }
996 #endif
997         else do
998                 *x1++ = *x++;
999                 while(x < xe);
1000         b1->wds = n1 - 1;
1001         Bfree(b);
1002         return b1;
1003         }
1004
1005  static int
1006 cmp
1007 #ifdef KR_headers
1008         (a, b) Bigint *a, *b;
1009 #else
1010         (Bigint *a, Bigint *b)
1011 #endif
1012 {
1013         ULong *xa, *xa0, *xb, *xb0;
1014         int i, j;
1015
1016         i = a->wds;
1017         j = b->wds;
1018 #ifdef DEBUG
1019         if (i > 1 && !a->x[i-1])
1020                 Bug("cmp called with a->x[a->wds-1] == 0");
1021         if (j > 1 && !b->x[j-1])
1022                 Bug("cmp called with b->x[b->wds-1] == 0");
1023 #endif
1024         if (i -= j)
1025                 return i;
1026         xa0 = a->x;
1027         xa = xa0 + j;
1028         xb0 = b->x;
1029         xb = xb0 + j;
1030         for(;;) {
1031                 if (*--xa != *--xb)
1032                         return *xa < *xb ? -1 : 1;
1033                 if (xa <= xa0)
1034                         break;
1035                 }
1036         return 0;
1037         }
1038
1039  static Bigint *
1040 diff
1041 #ifdef KR_headers
1042         (a, b) Bigint *a, *b;
1043 #else
1044         (Bigint *a, Bigint *b)
1045 #endif
1046 {
1047         Bigint *c;
1048         int i, wa, wb;
1049         ULong *xa, *xae, *xb, *xbe, *xc;
1050 #ifdef ULLong
1051         ULLong borrow, y;
1052 #else
1053         ULong borrow, y;
1054 #ifdef Pack_32
1055         ULong z;
1056 #endif
1057 #endif
1058
1059         i = cmp(a,b);
1060         if (!i) {
1061                 c = Balloc(0);
1062                 c->wds = 1;
1063                 c->x[0] = 0;
1064                 return c;
1065                 }
1066         if (i < 0) {
1067                 c = a;
1068                 a = b;
1069                 b = c;
1070                 i = 1;
1071                 }
1072         else
1073                 i = 0;
1074         c = Balloc(a->k);
1075         c->sign = i;
1076         wa = a->wds;
1077         xa = a->x;
1078         xae = xa + wa;
1079         wb = b->wds;
1080         xb = b->x;
1081         xbe = xb + wb;
1082         xc = c->x;
1083         borrow = 0;
1084 #ifdef ULLong
1085         do {
1086                 y = (ULLong)*xa++ - *xb++ - borrow;
1087                 borrow = y >> 32 & (ULong)1;
1088                 *xc++ = y & FFFFFFFF;
1089                 }
1090                 while(xb < xbe);
1091         while(xa < xae) {
1092                 y = *xa++ - borrow;
1093                 borrow = y >> 32 & (ULong)1;
1094                 *xc++ = y & FFFFFFFF;
1095                 }
1096 #else
1097 #ifdef Pack_32
1098         do {
1099                 y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
1100                 borrow = (y & 0x10000) >> 16;
1101                 z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
1102                 borrow = (z & 0x10000) >> 16;
1103                 Storeinc(xc, z, y);
1104                 }
1105                 while(xb < xbe);
1106         while(xa < xae) {
1107                 y = (*xa & 0xffff) - borrow;
1108                 borrow = (y & 0x10000) >> 16;
1109                 z = (*xa++ >> 16) - borrow;
1110                 borrow = (z & 0x10000) >> 16;
1111                 Storeinc(xc, z, y);
1112                 }
1113 #else
1114         do {
1115                 y = *xa++ - *xb++ - borrow;
1116                 borrow = (y & 0x10000) >> 16;
1117                 *xc++ = y & 0xffff;
1118                 }
1119                 while(xb < xbe);
1120         while(xa < xae) {
1121                 y = *xa++ - borrow;
1122                 borrow = (y & 0x10000) >> 16;
1123                 *xc++ = y & 0xffff;
1124                 }
1125 #endif
1126 #endif
1127         while(!*--xc)
1128                 wa--;
1129         c->wds = wa;
1130         return c;
1131         }
1132
1133  static double
1134 ulp
1135 #ifdef KR_headers
1136         (x) double x;
1137 #else
1138         (double x)
1139 #endif
1140 {
1141         register Long L;
1142         double a;
1143
1144         L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
1145 #ifndef Avoid_Underflow
1146 #ifndef Sudden_Underflow
1147         if (L > 0) {
1148 #endif
1149 #endif
1150 #ifdef IBM
1151                 L |= Exp_msk1 >> 4;
1152 #endif
1153                 word0(a) = L;
1154                 word1(a) = 0;
1155 #ifndef Avoid_Underflow
1156 #ifndef Sudden_Underflow
1157                 }
1158         else {
1159                 L = -L >> Exp_shift;
1160                 if (L < Exp_shift) {
1161                         word0(a) = 0x80000 >> L;
1162                         word1(a) = 0;
1163                         }
1164                 else {
1165                         word0(a) = 0;
1166                         L -= Exp_shift;
1167                         word1(a) = L >= 31 ? 1 : 1 << 31 - L;
1168                         }
1169                 }
1170 #endif
1171 #endif
1172         return dval(a);
1173         }
1174
1175  static double
1176 b2d
1177 #ifdef KR_headers
1178         (a, e) Bigint *a; int *e;
1179 #else
1180         (Bigint *a, int *e)
1181 #endif
1182 {
1183         ULong *xa, *xa0, w, y, z;
1184         int k;
1185         double d;
1186 #ifdef VAX
1187         ULong d0, d1;
1188 #else
1189 #define d0 word0(d)
1190 #define d1 word1(d)
1191 #endif
1192
1193         xa0 = a->x;
1194         xa = xa0 + a->wds;
1195         y = *--xa;
1196 #ifdef DEBUG
1197         if (!y) Bug("zero y in b2d");
1198 #endif
1199         k = hi0bits(y);
1200         *e = 32 - k;
1201 #ifdef Pack_32
1202         if (k < Ebits) {
1203                 d0 = Exp_1 | (y >> (Ebits - k));
1204                 w = xa > xa0 ? *--xa : 0;
1205                 d1 = y << ((32-Ebits) + k) | (w >> (Ebits - k));
1206                 goto ret_d;
1207                 }
1208         z = xa > xa0 ? *--xa : 0;
1209         if (k -= Ebits) {
1210                 d0 = Exp_1 | y << k | (z >> (32 - k));
1211                 y = xa > xa0 ? *--xa : 0;
1212                 d1 = z << k | (y >> (32 - k));
1213                 }
1214         else {
1215                 d0 = Exp_1 | y;
1216                 d1 = z;
1217                 }
1218 #else
1219         if (k < Ebits + 16) {
1220                 z = xa > xa0 ? *--xa : 0;
1221                 d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
1222                 w = xa > xa0 ? *--xa : 0;
1223                 y = xa > xa0 ? *--xa : 0;
1224                 d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
1225                 goto ret_d;
1226                 }
1227         z = xa > xa0 ? *--xa : 0;
1228         w = xa > xa0 ? *--xa : 0;
1229         k -= Ebits + 16;
1230         d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
1231         y = xa > xa0 ? *--xa : 0;
1232         d1 = w << k + 16 | y << k;
1233 #endif
1234  ret_d:
1235 #ifdef VAX
1236         word0(d) = d0 >> 16 | d0 << 16;
1237         word1(d) = d1 >> 16 | d1 << 16;
1238 #else
1239 #undef d0
1240 #undef d1
1241 #endif
1242         return dval(d);
1243         }
1244
1245  static Bigint *
1246 d2b
1247 #ifdef KR_headers
1248         (d, e, bits) double d; int *e, *bits;
1249 #else
1250         (double d, int *e, int *bits)
1251 #endif
1252 {
1253         Bigint *b;
1254         int de, k;
1255         ULong *x, y, z;
1256 #ifndef Sudden_Underflow
1257         int i;
1258 #endif
1259 #ifdef VAX
1260         ULong d0, d1;
1261         d0 = word0(d) >> 16 | word0(d) << 16;
1262         d1 = word1(d) >> 16 | word1(d) << 16;
1263 #else
1264 #define d0 word0(d)
1265 #define d1 word1(d)
1266 #endif
1267
1268 #ifdef Pack_32
1269         b = Balloc(1);
1270 #else
1271         b = Balloc(2);
1272 #endif
1273         x = b->x;
1274
1275         z = d0 & Frac_mask;
1276         d0 &= 0x7fffffff;       /* clear sign bit, which we ignore */
1277 #ifdef Sudden_Underflow
1278         de = (int)(d0 >> Exp_shift);
1279 #ifndef IBM
1280         z |= Exp_msk11;
1281 #endif
1282 #else
1283         if ((de = (int)(d0 >> Exp_shift)))
1284                 z |= Exp_msk1;
1285 #endif
1286 #ifdef Pack_32
1287         if ((y = d1)) {
1288                 if ((k = lo0bits(&y))) {
1289                         x[0] = y | (z << (32 - k));
1290                         z >>= k;
1291                         }
1292                 else
1293                         x[0] = y;
1294 #ifndef Sudden_Underflow
1295                 i =
1296 #endif
1297                     b->wds = (x[1] = z) ? 2 : 1;
1298                 }
1299         else {
1300 #ifdef DEBUG
1301                 if (!z)
1302                         Bug("Zero passed to d2b");
1303 #endif
1304                 k = lo0bits(&z);
1305                 x[0] = z;
1306 #ifndef Sudden_Underflow
1307                 i =
1308 #endif
1309                     b->wds = 1;
1310                 k += 32;
1311                 }
1312 #else
1313         if (y = d1) {
1314                 if (k = lo0bits(&y))
1315                         if (k >= 16) {
1316                                 x[0] = y | z << 32 - k & 0xffff;
1317                                 x[1] = z >> k - 16 & 0xffff;
1318                                 x[2] = z >> k;
1319                                 i = 2;
1320                                 }
1321                         else {
1322                                 x[0] = y & 0xffff;
1323                                 x[1] = y >> 16 | z << 16 - k & 0xffff;
1324                                 x[2] = z >> k & 0xffff;
1325                                 x[3] = z >> k+16;
1326                                 i = 3;
1327                                 }
1328                 else {
1329                         x[0] = y & 0xffff;
1330                         x[1] = y >> 16;
1331                         x[2] = z & 0xffff;
1332                         x[3] = z >> 16;
1333                         i = 3;
1334                         }
1335                 }
1336         else {
1337 #ifdef DEBUG
1338                 if (!z)
1339                         Bug("Zero passed to d2b");
1340 #endif
1341                 k = lo0bits(&z);
1342                 if (k >= 16) {
1343                         x[0] = z;
1344                         i = 0;
1345                         }
1346                 else {
1347                         x[0] = z & 0xffff;
1348                         x[1] = z >> 16;
1349                         i = 1;
1350                         }
1351                 k += 32;
1352                 }
1353         while(!x[i])
1354                 --i;
1355         b->wds = i + 1;
1356 #endif
1357 #ifndef Sudden_Underflow
1358         if (de) {
1359 #endif
1360 #ifdef IBM
1361                 *e = (de - Bias - (P-1) << 2) + k;
1362                 *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
1363 #else
1364                 *e = de - Bias - (P-1) + k;
1365                 *bits = P - k;
1366 #endif
1367 #ifndef Sudden_Underflow
1368                 }
1369         else {
1370                 *e = de - Bias - (P-1) + 1 + k;
1371 #ifdef Pack_32
1372                 *bits = 32*i - hi0bits(x[i-1]);
1373 #else
1374                 *bits = (i+2)*16 - hi0bits(x[i]);
1375 #endif
1376                 }
1377 #endif
1378         return b;
1379         }
1380 #undef d0
1381 #undef d1
1382
1383  static double
1384 ratio
1385 #ifdef KR_headers
1386         (a, b) Bigint *a, *b;
1387 #else
1388         (Bigint *a, Bigint *b)
1389 #endif
1390 {
1391         double da, db;
1392         int k, ka, kb;
1393
1394         dval(da) = b2d(a, &ka);
1395         dval(db) = b2d(b, &kb);
1396 #ifdef Pack_32
1397         k = ka - kb + 32*(a->wds - b->wds);
1398 #else
1399         k = ka - kb + 16*(a->wds - b->wds);
1400 #endif
1401 #ifdef IBM
1402         if (k > 0) {
1403                 word0(da) += (k >> 2)*Exp_msk1;
1404                 if (k &= 3)
1405                         dval(da) *= 1 << k;
1406                 }
1407         else {
1408                 k = -k;
1409                 word0(db) += (k >> 2)*Exp_msk1;
1410                 if (k &= 3)
1411                         dval(db) *= 1 << k;
1412                 }
1413 #else
1414         if (k > 0)
1415                 word0(da) += k*Exp_msk1;
1416         else {
1417                 k = -k;
1418                 word0(db) += k*Exp_msk1;
1419                 }
1420 #endif
1421         return dval(da) / dval(db);
1422         }
1423
1424  static CONST double
1425 tens[] = {
1426                 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1427                 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1428                 1e20, 1e21, 1e22
1429 #ifdef VAX
1430                 , 1e23, 1e24
1431 #endif
1432                 };
1433
1434  static CONST double
1435 #ifdef IEEE_Arith
1436 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1437 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
1438 #ifdef Avoid_Underflow
1439                 9007199254740992.*9007199254740992.e-256
1440                 /* = 2^106 * 1e-53 */
1441 #else
1442                 1e-256
1443 #endif
1444                 };
1445 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
1446 /* flag unnecessarily.  It leads to a song and dance at the end of strtod. */
1447 #define Scale_Bit 0x10
1448 #define n_bigtens 5
1449 #else
1450 #ifdef IBM
1451 bigtens[] = { 1e16, 1e32, 1e64 };
1452 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 };
1453 #define n_bigtens 3
1454 #else
1455 bigtens[] = { 1e16, 1e32 };
1456 static CONST double tinytens[] = { 1e-16, 1e-32 };
1457 #define n_bigtens 2
1458 #endif
1459 #endif
1460
1461 #ifndef IEEE_Arith
1462 #undef INFNAN_CHECK
1463 #endif
1464
1465 #ifdef INFNAN_CHECK
1466
1467 #ifndef NAN_WORD0
1468 #define NAN_WORD0 0x7ff80000
1469 #endif
1470
1471 #ifndef NAN_WORD1
1472 #define NAN_WORD1 0
1473 #endif
1474
1475  static int
1476 match
1477 #ifdef KR_headers
1478         (sp, t) char **sp, *t;
1479 #else
1480         (CONST char **sp, char *t)
1481 #endif
1482 {
1483         int c, d;
1484         CONST char *s = *sp;
1485
1486         while(d = *t++) {
1487                 if ((c = *++s) >= 'A' && c <= 'Z')
1488                         c += 'a' - 'A';
1489                 if (c != d)
1490                         return 0;
1491                 }
1492         *sp = s + 1;
1493         return 1;
1494         }
1495
1496 #ifndef No_Hex_NaN
1497  static void
1498 hexnan
1499 #ifdef KR_headers
1500         (rvp, sp) double *rvp; CONST char **sp;
1501 #else
1502         (double *rvp, CONST char **sp)
1503 #endif
1504 {
1505         ULong c, x[2];
1506         CONST char *s;
1507         int havedig, udx0, xshift;
1508
1509         x[0] = x[1] = 0;
1510         havedig = xshift = 0;
1511         udx0 = 1;
1512         s = *sp;
1513         while(c = *(CONST unsigned char*)++s) {
1514                 if (c >= '0' && c <= '9')
1515                         c -= '0';
1516                 else if (c >= 'a' && c <= 'f')
1517                         c += 10 - 'a';
1518                 else if (c >= 'A' && c <= 'F')
1519                         c += 10 - 'A';
1520                 else if (c <= ' ') {
1521                         if (udx0 && havedig) {
1522                                 udx0 = 0;
1523                                 xshift = 1;
1524                                 }
1525                         continue;
1526                         }
1527                 else if (/*(*/ c == ')' && havedig) {
1528                         *sp = s + 1;
1529                         break;
1530                         }
1531                 else
1532                         return; /* invalid form: don't change *sp */
1533                 havedig = 1;
1534                 if (xshift) {
1535                         xshift = 0;
1536                         x[0] = x[1];
1537                         x[1] = 0;
1538                         }
1539                 if (udx0)
1540                         x[0] = (x[0] << 4) | (x[1] >> 28);
1541                 x[1] = (x[1] << 4) | c;
1542                 }
1543         if ((x[0] &= 0xfffff) || x[1]) {
1544                 word0(*rvp) = Exp_mask | x[0];
1545                 word1(*rvp) = x[1];
1546                 }
1547         }
1548 #endif /*No_Hex_NaN*/
1549 #endif /* INFNAN_CHECK */
1550
1551  double
1552 mono_strtod
1553 #ifdef KR_headers
1554         (s00, se) CONST char *s00; char **se;
1555 #else
1556         (CONST char *s00, char **se)
1557 #endif
1558 {
1559 #ifdef Avoid_Underflow
1560         int scale;
1561 #endif
1562         int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
1563                  e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1564         CONST char *s, *s0, *s1;
1565         double aadj, aadj1, adj, rv, rv0;
1566         Long L;
1567         ULong y, z;
1568         Bigint *bb = NULL, *bb1, *bd = NULL, *bd0, *bs = NULL, *delta = NULL;
1569 #ifdef SET_INEXACT
1570         int inexact, oldinexact;
1571 #endif
1572 #ifdef Honor_FLT_ROUNDS
1573         int rounding;
1574 #endif
1575 #ifdef USE_LOCALE
1576         CONST char *s2;
1577 #endif
1578
1579         sign = nz0 = nz = 0;
1580         dval(rv) = 0.;
1581         for(s = s00;;s++) switch(*s) {
1582                 case '-':
1583                         sign = 1;
1584                         /* no break */
1585                 case '+':
1586                         if (*++s)
1587                                 goto break2;
1588                         /* no break */
1589                 case 0:
1590                         goto ret0;
1591                 case '\t':
1592                 case '\n':
1593                 case '\v':
1594                 case '\f':
1595                 case '\r':
1596                 case ' ':
1597                         continue;
1598                 default:
1599                         goto break2;
1600                 }
1601  break2:
1602         if (*s == '0') {
1603                 nz0 = 1;
1604                 while(*++s == '0') ;
1605                 if (!*s)
1606                         goto ret;
1607                 }
1608         s0 = s;
1609         y = z = 0;
1610         for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
1611                 if (nd < 9)
1612                         y = 10*y + c - '0';
1613                 else if (nd < 16)
1614                         z = 10*z + c - '0';
1615         nd0 = nd;
1616 #ifdef USE_LOCALE
1617         s1 = localeconv()->decimal_point;
1618         if (c == *s1) {
1619                 c = '.';
1620                 if (*++s1) {
1621                         s2 = s;
1622                         for(;;) {
1623                                 if (*++s2 != *s1) {
1624                                         c = 0;
1625                                         break;
1626                                         }
1627                                 if (!*++s1) {
1628                                         s = s2;
1629                                         break;
1630                                         }
1631                                 }
1632                         }
1633                 }
1634 #endif
1635         if (c == '.') {
1636                 c = *++s;
1637                 if (!nd) {
1638                         for(; c == '0'; c = *++s)
1639                                 nz++;
1640                         if (c > '0' && c <= '9') {
1641                                 s0 = s;
1642                                 nf += nz;
1643                                 nz = 0;
1644                                 goto have_dig;
1645                                 }
1646                         goto dig_done;
1647                         }
1648                 for(; c >= '0' && c <= '9'; c = *++s) {
1649  have_dig:
1650                         nz++;
1651                         if (c -= '0') {
1652                                 nf += nz;
1653                                 for(i = 1; i < nz; i++)
1654                                         if (nd++ < 9)
1655                                                 y *= 10;
1656                                         else if (nd <= DBL_DIG + 1)
1657                                                 z *= 10;
1658                                 if (nd++ < 9)
1659                                         y = 10*y + c;
1660                                 else if (nd <= DBL_DIG + 1)
1661                                         z = 10*z + c;
1662                                 nz = 0;
1663                                 }
1664                         }
1665                 }
1666  dig_done:
1667         e = 0;
1668         if (c == 'e' || c == 'E') {
1669                 if (!nd && !nz && !nz0) {
1670                         goto ret0;
1671                         }
1672                 s00 = s;
1673                 esign = 0;
1674                 switch(c = *++s) {
1675                         case '-':
1676                                 esign = 1;
1677                         case '+':
1678                                 c = *++s;
1679                         }
1680                 if (c >= '0' && c <= '9') {
1681                         while(c == '0')
1682                                 c = *++s;
1683                         if (c > '0' && c <= '9') {
1684                                 L = c - '0';
1685                                 s1 = s;
1686                                 while((c = *++s) >= '0' && c <= '9')
1687                                         L = 10*L + c - '0';
1688                                 if (s - s1 > 8 || L > 19999)
1689                                         /* Avoid confusion from exponents
1690                                          * so large that e might overflow.
1691                                          */
1692                                         e = 19999; /* safe for 16 bit ints */
1693                                 else
1694                                         e = (int)L;
1695                                 if (esign)
1696                                         e = -e;
1697                                 }
1698                         else
1699                                 e = 0;
1700                         }
1701                 else
1702                         s = s00;
1703                 }
1704         if (!nd) {
1705                 if (!nz && !nz0) {
1706 #ifdef INFNAN_CHECK
1707                         /* Check for Nan and Infinity */
1708                         switch(c) {
1709                           case 'i':
1710                           case 'I':
1711                                 if (match(&s,"nf")) {
1712                                         --s;
1713                                         if (!match(&s,"inity"))
1714                                                 ++s;
1715                                         word0(rv) = 0x7ff00000;
1716                                         word1(rv) = 0;
1717                                         goto ret;
1718                                         }
1719                                 break;
1720                           case 'n':
1721                           case 'N':
1722                                 if (match(&s, "an")) {
1723                                         word0(rv) = NAN_WORD0;
1724                                         word1(rv) = NAN_WORD1;
1725 #ifndef No_Hex_NaN
1726                                         if (*s == '(') /*)*/
1727                                                 hexnan(&rv, &s);
1728 #endif
1729                                         goto ret;
1730                                         }
1731                           }
1732 #endif /* INFNAN_CHECK */
1733  ret0:
1734                         s = s00;
1735                         sign = 0;
1736                         }
1737                 goto ret;
1738                 }
1739         e1 = e -= nf;
1740
1741         /* Now we have nd0 digits, starting at s0, followed by a
1742          * decimal point, followed by nd-nd0 digits.  The number we're
1743          * after is the integer represented by those digits times
1744          * 10**e */
1745
1746         if (!nd0)
1747                 nd0 = nd;
1748         k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1749         dval(rv) = y;
1750         if (k > 9) {
1751 #ifdef SET_INEXACT
1752                 if (k > DBL_DIG)
1753                         oldinexact = get_inexact();
1754 #endif
1755                 dval(rv) = tens[k - 9] * dval(rv) + z;
1756                 }
1757         bd0 = 0;
1758         if (nd <= DBL_DIG
1759 #ifndef RND_PRODQUOT
1760 #ifndef Honor_FLT_ROUNDS
1761                 && Flt_Rounds == 1
1762 #endif
1763 #endif
1764                         ) {
1765                 if (!e)
1766                         goto ret;
1767                 if (e > 0) {
1768                         if (e <= Ten_pmax) {
1769 #ifdef VAX
1770                                 goto vax_ovfl_check;
1771 #else
1772 #ifdef Honor_FLT_ROUNDS
1773                                 /* round correctly FLT_ROUNDS = 2 or 3 */
1774                                 if (sign) {
1775                                         rv = -rv;
1776                                         sign = 0;
1777                                         }
1778 #endif
1779                                 /* rv = */ rounded_product(dval(rv), tens[e]);
1780                                 goto ret;
1781 #endif
1782                                 }
1783                         i = DBL_DIG - nd;
1784                         if (e <= Ten_pmax + i) {
1785                                 /* A fancier test would sometimes let us do
1786                                  * this for larger i values.
1787                                  */
1788 #ifdef Honor_FLT_ROUNDS
1789                                 /* round correctly FLT_ROUNDS = 2 or 3 */
1790                                 if (sign) {
1791                                         rv = -rv;
1792                                         sign = 0;
1793                                         }
1794 #endif
1795                                 e -= i;
1796                                 dval(rv) *= tens[i];
1797 #ifdef VAX
1798                                 /* VAX exponent range is so narrow we must
1799                                  * worry about overflow here...
1800                                  */
1801  vax_ovfl_check:
1802                                 word0(rv) -= P*Exp_msk1;
1803                                 /* rv = */ rounded_product(dval(rv), tens[e]);
1804                                 if ((word0(rv) & Exp_mask)
1805                                  > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
1806                                         goto ovfl;
1807                                 word0(rv) += P*Exp_msk1;
1808 #else
1809                                 /* rv = */ rounded_product(dval(rv), tens[e]);
1810 #endif
1811                                 goto ret;
1812                                 }
1813                         }
1814 #ifndef Inaccurate_Divide
1815                 else if (e >= -Ten_pmax) {
1816 #ifdef Honor_FLT_ROUNDS
1817                         /* round correctly FLT_ROUNDS = 2 or 3 */
1818                         if (sign) {
1819                                 rv = -rv;
1820                                 sign = 0;
1821                                 }
1822 #endif
1823                         /* rv = */ rounded_quotient(dval(rv), tens[-e]);
1824                         goto ret;
1825                         }
1826 #endif
1827                 }
1828         e1 += nd - k;
1829
1830 #ifdef IEEE_Arith
1831 #ifdef SET_INEXACT
1832         inexact = 1;
1833         if (k <= DBL_DIG)
1834                 oldinexact = get_inexact();
1835 #endif
1836 #ifdef Avoid_Underflow
1837         scale = 0;
1838 #endif
1839 #ifdef Honor_FLT_ROUNDS
1840         if ((rounding = Flt_Rounds) >= 2) {
1841                 if (sign)
1842                         rounding = rounding == 2 ? 0 : 2;
1843                 else
1844                         if (rounding != 2)
1845                                 rounding = 0;
1846                 }
1847 #endif
1848 #endif /*IEEE_Arith*/
1849
1850         /* Get starting approximation = rv * 10**e1 */
1851
1852         if (e1 > 0) {
1853                 if ((i = e1 & 15))
1854                         dval(rv) *= tens[i];
1855                 if (e1 &= ~15) {
1856                         if (e1 > DBL_MAX_10_EXP) {
1857  ovfl:
1858 #ifndef NO_ERRNO
1859                                 errno = ERANGE;
1860 #endif
1861                                 /* Can't trust HUGE_VAL */
1862 #ifdef IEEE_Arith
1863 #ifdef Honor_FLT_ROUNDS
1864                                 switch(rounding) {
1865                                   case 0: /* toward 0 */
1866                                   case 3: /* toward -infinity */
1867                                         word0(rv) = Big0;
1868                                         word1(rv) = Big1;
1869                                         break;
1870                                   default:
1871                                         word0(rv) = Exp_mask;
1872                                         word1(rv) = 0;
1873                                   }
1874 #else /*Honor_FLT_ROUNDS*/
1875                                 word0(rv) = Exp_mask;
1876                                 word1(rv) = 0;
1877 #endif /*Honor_FLT_ROUNDS*/
1878 #ifdef SET_INEXACT
1879                                 /* set overflow bit */
1880                                 dval(rv0) = 1e300;
1881                                 dval(rv0) *= dval(rv0);
1882 #endif
1883 #else /*IEEE_Arith*/
1884                                 word0(rv) = Big0;
1885                                 word1(rv) = Big1;
1886 #endif /*IEEE_Arith*/
1887                                 if (bd0)
1888                                         goto retfree;
1889                                 goto ret;
1890                                 }
1891                         e1 >>= 4;
1892                         for(j = 0; e1 > 1; j++, e1 >>= 1)
1893                                 if (e1 & 1)
1894                                         dval(rv) *= bigtens[j];
1895                 /* The last multiplication could overflow. */
1896                         word0(rv) -= P*Exp_msk1;
1897                         dval(rv) *= bigtens[j];
1898                         if ((z = word0(rv) & Exp_mask)
1899                          > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1900                                 goto ovfl;
1901                         if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1902                                 /* set to largest number */
1903                                 /* (Can't trust DBL_MAX) */
1904                                 word0(rv) = Big0;
1905                                 word1(rv) = Big1;
1906                                 }
1907                         else
1908                                 word0(rv) += P*Exp_msk1;
1909                         }
1910                 }
1911         else if (e1 < 0) {
1912                 e1 = -e1;
1913                 if ((i = e1 & 15))
1914                         dval(rv) /= tens[i];
1915                 if (e1 >>= 4) {
1916                         if (e1 >= 1 << n_bigtens)
1917                                 goto undfl;
1918 #ifdef Avoid_Underflow
1919                         if (e1 & Scale_Bit)
1920                                 scale = 2*P;
1921                         for(j = 0; e1 > 0; j++, e1 >>= 1)
1922                                 if (e1 & 1)
1923                                         dval(rv) *= tinytens[j];
1924                         if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask)
1925                                                 >> Exp_shift)) > 0) {
1926                                 /* scaled rv is denormal; zap j low bits */
1927                                 if (j >= 32) {
1928                                         word1(rv) = 0;
1929                                         if (j >= 53)
1930                                          word0(rv) = (P+2)*Exp_msk1;
1931                                         else
1932                                          word0(rv) &= 0xffffffff << (j-32);
1933                                         }
1934                                 else
1935                                         word1(rv) &= 0xffffffff << j;
1936                                 }
1937 #else
1938                         for(j = 0; e1 > 1; j++, e1 >>= 1)
1939                                 if (e1 & 1)
1940                                         dval(rv) *= tinytens[j];
1941                         /* The last multiplication could underflow. */
1942                         dval(rv0) = dval(rv);
1943                         dval(rv) *= tinytens[j];
1944                         if (!dval(rv)) {
1945                                 dval(rv) = 2.*dval(rv0);
1946                                 dval(rv) *= tinytens[j];
1947 #endif
1948                                 if (!dval(rv)) {
1949  undfl:
1950                                         dval(rv) = 0.;
1951 #ifndef NO_ERRNO
1952                                         errno = ERANGE;
1953 #endif
1954                                         if (bd0)
1955                                                 goto retfree;
1956                                         goto ret;
1957                                         }
1958 #ifndef Avoid_Underflow
1959                                 word0(rv) = Tiny0;
1960                                 word1(rv) = Tiny1;
1961                                 /* The refinement below will clean
1962                                  * this approximation up.
1963                                  */
1964                                 }
1965 #endif
1966                         }
1967                 }
1968
1969         /* Now the hard part -- adjusting rv to the correct value.*/
1970
1971         /* Put digits into bd: true value = bd * 10^e */
1972
1973         bd0 = s2b(s0, nd0, nd, y);
1974
1975         for(;;) {
1976                 bd = Balloc(bd0->k);
1977                 Bcopy(bd, bd0);
1978                 bb = d2b(dval(rv), &bbe, &bbbits);      /* rv = bb * 2^bbe */
1979                 bs = i2b(1);
1980
1981                 if (e >= 0) {
1982                         bb2 = bb5 = 0;
1983                         bd2 = bd5 = e;
1984                         }
1985                 else {
1986                         bb2 = bb5 = -e;
1987                         bd2 = bd5 = 0;
1988                         }
1989                 if (bbe >= 0)
1990                         bb2 += bbe;
1991                 else
1992                         bd2 -= bbe;
1993                 bs2 = bb2;
1994 #ifdef Honor_FLT_ROUNDS
1995                 if (rounding != 1)
1996                         bs2++;
1997 #endif
1998 #ifdef Avoid_Underflow
1999                 j = bbe - scale;
2000                 i = j + bbbits - 1;     /* logb(rv) */
2001                 if (i < Emin)   /* denormal */
2002                         j += P - Emin;
2003                 else
2004                         j = P + 1 - bbbits;
2005 #else /*Avoid_Underflow*/
2006 #ifdef Sudden_Underflow
2007 #ifdef IBM
2008                 j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
2009 #else
2010                 j = P + 1 - bbbits;
2011 #endif
2012 #else /*Sudden_Underflow*/
2013                 j = bbe;
2014                 i = j + bbbits - 1;     /* logb(rv) */
2015                 if (i < Emin)   /* denormal */
2016                         j += P - Emin;
2017                 else
2018                         j = P + 1 - bbbits;
2019 #endif /*Sudden_Underflow*/
2020 #endif /*Avoid_Underflow*/
2021                 bb2 += j;
2022                 bd2 += j;
2023 #ifdef Avoid_Underflow
2024                 bd2 += scale;
2025 #endif
2026                 i = bb2 < bd2 ? bb2 : bd2;
2027                 if (i > bs2)
2028                         i = bs2;
2029                 if (i > 0) {
2030                         bb2 -= i;
2031                         bd2 -= i;
2032                         bs2 -= i;
2033                         }
2034                 if (bb5 > 0) {
2035                         bs = pow5mult(bs, bb5);
2036                         bb1 = mult(bs, bb);
2037                         Bfree(bb);
2038                         bb = bb1;
2039                         }
2040                 if (bb2 > 0)
2041                         bb = lshift(bb, bb2);
2042                 if (bd5 > 0)
2043                         bd = pow5mult(bd, bd5);
2044                 if (bd2 > 0)
2045                         bd = lshift(bd, bd2);
2046                 if (bs2 > 0)
2047                         bs = lshift(bs, bs2);
2048                 delta = diff(bb, bd);
2049                 dsign = delta->sign;
2050                 delta->sign = 0;
2051                 i = cmp(delta, bs);
2052 #ifdef Honor_FLT_ROUNDS
2053                 if (rounding != 1) {
2054                         if (i < 0) {
2055                                 /* Error is less than an ulp */
2056                                 if (!delta->x[0] && delta->wds <= 1) {
2057                                         /* exact */
2058 #ifdef SET_INEXACT
2059                                         inexact = 0;
2060 #endif
2061                                         break;
2062                                         }
2063                                 if (rounding) {
2064                                         if (dsign) {
2065                                                 adj = 1.;
2066                                                 goto apply_adj;
2067                                                 }
2068                                         }
2069                                 else if (!dsign) {
2070                                         adj = -1.;
2071                                         if (!word1(rv)
2072                                          && !(word0(rv) & Frac_mask)) {
2073                                                 y = word0(rv) & Exp_mask;
2074 #ifdef Avoid_Underflow
2075                                                 if (!scale || y > 2*P*Exp_msk1)
2076 #else
2077                                                 if (y)
2078 #endif
2079                                                   {
2080                                                   delta = lshift(delta,Log2P);
2081                                                   if (cmp(delta, bs) <= 0)
2082                                                         adj = -0.5;
2083                                                   }
2084                                                 }
2085  apply_adj:
2086 #ifdef Avoid_Underflow
2087                                         if (scale && (y = word0(rv) & Exp_mask)
2088                                                 <= 2*P*Exp_msk1)
2089                                           word0(adj) += (2*P+1)*Exp_msk1 - y;
2090 #else
2091 #ifdef Sudden_Underflow
2092                                         if ((word0(rv) & Exp_mask) <=
2093                                                         P*Exp_msk1) {
2094                                                 word0(rv) += P*Exp_msk1;
2095                                                 dval(rv) += adj*ulp(dval(rv));
2096                                                 word0(rv) -= P*Exp_msk1;
2097                                                 }
2098                                         else
2099 #endif /*Sudden_Underflow*/
2100 #endif /*Avoid_Underflow*/
2101                                         dval(rv) += adj*ulp(dval(rv));
2102                                         }
2103                                 break;
2104                                 }
2105                         adj = ratio(delta, bs);
2106                         if (adj < 1.)
2107                                 adj = 1.;
2108                         if (adj <= 0x7ffffffe) {
2109                                 /* adj = rounding ? ceil(adj) : floor(adj); */
2110                                 y = adj;
2111                                 if (y != adj) {
2112                                         if (!((rounding>>1) ^ dsign))
2113                                                 y++;
2114                                         adj = y;
2115                                         }
2116                                 }
2117 #ifdef Avoid_Underflow
2118                         if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2119                                 word0(adj) += (2*P+1)*Exp_msk1 - y;
2120 #else
2121 #ifdef Sudden_Underflow
2122                         if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2123                                 word0(rv) += P*Exp_msk1;
2124                                 adj *= ulp(dval(rv));
2125                                 if (dsign)
2126                                         dval(rv) += adj;
2127                                 else
2128                                         dval(rv) -= adj;
2129                                 word0(rv) -= P*Exp_msk1;
2130                                 goto cont;
2131                                 }
2132 #endif /*Sudden_Underflow*/
2133 #endif /*Avoid_Underflow*/
2134                         adj *= ulp(dval(rv));
2135                         if (dsign)
2136                                 dval(rv) += adj;
2137                         else
2138                                 dval(rv) -= adj;
2139                         goto cont;
2140                         }
2141 #endif /*Honor_FLT_ROUNDS*/
2142
2143                 if (i < 0) {
2144                         /* Error is less than half an ulp -- check for
2145                          * special case of mantissa a power of two.
2146                          */
2147                         if (dsign || word1(rv) || word0(rv) & Bndry_mask
2148 #ifdef IEEE_Arith
2149 #ifdef Avoid_Underflow
2150                          || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
2151 #else
2152                          || (word0(rv) & Exp_mask) <= Exp_msk1
2153 #endif
2154 #endif
2155                                 ) {
2156 #ifdef SET_INEXACT
2157                                 if (!delta->x[0] && delta->wds <= 1)
2158                                         inexact = 0;
2159 #endif
2160                                 break;
2161                                 }
2162                         if (!delta->x[0] && delta->wds <= 1) {
2163                                 /* exact result */
2164 #ifdef SET_INEXACT
2165                                 inexact = 0;
2166 #endif
2167                                 break;
2168                                 }
2169                         delta = lshift(delta,Log2P);
2170                         if (cmp(delta, bs) > 0)
2171                                 goto drop_down;
2172                         break;
2173                         }
2174                 if (i == 0) {
2175                         /* exactly half-way between */
2176                         if (dsign) {
2177                                 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
2178                                  &&  word1(rv) == (
2179 #ifdef Avoid_Underflow
2180                         (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2181                 ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
2182 #endif
2183                                                    0xffffffff)) {
2184                                         /*boundary case -- increment exponent*/
2185                                         word0(rv) = (word0(rv) & Exp_mask)
2186                                                 + Exp_msk1
2187 #ifdef IBM
2188                                                 | Exp_msk1 >> 4
2189 #endif
2190                                                 ;
2191                                         word1(rv) = 0;
2192 #ifdef Avoid_Underflow
2193                                         dsign = 0;
2194 #endif
2195                                         break;
2196                                         }
2197                                 }
2198                         else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
2199  drop_down:
2200                                 /* boundary case -- decrement exponent */
2201 #ifdef Sudden_Underflow /*{{*/
2202                                 L = word0(rv) & Exp_mask;
2203 #ifdef IBM
2204                                 if (L <  Exp_msk1)
2205 #else
2206 #ifdef Avoid_Underflow
2207                                 if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
2208 #else
2209                                 if (L <= Exp_msk1)
2210 #endif /*Avoid_Underflow*/
2211 #endif /*IBM*/
2212                                         goto undfl;
2213                                 L -= Exp_msk1;
2214 #else /*Sudden_Underflow}{*/
2215 #ifdef Avoid_Underflow
2216                                 if (scale) {
2217                                         L = word0(rv) & Exp_mask;
2218                                         if (L <= (2*P+1)*Exp_msk1) {
2219                                                 if (L > (P+2)*Exp_msk1)
2220                                                         /* round even ==> */
2221                                                         /* accept rv */
2222                                                         break;
2223                                                 /* rv = smallest denormal */
2224                                                 goto undfl;
2225                                                 }
2226                                         }
2227 #endif /*Avoid_Underflow*/
2228                                 L = (word0(rv) & Exp_mask) - Exp_msk1;
2229 #endif /*Sudden_Underflow}}*/
2230                                 word0(rv) = L | Bndry_mask1;
2231                                 word1(rv) = 0xffffffff;
2232 #ifdef IBM
2233                                 goto cont;
2234 #else
2235                                 break;
2236 #endif
2237                                 }
2238 #ifndef ROUND_BIASED
2239                         if (!(word1(rv) & LSB))
2240                                 break;
2241 #endif
2242                         if (dsign)
2243                                 dval(rv) += ulp(dval(rv));
2244 #ifndef ROUND_BIASED
2245                         else {
2246                                 dval(rv) -= ulp(dval(rv));
2247 #ifndef Sudden_Underflow
2248                                 if (!dval(rv))
2249                                         goto undfl;
2250 #endif
2251                                 }
2252 #ifdef Avoid_Underflow
2253                         dsign = 1 - dsign;
2254 #endif
2255 #endif
2256                         break;
2257                         }
2258                 if ((aadj = ratio(delta, bs)) <= 2.) {
2259                         if (dsign)
2260                                 aadj = aadj1 = 1.;
2261                         else if (word1(rv) || word0(rv) & Bndry_mask) {
2262 #ifndef Sudden_Underflow
2263                                 if (word1(rv) == Tiny1 && !word0(rv))
2264                                         goto undfl;
2265 #endif
2266                                 aadj = 1.;
2267                                 aadj1 = -1.;
2268                                 }
2269                         else {
2270                                 /* special case -- power of FLT_RADIX to be */
2271                                 /* rounded down... */
2272
2273                                 if (aadj < 2./FLT_RADIX)
2274                                         aadj = 1./FLT_RADIX;
2275                                 else
2276                                         aadj *= 0.5;
2277                                 aadj1 = -aadj;
2278                                 }
2279                         }
2280                 else {
2281                         aadj *= 0.5;
2282                         aadj1 = dsign ? aadj : -aadj;
2283 #ifdef Check_FLT_ROUNDS
2284                         switch(Rounding) {
2285                                 case 2: /* towards +infinity */
2286                                         aadj1 -= 0.5;
2287                                         break;
2288                                 case 0: /* towards 0 */
2289                                 case 3: /* towards -infinity */
2290                                         aadj1 += 0.5;
2291                                 }
2292 #else
2293                         if (Flt_Rounds == 0)
2294                                 aadj1 += 0.5;
2295 #endif /*Check_FLT_ROUNDS*/
2296                         }
2297                 y = word0(rv) & Exp_mask;
2298
2299                 /* Check for overflow */
2300
2301                 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2302                         dval(rv0) = dval(rv);
2303                         word0(rv) -= P*Exp_msk1;
2304                         adj = aadj1 * ulp(dval(rv));
2305                         dval(rv) += adj;
2306                         if ((word0(rv) & Exp_mask) >=
2307                                         Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2308                                 if (word0(rv0) == Big0 && word1(rv0) == Big1)
2309                                         goto ovfl;
2310                                 word0(rv) = Big0;
2311                                 word1(rv) = Big1;
2312                                 goto cont;
2313                                 }
2314                         else
2315                                 word0(rv) += P*Exp_msk1;
2316                         }
2317                 else {
2318 #ifdef Avoid_Underflow
2319                         if (scale && y <= 2*P*Exp_msk1) {
2320                                 if (aadj <= 0x7fffffff) {
2321                                         if ((z = aadj) <= 0)
2322                                                 z = 1;
2323                                         aadj = z;
2324                                         aadj1 = dsign ? aadj : -aadj;
2325                                         }
2326                                 word0(aadj1) += (2*P+1)*Exp_msk1 - y;
2327                                 }
2328                         adj = aadj1 * ulp(dval(rv));
2329                         dval(rv) += adj;
2330 #else
2331 #ifdef Sudden_Underflow
2332                         if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2333                                 dval(rv0) = dval(rv);
2334                                 word0(rv) += P*Exp_msk1;
2335                                 adj = aadj1 * ulp(dval(rv));
2336                                 dval(rv) += adj;
2337 #ifdef IBM
2338                                 if ((word0(rv) & Exp_mask) <  P*Exp_msk1)
2339 #else
2340                                 if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
2341 #endif
2342                                         {
2343                                         if (word0(rv0) == Tiny0
2344                                          && word1(rv0) == Tiny1)
2345                                                 goto undfl;
2346                                         word0(rv) = Tiny0;
2347                                         word1(rv) = Tiny1;
2348                                         goto cont;
2349                                         }
2350                                 else
2351                                         word0(rv) -= P*Exp_msk1;
2352                                 }
2353                         else {
2354                                 adj = aadj1 * ulp(dval(rv));
2355                                 dval(rv) += adj;
2356                                 }
2357 #else /*Sudden_Underflow*/
2358                         /* Compute adj so that the IEEE rounding rules will
2359                          * correctly round rv + adj in some half-way cases.
2360                          * If rv * ulp(rv) is denormalized (i.e.,
2361                          * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
2362                          * trouble from bits lost to denormalization;
2363                          * example: 1.2e-307 .
2364                          */
2365                         if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
2366                                 aadj1 = (double)(int)(aadj + 0.5);
2367                                 if (!dsign)
2368                                         aadj1 = -aadj1;
2369                                 }
2370                         adj = aadj1 * ulp(dval(rv));
2371                         dval(rv) += adj;
2372 #endif /*Sudden_Underflow*/
2373 #endif /*Avoid_Underflow*/
2374                         }
2375                 z = word0(rv) & Exp_mask;
2376 #ifndef SET_INEXACT
2377 #ifdef Avoid_Underflow
2378                 if (!scale)
2379 #endif
2380                 if (y == z) {
2381                         /* Can we stop now? */
2382                         L = (Long)aadj;
2383                         aadj -= L;
2384                         /* The tolerances below are conservative. */
2385                         if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
2386                                 if (aadj < .4999999 || aadj > .5000001)
2387                                         break;
2388                                 }
2389                         else if (aadj < .4999999/FLT_RADIX)
2390                                 break;
2391                         }
2392 #endif
2393  cont:
2394                 Bfree(bb);
2395                 Bfree(bd);
2396                 Bfree(bs);
2397                 Bfree(delta);
2398                 }
2399 #ifdef SET_INEXACT
2400         if (inexact) {
2401                 if (!oldinexact) {
2402                         word0(rv0) = Exp_1 + (70 << Exp_shift);
2403                         word1(rv0) = 0;
2404                         dval(rv0) += 1.;
2405                         }
2406                 }
2407         else if (!oldinexact)
2408                 clear_inexact();
2409 #endif
2410 #ifdef Avoid_Underflow
2411         if (scale) {
2412                 word0(rv0) = Exp_1 - 2*P*Exp_msk1;
2413                 word1(rv0) = 0;
2414                 dval(rv) *= dval(rv0);
2415 #ifndef NO_ERRNO
2416                 /* try to avoid the bug of testing an 8087 register value */
2417                 if (word0(rv) == 0 && word1(rv) == 0)
2418                         errno = ERANGE;
2419 #endif
2420                 }
2421 #endif /* Avoid_Underflow */
2422 #ifdef SET_INEXACT
2423         if (inexact && !(word0(rv) & Exp_mask)) {
2424                 /* set underflow bit */
2425                 dval(rv0) = 1e-300;
2426                 dval(rv0) *= dval(rv0);
2427                 }
2428 #endif
2429  retfree:
2430         Bfree(bb);
2431         Bfree(bd);
2432         Bfree(bs);
2433         Bfree(bd0);
2434         Bfree(delta);
2435  ret:
2436         if (se)
2437                 *se = (char *)s;
2438         return sign ? -dval(rv) : dval(rv);
2439         }
2440
2441  static int
2442 quorem
2443 #ifdef KR_headers
2444         (b, S) Bigint *b, *S;
2445 #else
2446         (Bigint *b, Bigint *S)
2447 #endif
2448 {
2449         int n;
2450         ULong *bx, *bxe, q, *sx, *sxe;
2451 #ifdef ULLong
2452         ULLong borrow, carry, y, ys;
2453 #else
2454         ULong borrow, carry, y, ys;
2455 #ifdef Pack_32
2456         ULong si, z, zs;
2457 #endif
2458 #endif
2459
2460         n = S->wds;
2461 #ifdef DEBUG
2462         /*debug*/ if (b->wds > n)
2463         /*debug*/       Bug("oversize b in quorem");
2464 #endif
2465         if (b->wds < n)
2466                 return 0;
2467         sx = S->x;
2468         sxe = sx + --n;
2469         bx = b->x;
2470         bxe = bx + n;
2471         q = *bxe / (*sxe + 1);  /* ensure q <= true quotient */
2472 #ifdef DEBUG
2473         /*debug*/ if (q > 9)
2474         /*debug*/       Bug("oversized quotient in quorem");
2475 #endif
2476         if (q) {
2477                 borrow = 0;
2478                 carry = 0;
2479                 do {
2480 #ifdef ULLong
2481                         ys = *sx++ * (ULLong)q + carry;
2482                         carry = ys >> 32;
2483                         y = *bx - (ys & FFFFFFFF) - borrow;
2484                         borrow = y >> 32 & (ULong)1;
2485                         *bx++ = y & FFFFFFFF;
2486 #else
2487 #ifdef Pack_32
2488                         si = *sx++;
2489                         ys = (si & 0xffff) * q + carry;
2490                         zs = (si >> 16) * q + (ys >> 16);
2491                         carry = zs >> 16;
2492                         y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2493                         borrow = (y & 0x10000) >> 16;
2494                         z = (*bx >> 16) - (zs & 0xffff) - borrow;
2495                         borrow = (z & 0x10000) >> 16;
2496                         Storeinc(bx, z, y);
2497 #else
2498                         ys = *sx++ * q + carry;
2499                         carry = ys >> 16;
2500                         y = *bx - (ys & 0xffff) - borrow;
2501                         borrow = (y & 0x10000) >> 16;
2502                         *bx++ = y & 0xffff;
2503 #endif
2504 #endif
2505                         }
2506                         while(sx <= sxe);
2507                 if (!*bxe) {
2508                         bx = b->x;
2509                         while(--bxe > bx && !*bxe)
2510                                 --n;
2511                         b->wds = n;
2512                         }
2513                 }
2514         if (cmp(b, S) >= 0) {
2515                 q++;
2516                 borrow = 0;
2517                 carry = 0;
2518                 bx = b->x;
2519                 sx = S->x;
2520                 do {
2521 #ifdef ULLong
2522                         ys = *sx++ + carry;
2523                         carry = ys >> 32;
2524                         y = *bx - (ys & FFFFFFFF) - borrow;
2525                         borrow = y >> 32 & (ULong)1;
2526                         *bx++ = y & FFFFFFFF;
2527 #else
2528 #ifdef Pack_32
2529                         si = *sx++;
2530                         ys = (si & 0xffff) + carry;
2531                         zs = (si >> 16) + (ys >> 16);
2532                         carry = zs >> 16;
2533                         y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2534                         borrow = (y & 0x10000) >> 16;
2535                         z = (*bx >> 16) - (zs & 0xffff) - borrow;
2536                         borrow = (z & 0x10000) >> 16;
2537                         Storeinc(bx, z, y);
2538 #else
2539                         ys = *sx++ + carry;
2540                         carry = ys >> 16;
2541                         y = *bx - (ys & 0xffff) - borrow;
2542                         borrow = (y & 0x10000) >> 16;
2543                         *bx++ = y & 0xffff;
2544 #endif
2545 #endif
2546                         }
2547                         while(sx <= sxe);
2548                 bx = b->x;
2549                 bxe = bx + n;
2550                 if (!*bxe) {
2551                         while(--bxe > bx && !*bxe)
2552                                 --n;
2553                         b->wds = n;
2554                         }
2555                 }
2556         return q;
2557         }
2558
2559 #ifndef MULTIPLE_THREADS
2560  static char *dtoa_result;
2561 #endif
2562
2563  static char *
2564 #ifdef KR_headers
2565 rv_alloc(i) int i;
2566 #else
2567 rv_alloc(int i)
2568 #endif
2569 {
2570         int j, k, *r;
2571
2572         j = sizeof(ULong);
2573         for(k = 0;
2574                 sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i;
2575                 j <<= 1)
2576                         k++;
2577         r = (int*)Balloc(k);
2578         *r = k;
2579         return
2580 #ifndef MULTIPLE_THREADS
2581         dtoa_result =
2582 #endif
2583                 (char *)(r+1);
2584         }
2585
2586  static char *
2587 #ifdef KR_headers
2588 nrv_alloc(s, rve, n) char *s, **rve; int n;
2589 #else
2590 nrv_alloc(char *s, char **rve, int n)
2591 #endif
2592 {
2593         char *rv, *t;
2594
2595         t = rv = rv_alloc(n);
2596         while((*t = *s++)) t++;
2597         if (rve)
2598                 *rve = t;
2599         return rv;
2600         }
2601
2602 /* freedtoa(s) must be used to free values s returned by dtoa
2603  * when MULTIPLE_THREADS is #defined.  It should be used in all cases,
2604  * but for consistency with earlier versions of dtoa, it is optional
2605  * when MULTIPLE_THREADS is not defined.
2606  */
2607
2608 static void freedtoa (char *s);
2609
2610 static void
2611 #ifdef KR_headers
2612 freedtoa(s) char *s;
2613 #else
2614 freedtoa(char *s)
2615 #endif
2616 {
2617         Bigint *b = (Bigint *)((int *)s - 1);
2618         b->maxwds = 1 << (b->k = *(int*)b);
2619         Bfree(b);
2620 #ifndef MULTIPLE_THREADS
2621         if (s == dtoa_result)
2622                 dtoa_result = 0;
2623 #endif
2624         }
2625
2626 #if 0
2627 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
2628  *
2629  * Inspired by "How to Print Floating-Point Numbers Accurately" by
2630  * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
2631  *
2632  * Modifications:
2633  *      1. Rather than iterating, we use a simple numeric overestimate
2634  *         to determine k = floor(log10(d)).  We scale relevant
2635  *         quantities using O(log2(k)) rather than O(k) multiplications.
2636  *      2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
2637  *         try to generate digits strictly left to right.  Instead, we
2638  *         compute with fewer bits and propagate the carry if necessary
2639  *         when rounding the final digit up.  This is often faster.
2640  *      3. Under the assumption that input will be rounded nearest,
2641  *         mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
2642  *         That is, we allow equality in stopping tests when the
2643  *         round-nearest rule will give the same floating-point value
2644  *         as would satisfaction of the stopping test with strict
2645  *         inequality.
2646  *      4. We remove common factors of powers of 2 from relevant
2647  *         quantities.
2648  *      5. When converting floating-point integers less than 1e16,
2649  *         we use floating-point arithmetic rather than resorting
2650  *         to multiple-precision integers.
2651  *      6. When asked to produce fewer than 15 digits, we first try
2652  *         to get by with floating-point arithmetic; we resort to
2653  *         multiple-precision integer arithmetic only if we cannot
2654  *         guarantee that the floating-point calculation has given
2655  *         the correctly rounded result.  For k requested digits and
2656  *         "uniformly" distributed input, the probability is
2657  *         something like 10^(k-15) that we must resort to the Long
2658  *         calculation.
2659  */
2660
2661  char *
2662 dtoa
2663 #ifdef KR_headers
2664         (d, mode, ndigits, decpt, sign, rve)
2665         double d; int mode, ndigits, *decpt, *sign; char **rve;
2666 #else
2667         (double d, int mode, int ndigits, int *decpt, int *sign, char **rve)
2668 #endif
2669 {
2670  /*     Arguments ndigits, decpt, sign are similar to those
2671         of ecvt and fcvt; trailing zeros are suppressed from
2672         the returned string.  If not null, *rve is set to point
2673         to the end of the return value.  If d is +-Infinity or NaN,
2674         then *decpt is set to 9999.
2675
2676         mode:
2677                 0 ==> shortest string that yields d when read in
2678                         and rounded to nearest.
2679                 1 ==> like 0, but with Steele & White stopping rule;
2680                         e.g. with IEEE P754 arithmetic , mode 0 gives
2681                         1e23 whereas mode 1 gives 9.999999999999999e22.
2682                 2 ==> max(1,ndigits) significant digits.  This gives a
2683                         return value similar to that of ecvt, except
2684                         that trailing zeros are suppressed.
2685                 3 ==> through ndigits past the decimal point.  This
2686                         gives a return value similar to that from fcvt,
2687                         except that trailing zeros are suppressed, and
2688                         ndigits can be negative.
2689                 4,5 ==> similar to 2 and 3, respectively, but (in
2690                         round-nearest mode) with the tests of mode 0 to
2691                         possibly return a shorter string that rounds to d.
2692                         With IEEE arithmetic and compilation with
2693                         -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
2694                         as modes 2 and 3 when FLT_ROUNDS != 1.
2695                 6-9 ==> Debugging modes similar to mode - 4:  don't try
2696                         fast floating-point estimate (if applicable).
2697
2698                 Values of mode other than 0-9 are treated as mode 0.
2699
2700                 Sufficient space is allocated to the return value
2701                 to hold the suppressed trailing zeros.
2702         */
2703
2704         int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2705                 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2706                 spec_case, try_quick;
2707         Long L;
2708 #ifndef Sudden_Underflow
2709         int denorm;
2710         ULong x;
2711 #endif
2712         Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2713         double d2, ds, eps;
2714         char *s, *s0;
2715 #ifdef Honor_FLT_ROUNDS
2716         int rounding;
2717 #endif
2718 #ifdef SET_INEXACT
2719         int inexact, oldinexact;
2720 #endif
2721
2722 #ifndef MULTIPLE_THREADS
2723         if (dtoa_result) {
2724                 freedtoa(dtoa_result);
2725                 dtoa_result = 0;
2726                 }
2727 #endif
2728
2729         if (word0(d) & Sign_bit) {
2730                 /* set sign for everything, including 0's and NaNs */
2731                 *sign = 1;
2732                 word0(d) &= ~Sign_bit;  /* clear sign bit */
2733                 }
2734         else
2735                 *sign = 0;
2736
2737 #if defined(IEEE_Arith) + defined(VAX)
2738 #ifdef IEEE_Arith
2739         if ((word0(d) & Exp_mask) == Exp_mask)
2740 #else
2741         if (word0(d)  == 0x8000)
2742 #endif
2743                 {
2744                 /* Infinity or NaN */
2745                 *decpt = 9999;
2746 #ifdef IEEE_Arith
2747                 if (!word1(d) && !(word0(d) & 0xfffff))
2748                         return nrv_alloc("Infinity", rve, 8);
2749 #endif
2750                 return nrv_alloc("NaN", rve, 3);
2751                 }
2752 #endif
2753 #ifdef IBM
2754         dval(d) += 0; /* normalize */
2755 #endif
2756         if (!dval(d)) {
2757                 *decpt = 1;
2758                 return nrv_alloc("0", rve, 1);
2759                 }
2760
2761 #ifdef SET_INEXACT
2762         try_quick = oldinexact = get_inexact();
2763         inexact = 1;
2764 #endif
2765 #ifdef Honor_FLT_ROUNDS
2766         if ((rounding = Flt_Rounds) >= 2) {
2767                 if (*sign)
2768                         rounding = rounding == 2 ? 0 : 2;
2769                 else
2770                         if (rounding != 2)
2771                                 rounding = 0;
2772                 }
2773 #endif
2774
2775         b = d2b(dval(d), &be, &bbits);
2776 #ifdef Sudden_Underflow
2777         i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
2778 #else
2779         if (i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) {
2780 #endif
2781                 dval(d2) = dval(d);
2782                 word0(d2) &= Frac_mask1;
2783                 word0(d2) |= Exp_11;
2784 #ifdef IBM
2785                 if (j = 11 - hi0bits(word0(d2) & Frac_mask))
2786                         dval(d2) /= 1 << j;
2787 #endif
2788
2789                 /* log(x)       ~=~ log(1.5) + (x-1.5)/1.5
2790                  * log10(x)      =  log(x) / log(10)
2791                  *              ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2792                  * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
2793                  *
2794                  * This suggests computing an approximation k to log10(d) by
2795                  *
2796                  * k = (i - Bias)*0.301029995663981
2797                  *      + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2798                  *
2799                  * We want k to be too large rather than too small.
2800                  * The error in the first-order Taylor series approximation
2801                  * is in our favor, so we just round up the constant enough
2802                  * to compensate for any error in the multiplication of
2803                  * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2804                  * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2805                  * adding 1e-13 to the constant term more than suffices.
2806                  * Hence we adjust the constant term to 0.1760912590558.
2807                  * (We could get a more accurate k by invoking log10,
2808                  *  but this is probably not worthwhile.)
2809                  */
2810
2811                 i -= Bias;
2812 #ifdef IBM
2813                 i <<= 2;
2814                 i += j;
2815 #endif
2816 #ifndef Sudden_Underflow
2817                 denorm = 0;
2818                 }
2819         else {
2820                 /* d is denormalized */
2821
2822                 i = bbits + be + (Bias + (P-1) - 1);
2823                 x = i > 32  ? word0(d) << 64 - i | word1(d) >> i - 32
2824                             : word1(d) << 32 - i;
2825                 dval(d2) = x;
2826                 word0(d2) -= 31*Exp_msk1; /* adjust exponent */
2827                 i -= (Bias + (P-1) - 1) + 1;
2828                 denorm = 1;
2829                 }
2830 #endif
2831         ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
2832         k = (int)ds;
2833         if (ds < 0. && ds != k)
2834                 k--;    /* want k = floor(ds) */
2835         k_check = 1;
2836         if (k >= 0 && k <= Ten_pmax) {
2837                 if (dval(d) < tens[k])
2838                         k--;
2839                 k_check = 0;
2840                 }
2841         j = bbits - i - 1;
2842         if (j >= 0) {
2843                 b2 = 0;
2844                 s2 = j;
2845                 }
2846         else {
2847                 b2 = -j;
2848                 s2 = 0;
2849                 }
2850         if (k >= 0) {
2851                 b5 = 0;
2852                 s5 = k;
2853                 s2 += k;
2854                 }
2855         else {
2856                 b2 -= k;
2857                 b5 = -k;
2858                 s5 = 0;
2859                 }
2860         if (mode < 0 || mode > 9)
2861                 mode = 0;
2862
2863 #ifndef SET_INEXACT
2864 #ifdef Check_FLT_ROUNDS
2865         try_quick = Rounding == 1;
2866 #else
2867         try_quick = 1;
2868 #endif
2869 #endif /*SET_INEXACT*/
2870
2871         if (mode > 5) {
2872                 mode -= 4;
2873                 try_quick = 0;
2874                 }
2875         leftright = 1;
2876         switch(mode) {
2877                 case 0:
2878                 case 1:
2879                         ilim = ilim1 = -1;
2880                         i = 18;
2881                         ndigits = 0;
2882                         break;
2883                 case 2:
2884                         leftright = 0;
2885                         /* no break */
2886                 case 4:
2887                         if (ndigits <= 0)
2888                                 ndigits = 1;
2889                         ilim = ilim1 = i = ndigits;
2890                         break;
2891                 case 3:
2892                         leftright = 0;
2893                         /* no break */
2894                 case 5:
2895                         i = ndigits + k + 1;
2896                         ilim = i;
2897                         ilim1 = i - 1;
2898                         if (i <= 0)
2899                                 i = 1;
2900                 }
2901         s = s0 = rv_alloc(i);
2902
2903 #ifdef Honor_FLT_ROUNDS
2904         if (mode > 1 && rounding != 1)
2905                 leftright = 0;
2906 #endif
2907
2908         if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2909
2910                 /* Try to get by with floating-point arithmetic. */
2911
2912                 i = 0;
2913                 dval(d2) = dval(d);
2914                 k0 = k;
2915                 ilim0 = ilim;
2916                 ieps = 2; /* conservative */
2917                 if (k > 0) {
2918                         ds = tens[k&0xf];
2919                         j = k >> 4;
2920                         if (j & Bletch) {
2921                                 /* prevent overflows */
2922                                 j &= Bletch - 1;
2923                                 dval(d) /= bigtens[n_bigtens-1];
2924                                 ieps++;
2925                                 }
2926                         for(; j; j >>= 1, i++)
2927                                 if (j & 1) {
2928                                         ieps++;
2929                                         ds *= bigtens[i];
2930                                         }
2931                         dval(d) /= ds;
2932                         }
2933                 else if (j1 = -k) {
2934                         dval(d) *= tens[j1 & 0xf];
2935                         for(j = j1 >> 4; j; j >>= 1, i++)
2936                                 if (j & 1) {
2937                                         ieps++;
2938                                         dval(d) *= bigtens[i];
2939                                         }
2940                         }
2941                 if (k_check && dval(d) < 1. && ilim > 0) {
2942                         if (ilim1 <= 0)
2943                                 goto fast_failed;
2944                         ilim = ilim1;
2945                         k--;
2946                         dval(d) *= 10.;
2947                         ieps++;
2948                         }
2949                 dval(eps) = ieps*dval(d) + 7.;
2950                 word0(eps) -= (P-1)*Exp_msk1;
2951                 if (ilim == 0) {
2952                         S = mhi = 0;
2953                         dval(d) -= 5.;
2954                         if (dval(d) > dval(eps))
2955                                 goto one_digit;
2956                         if (dval(d) < -dval(eps))
2957                                 goto no_digits;
2958                         goto fast_failed;
2959                         }
2960 #ifndef No_leftright
2961                 if (leftright) {
2962                         /* Use Steele & White method of only
2963                          * generating digits needed.
2964                          */
2965                         dval(eps) = 0.5/tens[ilim-1] - dval(eps);
2966                         for(i = 0;;) {
2967                                 L = dval(d);
2968                                 dval(d) -= L;
2969                                 *s++ = '0' + (int)L;
2970                                 if (dval(d) < dval(eps))
2971                                         goto ret1;
2972                                 if (1. - dval(d) < dval(eps))
2973                                         goto bump_up;
2974                                 if (++i >= ilim)
2975                                         break;
2976                                 dval(eps) *= 10.;
2977                                 dval(d) *= 10.;
2978                                 }
2979                         }
2980                 else {
2981 #endif
2982                         /* Generate ilim digits, then fix them up. */
2983                         dval(eps) *= tens[ilim-1];
2984                         for(i = 1;; i++, dval(d) *= 10.) {
2985                                 L = (Long)(dval(d));
2986                                 if (!(dval(d) -= L))
2987                                         ilim = i;
2988                                 *s++ = '0' + (int)L;
2989                                 if (i == ilim) {
2990                                         if (dval(d) > 0.5 + dval(eps))
2991                                                 goto bump_up;
2992                                         else if (dval(d) < 0.5 - dval(eps)) {
2993                                                 while(*--s == '0');
2994                                                 s++;
2995                                                 goto ret1;
2996                                                 }
2997                                         break;
2998                                         }
2999                                 }
3000 #ifndef No_leftright
3001                         }
3002 #endif
3003  fast_failed:
3004                 s = s0;
3005                 dval(d) = dval(d2);
3006                 k = k0;
3007                 ilim = ilim0;
3008                 }
3009
3010         /* Do we have a "small" integer? */
3011
3012         if (be >= 0 && k <= Int_max) {
3013                 /* Yes. */
3014                 ds = tens[k];
3015                 if (ndigits < 0 && ilim <= 0) {
3016                         S = mhi = 0;
3017                         if (ilim < 0 || dval(d) <= 5*ds)
3018                                 goto no_digits;
3019                         goto one_digit;
3020                         }
3021                 for(i = 1;; i++, dval(d) *= 10.) {
3022                         L = (Long)(dval(d) / ds);
3023                         dval(d) -= L*ds;
3024 #ifdef Check_FLT_ROUNDS
3025                         /* If FLT_ROUNDS == 2, L will usually be high by 1 */
3026                         if (dval(d) < 0) {
3027                                 L--;
3028                                 dval(d) += ds;
3029                                 }
3030 #endif
3031                         *s++ = '0' + (int)L;
3032                         if (!dval(d)) {
3033 #ifdef SET_INEXACT
3034                                 inexact = 0;
3035 #endif
3036                                 break;
3037                                 }
3038                         if (i == ilim) {
3039 #ifdef Honor_FLT_ROUNDS
3040                                 if (mode > 1)
3041                                 switch(rounding) {
3042                                   case 0: goto ret1;
3043                                   case 2: goto bump_up;
3044                                   }
3045 #endif
3046                                 dval(d) += dval(d);
3047                                 if (dval(d) > ds || dval(d) == ds && L & 1) {
3048  bump_up:
3049                                         while(*--s == '9')
3050                                                 if (s == s0) {
3051                                                         k++;
3052                                                         *s = '0';
3053                                                         break;
3054                                                         }
3055                                         ++*s++;
3056                                         }
3057                                 break;
3058                                 }
3059                         }
3060                 goto ret1;
3061                 }
3062
3063         m2 = b2;
3064         m5 = b5;
3065         mhi = mlo = 0;
3066         if (leftright) {
3067                 i =
3068 #ifndef Sudden_Underflow
3069                         denorm ? be + (Bias + (P-1) - 1 + 1) :
3070 #endif
3071 #ifdef IBM
3072                         1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
3073 #else
3074                         1 + P - bbits;
3075 #endif
3076                 b2 += i;
3077                 s2 += i;
3078                 mhi = i2b(1);
3079                 }
3080         if (m2 > 0 && s2 > 0) {
3081                 i = m2 < s2 ? m2 : s2;
3082                 b2 -= i;
3083                 m2 -= i;
3084                 s2 -= i;
3085                 }
3086         if (b5 > 0) {
3087                 if (leftright) {
3088                         if (m5 > 0) {
3089                                 mhi = pow5mult(mhi, m5);
3090                                 b1 = mult(mhi, b);
3091                                 Bfree(b);
3092                                 b = b1;
3093                                 }
3094                         if (j = b5 - m5)
3095                                 b = pow5mult(b, j);
3096                         }
3097                 else
3098                         b = pow5mult(b, b5);
3099                 }
3100         S = i2b(1);
3101         if (s5 > 0)
3102                 S = pow5mult(S, s5);
3103
3104         /* Check for special case that d is a normalized power of 2. */
3105
3106         spec_case = 0;
3107         if ((mode < 2 || leftright)
3108 #ifdef Honor_FLT_ROUNDS
3109                         && rounding == 1
3110 #endif
3111                                 ) {
3112                 if (!word1(d) && !(word0(d) & Bndry_mask)
3113 #ifndef Sudden_Underflow
3114                  && word0(d) & (Exp_mask & ~Exp_msk1)
3115 #endif
3116                                 ) {
3117                         /* The special case */
3118                         b2 += Log2P;
3119                         s2 += Log2P;
3120                         spec_case = 1;
3121                         }
3122                 }
3123
3124         /* Arrange for convenient computation of quotients:
3125          * shift left if necessary so divisor has 4 leading 0 bits.
3126          *
3127          * Perhaps we should just compute leading 28 bits of S once
3128          * and for all and pass them and a shift to quorem, so it
3129          * can do shifts and ors to compute the numerator for q.
3130          */
3131 #ifdef Pack_32
3132         if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)
3133                 i = 32 - i;
3134 #else
3135         if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf)
3136                 i = 16 - i;
3137 #endif
3138         if (i > 4) {
3139                 i -= 4;
3140                 b2 += i;
3141                 m2 += i;
3142                 s2 += i;
3143                 }
3144         else if (i < 4) {
3145                 i += 28;
3146                 b2 += i;
3147                 m2 += i;
3148                 s2 += i;
3149                 }
3150         if (b2 > 0)
3151                 b = lshift(b, b2);
3152         if (s2 > 0)
3153                 S = lshift(S, s2);
3154         if (k_check) {
3155                 if (cmp(b,S) < 0) {
3156                         k--;
3157                         b = multadd(b, 10, 0);  /* we botched the k estimate */
3158                         if (leftright)
3159                                 mhi = multadd(mhi, 10, 0);
3160                         ilim = ilim1;
3161                         }
3162                 }
3163         if (ilim <= 0 && (mode == 3 || mode == 5)) {
3164                 if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
3165                         /* no digits, fcvt style */
3166  no_digits:
3167                         k = -1 - ndigits;
3168                         goto ret;
3169                         }
3170  one_digit:
3171                 *s++ = '1';
3172                 k++;
3173                 goto ret;
3174                 }
3175         if (leftright) {
3176                 if (m2 > 0)
3177                         mhi = lshift(mhi, m2);
3178
3179                 /* Compute mlo -- check for special case
3180                  * that d is a normalized power of 2.
3181                  */
3182
3183                 mlo = mhi;
3184                 if (spec_case) {
3185                         mhi = Balloc(mhi->k);
3186                         Bcopy(mhi, mlo);
3187                         mhi = lshift(mhi, Log2P);
3188                         }
3189
3190                 for(i = 1;;i++) {
3191                         dig = quorem(b,S) + '0';
3192                         /* Do we yet have the shortest decimal string
3193                          * that will round to d?
3194                          */
3195                         j = cmp(b, mlo);
3196                         delta = diff(S, mhi);
3197                         j1 = delta->sign ? 1 : cmp(b, delta);
3198                         Bfree(delta);
3199 #ifndef ROUND_BIASED
3200                         if (j1 == 0 && mode != 1 && !(word1(d) & 1)
3201 #ifdef Honor_FLT_ROUNDS
3202                                 && rounding >= 1
3203 #endif
3204                                                                    ) {
3205                                 if (dig == '9')
3206                                         goto round_9_up;
3207                                 if (j > 0)
3208                                         dig++;
3209 #ifdef SET_INEXACT
3210                                 else if (!b->x[0] && b->wds <= 1)
3211                                         inexact = 0;
3212 #endif
3213                                 *s++ = dig;
3214                                 goto ret;
3215                                 }
3216 #endif
3217                         if (j < 0 || j == 0 && mode != 1
3218 #ifndef ROUND_BIASED
3219                                                         && !(word1(d) & 1)
3220 #endif
3221                                         ) {
3222                                 if (!b->x[0] && b->wds <= 1) {
3223 #ifdef SET_INEXACT
3224                                         inexact = 0;
3225 #endif
3226                                         goto accept_dig;
3227                                         }
3228 #ifdef Honor_FLT_ROUNDS
3229                                 if (mode > 1)
3230                                  switch(rounding) {
3231                                   case 0: goto accept_dig;
3232                                   case 2: goto keep_dig;
3233                                   }
3234 #endif /*Honor_FLT_ROUNDS*/
3235                                 if (j1 > 0) {
3236                                         b = lshift(b, 1);
3237                                         j1 = cmp(b, S);
3238                                         if ((j1 > 0 || j1 == 0 && dig & 1)
3239                                         && dig++ == '9')
3240                                                 goto round_9_up;
3241                                         }
3242  accept_dig:
3243                                 *s++ = dig;
3244                                 goto ret;
3245                                 }
3246                         if (j1 > 0) {
3247 #ifdef Honor_FLT_ROUNDS
3248                                 if (!rounding)
3249                                         goto accept_dig;
3250 #endif
3251                                 if (dig == '9') { /* possible if i == 1 */
3252  round_9_up:
3253                                         *s++ = '9';
3254                                         goto roundoff;
3255                                         }
3256                                 *s++ = dig + 1;
3257                                 goto ret;
3258                                 }
3259 #ifdef Honor_FLT_ROUNDS
3260  keep_dig:
3261 #endif
3262                         *s++ = dig;
3263                         if (i == ilim)
3264                                 break;
3265                         b = multadd(b, 10, 0);
3266                         if (mlo == mhi)
3267                                 mlo = mhi = multadd(mhi, 10, 0);
3268                         else {
3269                                 mlo = multadd(mlo, 10, 0);
3270                                 mhi = multadd(mhi, 10, 0);
3271                                 }
3272                         }
3273                 }
3274         else
3275                 for(i = 1;; i++) {
3276                         *s++ = dig = quorem(b,S) + '0';
3277                         if (!b->x[0] && b->wds <= 1) {
3278 #ifdef SET_INEXACT
3279                                 inexact = 0;
3280 #endif
3281                                 goto ret;
3282                                 }
3283                         if (i >= ilim)
3284                                 break;
3285                         b = multadd(b, 10, 0);
3286                         }
3287
3288         /* Round off last digit */
3289
3290 #ifdef Honor_FLT_ROUNDS
3291         switch(rounding) {
3292           case 0: goto trimzeros;
3293           case 2: goto roundoff;
3294           }
3295 #endif
3296         b = lshift(b, 1);
3297         j = cmp(b, S);
3298         if (j > 0 || j == 0 && dig & 1) {
3299  roundoff:
3300                 while(*--s == '9')
3301                         if (s == s0) {
3302                                 k++;
3303                                 *s++ = '1';
3304                                 goto ret;
3305                                 }
3306                 ++*s++;
3307                 }
3308         else {
3309  trimzeros:
3310                 while(*--s == '0');
3311                 s++;
3312                 }
3313  ret:
3314         Bfree(S);
3315         if (mhi) {
3316                 if (mlo && mlo != mhi)
3317                         Bfree(mlo);
3318                 Bfree(mhi);
3319                 }
3320  ret1:
3321 #ifdef SET_INEXACT
3322         if (inexact) {
3323                 if (!oldinexact) {
3324                         word0(d) = Exp_1 + (70 << Exp_shift);
3325                         word1(d) = 0;
3326                         dval(d) += 1.;
3327                         }
3328                 }
3329         else if (!oldinexact)
3330                 clear_inexact();
3331 #endif
3332         Bfree(b);
3333         *s = 0;
3334         *decpt = k + 1;
3335         if (rve)
3336                 *rve = s;
3337         return s0;
3338         }
3339 #endif
3340
3341 #ifdef __cplusplus
3342 }
3343 #endif