]> granicus.if.org Git - jq/commitdiff
Add decNumber library
authorLeonid S. Usov <leonid@practi.net>
Fri, 26 Oct 2018 21:04:35 +0000 (00:04 +0300)
committerWilliam Langford <wlangfor@gmail.com>
Tue, 22 Oct 2019 18:11:04 +0000 (14:11 -0400)
The library adds support for decimal numbers of arbitrary length.
Downloaded from ICU, under ICU 1.8.1 license
http://download.icu-project.org/files/decNumber/decNumber-icu-368.zip

36 files changed:
COPYING
docs/content/download/default.yml
src/decNumber/ICU-license.html [new file with mode: 0644]
src/decNumber/decBasic.c [new file with mode: 0644]
src/decNumber/decCommon.c [new file with mode: 0644]
src/decNumber/decContext.c [new file with mode: 0644]
src/decNumber/decContext.h [new file with mode: 0644]
src/decNumber/decDPD.h [new file with mode: 0644]
src/decNumber/decDouble.c [new file with mode: 0644]
src/decNumber/decDouble.h [new file with mode: 0644]
src/decNumber/decNumber.c [new file with mode: 0644]
src/decNumber/decNumber.h [new file with mode: 0644]
src/decNumber/decNumberLocal.h [new file with mode: 0644]
src/decNumber/decPacked.c [new file with mode: 0644]
src/decNumber/decPacked.h [new file with mode: 0644]
src/decNumber/decQuad.c [new file with mode: 0644]
src/decNumber/decQuad.h [new file with mode: 0644]
src/decNumber/decSingle.c [new file with mode: 0644]
src/decNumber/decSingle.h [new file with mode: 0644]
src/decNumber/decimal128.c [new file with mode: 0644]
src/decNumber/decimal128.h [new file with mode: 0644]
src/decNumber/decimal32.c [new file with mode: 0644]
src/decNumber/decimal32.h [new file with mode: 0644]
src/decNumber/decimal64.c [new file with mode: 0644]
src/decNumber/decimal64.h [new file with mode: 0644]
src/decNumber/decnumber.pdf [new file with mode: 0644]
src/decNumber/example1.c [new file with mode: 0644]
src/decNumber/example2.c [new file with mode: 0644]
src/decNumber/example3.c [new file with mode: 0644]
src/decNumber/example4.c [new file with mode: 0644]
src/decNumber/example5.c [new file with mode: 0644]
src/decNumber/example6.c [new file with mode: 0644]
src/decNumber/example7.c [new file with mode: 0644]
src/decNumber/example8.c [new file with mode: 0644]
src/decNumber/readme.txt [new file with mode: 0644]
tests.out [new file with mode: 0644]

diff --git a/COPYING b/COPYING
index 7222ff0be7f18f8b2467bc03e48ffb0e7c344977..3e1dd1fa6ccf70f03045bfac3ee2dd710778e6a4 100644 (file)
--- a/COPYING
+++ b/COPYING
@@ -68,3 +68,41 @@ WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
 REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
 OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
 
+
+
+jq uses parts of the open source C library "decNumber", which is distribured
+under the following license:
+
+
+ICU License - ICU 1.8.1 and later
+
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright (c) 1995-2005 International Business Machines Corporation and others
+All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, and/or sell copies of the Software, and to permit persons
+to whom the Software is furnished to do so, provided that the above
+copyright notice(s) and this permission notice appear in all copies of
+the Software and that both the above copyright notice(s) and this
+permission notice appear in supporting documentation.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder
+shall not be used in advertising or otherwise to promote the sale, use
+or other dealings in this Software without prior written authorization
+of the copyright holder.
+
index 8fb1216b84c55b7335793f945f00f50c57ec9493..8ff45804bfeff6fed47e4ee9f39c2293e632f122 100644 (file)
@@ -13,6 +13,10 @@ body:
       jq is licensed under the MIT license. For all of the gory
       details, read the file `COPYING` in the source distribution.
 
+      jq uses a C library for decimal number support. This is an ICU 1.8.1
+      licensed code obtained from the ICU downloads archive
+      http://download.icu-project.org/files/decNumber/decNumber-icu-368.zip.
+
 
       ### Linux
 
diff --git a/src/decNumber/ICU-license.html b/src/decNumber/ICU-license.html
new file mode 100644 (file)
index 0000000..bc99e8b
--- /dev/null
@@ -0,0 +1,45 @@
+<html>\r
+\r
+<head>\r
+<meta http-equiv="Content-Type" content="text/html; charset=us-ascii"></meta>\r
+<title>ICU License - ICU 1.8.1 and later</title>\r
+</head>\r
+\r
+<body>\r
+<h1>ICU License - ICU 1.8.1 and later</h1>\r
+<pre>\r
+COPYRIGHT AND PERMISSION NOTICE\r
+\r
+Copyright (c) 1995-2005 International Business Machines Corporation and others\r
+All rights reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a\r
+copy of this software and associated documentation files (the\r
+"Software"), to deal in the Software without restriction, including\r
+without limitation the rights to use, copy, modify, merge, publish,\r
+distribute, and/or sell copies of the Software, and to permit persons\r
+to whom the Software is furnished to do so, provided that the above\r
+copyright notice(s) and this permission notice appear in all copies of\r
+the Software and that both the above copyright notice(s) and this\r
+permission notice appear in supporting documentation.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\r
+OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\r
+HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL\r
+INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING\r
+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\r
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION\r
+WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\r
+\r
+Except as contained in this notice, the name of a copyright holder\r
+shall not be used in advertising or otherwise to promote the sale, use\r
+or other dealings in this Software without prior written authorization\r
+of the copyright holder.\r
+\r
+--------------------------------------------------------------------------------\r
+All trademarks and registered trademarks mentioned herein are the property of their respective owners.\r
+</pre>\r
+</body>\r
+</html>\r
diff --git a/src/decNumber/decBasic.c b/src/decNumber/decBasic.c
new file mode 100644 (file)
index 0000000..1f680c4
--- /dev/null
@@ -0,0 +1,3908 @@
+/* ------------------------------------------------------------------ */\r
+/* decBasic.c -- common base code for Basic decimal types             */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2010.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is included in the package as decNumber.pdf.  This   */\r
+/* document is also available in HTML, together with specifications,  */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises code that is shared between decDouble and    */\r
+/* decQuad (but not decSingle).  The main arithmetic operations are   */\r
+/* here (Add, Subtract, Multiply, FMA, and Division operators).       */\r
+/*                                                                    */\r
+/* Unlike decNumber, parameterization takes place at compile time     */\r
+/* rather than at runtime.  The parameters are set in the decDouble.c */\r
+/* (etc.) files, which then include this one to produce the compiled  */\r
+/* code.  The functions here, therefore, are code shared between      */\r
+/* multiple formats.                                                  */\r
+/*                                                                    */\r
+/* This must be included after decCommon.c.                           */\r
+/* ------------------------------------------------------------------ */\r
+// Names here refer to decFloat rather than to decDouble, etc., and\r
+// the functions are in strict alphabetical order.\r
+\r
+// The compile-time flags SINGLE, DOUBLE, and QUAD are set up in\r
+// decCommon.c\r
+#if !defined(QUAD)\r
+  #error decBasic.c must be included after decCommon.c\r
+#endif\r
+#if SINGLE\r
+  #error Routines in decBasic.c are for decDouble and decQuad only\r
+#endif\r
+\r
+/* Private constants */\r
+#define DIVIDE      0x80000000     // Divide operations [as flags]\r
+#define REMAINDER   0x40000000     // ..\r
+#define DIVIDEINT   0x20000000     // ..\r
+#define REMNEAR     0x10000000     // ..\r
+\r
+/* Private functions (local, used only by routines in this module) */\r
+static decFloat *decDivide(decFloat *, const decFloat *,\r
+                              const decFloat *, decContext *, uInt);\r
+static decFloat *decCanonical(decFloat *, const decFloat *);\r
+static void      decFiniteMultiply(bcdnum *, uByte *, const decFloat *,\r
+                              const decFloat *);\r
+static decFloat *decInfinity(decFloat *, const decFloat *);\r
+static decFloat *decInvalid(decFloat *, decContext *);\r
+static decFloat *decNaNs(decFloat *, const decFloat *, const decFloat *,\r
+                              decContext *);\r
+static Int       decNumCompare(const decFloat *, const decFloat *, Flag);\r
+static decFloat *decToIntegral(decFloat *, const decFloat *, decContext *,\r
+                              enum rounding, Flag);\r
+static uInt      decToInt32(const decFloat *, decContext *, enum rounding,\r
+                              Flag, Flag);\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decCanonical -- copy a decFloat, making canonical                  */\r
+/*                                                                    */\r
+/*   result gets the canonicalized df                                 */\r
+/*   df     is the decFloat to copy and make canonical                */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This is exposed via decFloatCanonical for Double and Quad only.    */\r
+/* This works on specials, too; no error or exception is possible.    */\r
+/* ------------------------------------------------------------------ */\r
+static decFloat * decCanonical(decFloat *result, const decFloat *df) {\r
+  uInt encode, precode, dpd;       // work\r
+  uInt inword, uoff, canon;        // ..\r
+  Int  n;                          // counter (down)\r
+  if (df!=result) *result=*df;     // effect copy if needed\r
+  if (DFISSPECIAL(result)) {\r
+    if (DFISINF(result)) return decInfinity(result, df); // clean Infinity\r
+    // is a NaN\r
+    DFWORD(result, 0)&=~ECONNANMASK;    // clear ECON except selector\r
+    if (DFISCCZERO(df)) return result;  // coefficient continuation is 0\r
+    // drop through to check payload\r
+    }\r
+  // return quickly if the coefficient continuation is canonical\r
+  { // declare block\r
+  #if DOUBLE\r
+    uInt sourhi=DFWORD(df, 0);\r
+    uInt sourlo=DFWORD(df, 1);\r
+    if (CANONDPDOFF(sourhi, 8)\r
+     && CANONDPDTWO(sourhi, sourlo, 30)\r
+     && CANONDPDOFF(sourlo, 20)\r
+     && CANONDPDOFF(sourlo, 10)\r
+     && CANONDPDOFF(sourlo, 0)) return result;\r
+  #elif QUAD\r
+    uInt sourhi=DFWORD(df, 0);\r
+    uInt sourmh=DFWORD(df, 1);\r
+    uInt sourml=DFWORD(df, 2);\r
+    uInt sourlo=DFWORD(df, 3);\r
+    if (CANONDPDOFF(sourhi, 4)\r
+     && CANONDPDTWO(sourhi, sourmh, 26)\r
+     && CANONDPDOFF(sourmh, 16)\r
+     && CANONDPDOFF(sourmh, 6)\r
+     && CANONDPDTWO(sourmh, sourml, 28)\r
+     && CANONDPDOFF(sourml, 18)\r
+     && CANONDPDOFF(sourml, 8)\r
+     && CANONDPDTWO(sourml, sourlo, 30)\r
+     && CANONDPDOFF(sourlo, 20)\r
+     && CANONDPDOFF(sourlo, 10)\r
+     && CANONDPDOFF(sourlo, 0)) return result;\r
+  #endif\r
+  } // block\r
+\r
+  // Loop to repair a non-canonical coefficent, as needed\r
+  inword=DECWORDS-1;               // current input word\r
+  uoff=0;                          // bit offset of declet\r
+  encode=DFWORD(result, inword);\r
+  for (n=DECLETS-1; n>=0; n--) {   // count down declets of 10 bits\r
+    dpd=encode>>uoff;\r
+    uoff+=10;\r
+    if (uoff>32) {                 // crossed uInt boundary\r
+      inword--;\r
+      encode=DFWORD(result, inword);\r
+      uoff-=32;\r
+      dpd|=encode<<(10-uoff);      // get pending bits\r
+      }\r
+    dpd&=0x3ff;                    // clear uninteresting bits\r
+    if (dpd<0x16e) continue;       // must be canonical\r
+    canon=BIN2DPD[DPD2BIN[dpd]];   // determine canonical declet\r
+    if (canon==dpd) continue;      // have canonical declet\r
+    // need to replace declet\r
+    if (uoff>=10) {                // all within current word\r
+      encode&=~(0x3ff<<(uoff-10)); // clear the 10 bits ready for replace\r
+      encode|=canon<<(uoff-10);    // insert the canonical form\r
+      DFWORD(result, inword)=encode;    // .. and save\r
+      continue;\r
+      }\r
+    // straddled words\r
+    precode=DFWORD(result, inword+1);   // get previous\r
+    precode&=0xffffffff>>(10-uoff);     // clear top bits\r
+    DFWORD(result, inword+1)=precode|(canon<<(32-(10-uoff)));\r
+    encode&=0xffffffff<<uoff;           // clear bottom bits\r
+    encode|=canon>>(10-uoff);           // insert canonical\r
+    DFWORD(result, inword)=encode;      // .. and save\r
+    } // n\r
+  return result;\r
+  } // decCanonical\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decDivide -- divide operations                                     */\r
+/*                                                                    */\r
+/*   result gets the result of dividing dfl by dfr:                   */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   op     is the operation selector                                 */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* op is one of DIVIDE, REMAINDER, DIVIDEINT, or REMNEAR.             */\r
+/* ------------------------------------------------------------------ */\r
+#define DIVCOUNT  0                // 1 to instrument subtractions counter\r
+#define DIVBASE   ((uInt)BILLION)  // the base used for divide\r
+#define DIVOPLEN  DECPMAX9         // operand length ('digits' base 10**9)\r
+#define DIVACCLEN (DIVOPLEN*3)     // accumulator length (ditto)\r
+static decFloat * decDivide(decFloat *result, const decFloat *dfl,\r
+                            const decFloat *dfr, decContext *set, uInt op) {\r
+  decFloat quotient;               // for remainders\r
+  bcdnum num;                      // for final conversion\r
+  uInt   acc[DIVACCLEN];           // coefficent in base-billion ..\r
+  uInt   div[DIVOPLEN];            // divisor in base-billion ..\r
+  uInt   quo[DIVOPLEN+1];          // quotient in base-billion ..\r
+  uByte  bcdacc[(DIVOPLEN+1)*9+2]; // for quotient in BCD, +1, +1\r
+  uInt   *msua, *msud, *msuq;      // -> msu of acc, div, and quo\r
+  Int    divunits, accunits;       // lengths\r
+  Int    quodigits;                // digits in quotient\r
+  uInt   *lsua, *lsuq;             // -> current acc and quo lsus\r
+  Int    length, multiplier;       // work\r
+  uInt   carry, sign;              // ..\r
+  uInt   *ua, *ud, *uq;            // ..\r
+  uByte  *ub;                      // ..\r
+  uInt   uiwork;                   // for macros\r
+  uInt   divtop;                   // top unit of div adjusted for estimating\r
+  #if DIVCOUNT\r
+  static uInt maxcount=0;          // worst-seen subtractions count\r
+  uInt   divcount=0;               // subtractions count [this divide]\r
+  #endif\r
+\r
+  // calculate sign\r
+  num.sign=(DFWORD(dfl, 0)^DFWORD(dfr, 0)) & DECFLOAT_Sign;\r
+\r
+  if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) { // either is special?\r
+    // NaNs are handled as usual\r
+    if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+    // one or two infinities\r
+    if (DFISINF(dfl)) {\r
+      if (DFISINF(dfr)) return decInvalid(result, set); // Two infinities bad\r
+      if (op&(REMAINDER|REMNEAR)) return decInvalid(result, set); // as is rem\r
+      // Infinity/x is infinite and quiet, even if x=0\r
+      DFWORD(result, 0)=num.sign;\r
+      return decInfinity(result, result);\r
+      }\r
+    // must be x/Infinity -- remainders are lhs\r
+    if (op&(REMAINDER|REMNEAR)) return decCanonical(result, dfl);\r
+    // divides: return zero with correct sign and exponent depending\r
+    // on op (Etiny for divide, 0 for divideInt)\r
+    decFloatZero(result);\r
+    if (op==DIVIDEINT) DFWORD(result, 0)|=num.sign; // add sign\r
+     else DFWORD(result, 0)=num.sign;        // zeros the exponent, too\r
+    return result;\r
+    }\r
+  // next, handle zero operands (x/0 and 0/x)\r
+  if (DFISZERO(dfr)) {                       // x/0\r
+    if (DFISZERO(dfl)) {                     // 0/0 is undefined\r
+      decFloatZero(result);\r
+      DFWORD(result, 0)=DECFLOAT_qNaN;\r
+      set->status|=DEC_Division_undefined;\r
+      return result;\r
+      }\r
+    if (op&(REMAINDER|REMNEAR)) return decInvalid(result, set); // bad rem\r
+    set->status|=DEC_Division_by_zero;\r
+    DFWORD(result, 0)=num.sign;\r
+    return decInfinity(result, result);      // x/0 -> signed Infinity\r
+    }\r
+  num.exponent=GETEXPUN(dfl)-GETEXPUN(dfr);  // ideal exponent\r
+  if (DFISZERO(dfl)) {                       // 0/x (x!=0)\r
+    // if divide, result is 0 with ideal exponent; divideInt has\r
+    // exponent=0, remainders give zero with lower exponent\r
+    if (op&DIVIDEINT) {\r
+      decFloatZero(result);\r
+      DFWORD(result, 0)|=num.sign;           // add sign\r
+      return result;\r
+      }\r
+    if (!(op&DIVIDE)) {                      // a remainder\r
+      // exponent is the minimum of the operands\r
+      num.exponent=MINI(GETEXPUN(dfl), GETEXPUN(dfr));\r
+      // if the result is zero the sign shall be sign of dfl\r
+      num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;\r
+      }\r
+    bcdacc[0]=0;\r
+    num.msd=bcdacc;                          // -> 0\r
+    num.lsd=bcdacc;                          // ..\r
+    return decFinalize(result, &num, set);   // [divide may clamp exponent]\r
+    } // 0/x\r
+  // [here, both operands are known to be finite and non-zero]\r
+\r
+  // extract the operand coefficents into 'units' which are\r
+  // base-billion; the lhs is high-aligned in acc and the msu of both\r
+  // acc and div is at the right-hand end of array (offset length-1);\r
+  // the quotient can need one more unit than the operands as digits\r
+  // in it are not necessarily aligned neatly; further, the quotient\r
+  // may not start accumulating until after the end of the initial\r
+  // operand in acc if that is small (e.g., 1) so the accumulator\r
+  // must have at least that number of units extra (at the ls end)\r
+  GETCOEFFBILL(dfl, acc+DIVACCLEN-DIVOPLEN);\r
+  GETCOEFFBILL(dfr, div);\r
+  // zero the low uInts of acc\r
+  acc[0]=0;\r
+  acc[1]=0;\r
+  acc[2]=0;\r
+  acc[3]=0;\r
+  #if DOUBLE\r
+    #if DIVOPLEN!=2\r
+      #error Unexpected Double DIVOPLEN\r
+    #endif\r
+  #elif QUAD\r
+  acc[4]=0;\r
+  acc[5]=0;\r
+  acc[6]=0;\r
+  acc[7]=0;\r
+    #if DIVOPLEN!=4\r
+      #error Unexpected Quad DIVOPLEN\r
+    #endif\r
+  #endif\r
+\r
+  // set msu and lsu pointers\r
+  msua=acc+DIVACCLEN-1;       // [leading zeros removed below]\r
+  msuq=quo+DIVOPLEN;\r
+  //[loop for div will terminate because operands are non-zero]\r
+  for (msud=div+DIVOPLEN-1; *msud==0;) msud--;\r
+  // the initial least-significant unit of acc is set so acc appears\r
+  // to have the same length as div.\r
+  // This moves one position towards the least possible for each\r
+  // iteration\r
+  divunits=(Int)(msud-div+1); // precalculate\r
+  lsua=msua-divunits+1;       // initial working lsu of acc\r
+  lsuq=msuq;                  // and of quo\r
+\r
+  // set up the estimator for the multiplier; this is the msu of div,\r
+  // plus two bits from the unit below (if any) rounded up by one if\r
+  // there are any non-zero bits or units below that [the extra two\r
+  // bits makes for a much better estimate when the top unit is small]\r
+  divtop=*msud<<2;\r
+  if (divunits>1) {\r
+    uInt *um=msud-1;\r
+    uInt d=*um;\r
+    if (d>=750000000) {divtop+=3; d-=750000000;}\r
+     else if (d>=500000000) {divtop+=2; d-=500000000;}\r
+     else if (d>=250000000) {divtop++; d-=250000000;}\r
+    if (d) divtop++;\r
+     else for (um--; um>=div; um--) if (*um) {\r
+      divtop++;\r
+      break;\r
+      }\r
+    } // >1 unit\r
+\r
+  #if DECTRACE\r
+  {Int i;\r
+  printf("----- div=");\r
+  for (i=divunits-1; i>=0; i--) printf("%09ld ", (LI)div[i]);\r
+  printf("\n");}\r
+  #endif\r
+\r
+  // now collect up to DECPMAX+1 digits in the quotient (this may\r
+  // need OPLEN+1 uInts if unaligned)\r
+  quodigits=0;                // no digits yet\r
+  for (;; lsua--) {           // outer loop -- each input position\r
+    #if DECCHECK\r
+    if (lsua<acc) {\r
+      printf("Acc underrun...\n");\r
+      break;\r
+      }\r
+    #endif\r
+    #if DECTRACE\r
+    printf("Outer: quodigits=%ld acc=", (LI)quodigits);\r
+    for (ua=msua; ua>=lsua; ua--) printf("%09ld ", (LI)*ua);\r
+    printf("\n");\r
+    #endif\r
+    *lsuq=0;                  // default unit result is 0\r
+    for (;;) {                // inner loop -- calculate quotient unit\r
+      // strip leading zero units from acc (either there initially or\r
+      // from subtraction below); this may strip all if exactly 0\r
+      for (; *msua==0 && msua>=lsua;) msua--;\r
+      accunits=(Int)(msua-lsua+1);                // [maybe 0]\r
+      // subtraction is only necessary and possible if there are as\r
+      // least as many units remaining in acc for this iteration as\r
+      // there are in div\r
+      if (accunits<divunits) {\r
+        if (accunits==0) msua++;                  // restore\r
+        break;\r
+        }\r
+\r
+      // If acc is longer than div then subtraction is definitely\r
+      // possible (as msu of both is non-zero), but if they are the\r
+      // same length a comparison is needed.\r
+      // If a subtraction is needed then a good estimate of the\r
+      // multiplier for the subtraction is also needed in order to\r
+      // minimise the iterations of this inner loop because the\r
+      // subtractions needed dominate division performance.\r
+      if (accunits==divunits) {\r
+        // compare the high divunits of acc and div:\r
+        // acc<div:  this quotient unit is unchanged; subtraction\r
+        //           will be possible on the next iteration\r
+        // acc==div: quotient gains 1, set acc=0\r
+        // acc>div:  subtraction necessary at this position\r
+        for (ud=msud, ua=msua; ud>div; ud--, ua--) if (*ud!=*ua) break;\r
+        // [now at first mismatch or lsu]\r
+        if (*ud>*ua) break;                       // next time...\r
+        if (*ud==*ua) {                           // all compared equal\r
+          *lsuq+=1;                               // increment result\r
+          msua=lsua;                              // collapse acc units\r
+          *msua=0;                                // .. to a zero\r
+          break;\r
+          }\r
+\r
+        // subtraction necessary; estimate multiplier [see above]\r
+        // if both *msud and *msua are small it is cost-effective to\r
+        // bring in part of the following units (if any) to get a\r
+        // better estimate (assume some other non-zero in div)\r
+        #define DIVLO 1000000U\r
+        #define DIVHI (DIVBASE/DIVLO)\r
+        #if DECUSE64\r
+          if (divunits>1) {\r
+            // there cannot be a *(msud-2) for DECDOUBLE so next is\r
+            // an exact calculation unless DECQUAD (which needs to\r
+            // assume bits out there if divunits>2)\r
+            uLong mul=(uLong)*msua * DIVBASE + *(msua-1);\r
+            uLong div=(uLong)*msud * DIVBASE + *(msud-1);\r
+            #if QUAD\r
+            if (divunits>2) div++;\r
+            #endif\r
+            mul/=div;\r
+            multiplier=(Int)mul;\r
+            }\r
+           else multiplier=*msua/(*msud);\r
+        #else\r
+          if (divunits>1 && *msua<DIVLO && *msud<DIVLO) {\r
+            multiplier=(*msua*DIVHI + *(msua-1)/DIVLO)\r
+                      /(*msud*DIVHI + *(msud-1)/DIVLO +1);\r
+            }\r
+           else multiplier=(*msua<<2)/divtop;\r
+        #endif\r
+        }\r
+       else {                                     // accunits>divunits\r
+        // msud is one unit 'lower' than msua, so estimate differently\r
+        #if DECUSE64\r
+          uLong mul;\r
+          // as before, bring in extra digits if possible\r
+          if (divunits>1 && *msua<DIVLO && *msud<DIVLO) {\r
+            mul=((uLong)*msua * DIVHI * DIVBASE) + *(msua-1) * DIVHI\r
+               + *(msua-2)/DIVLO;\r
+            mul/=(*msud*DIVHI + *(msud-1)/DIVLO +1);\r
+            }\r
+           else if (divunits==1) {\r
+            mul=(uLong)*msua * DIVBASE + *(msua-1);\r
+            mul/=*msud;       // no more to the right\r
+            }\r
+           else {\r
+            mul=(uLong)(*msua) * (uInt)(DIVBASE<<2)\r
+                + (*(msua-1)<<2);\r
+            mul/=divtop;      // [divtop already allows for sticky bits]\r
+            }\r
+          multiplier=(Int)mul;\r
+        #else\r
+          multiplier=*msua * ((DIVBASE<<2)/divtop);\r
+        #endif\r
+        }\r
+      if (multiplier==0) multiplier=1;            // marginal case\r
+      *lsuq+=multiplier;\r
+\r
+      #if DIVCOUNT\r
+      // printf("Multiplier: %ld\n", (LI)multiplier);\r
+      divcount++;\r
+      #endif\r
+\r
+      // Carry out the subtraction  acc-(div*multiplier); for each\r
+      // unit in div, do the multiply, split to units (see\r
+      // decFloatMultiply for the algorithm), and subtract from acc\r
+      #define DIVMAGIC  2305843009U               // 2**61/10**9\r
+      #define DIVSHIFTA 29\r
+      #define DIVSHIFTB 32\r
+      carry=0;\r
+      for (ud=div, ua=lsua; ud<=msud; ud++, ua++) {\r
+        uInt lo, hop;\r
+        #if DECUSE64\r
+          uLong sub=(uLong)multiplier*(*ud)+carry;\r
+          if (sub<DIVBASE) {\r
+            carry=0;\r
+            lo=(uInt)sub;\r
+            }\r
+           else {\r
+            hop=(uInt)(sub>>DIVSHIFTA);\r
+            carry=(uInt)(((uLong)hop*DIVMAGIC)>>DIVSHIFTB);\r
+            // the estimate is now in hi; now calculate sub-hi*10**9\r
+            // to get the remainder (which will be <DIVBASE))\r
+            lo=(uInt)sub;\r
+            lo-=carry*DIVBASE;                    // low word of result\r
+            if (lo>=DIVBASE) {\r
+              lo-=DIVBASE;                        // correct by +1\r
+              carry++;\r
+              }\r
+            }\r
+        #else // 32-bit\r
+          uInt hi;\r
+          // calculate multiplier*(*ud) into hi and lo\r
+          LONGMUL32HI(hi, *ud, multiplier);       // get the high word\r
+          lo=multiplier*(*ud);                    // .. and the low\r
+          lo+=carry;                              // add the old hi\r
+          carry=hi+(lo<carry);                    // .. with any carry\r
+          if (carry || lo>=DIVBASE) {             // split is needed\r
+            hop=(carry<<3)+(lo>>DIVSHIFTA);       // hi:lo/2**29\r
+            LONGMUL32HI(carry, hop, DIVMAGIC);    // only need the high word\r
+            // [DIVSHIFTB is 32, so carry can be used directly]\r
+            // the estimate is now in carry; now calculate hi:lo-est*10**9;\r
+            // happily the top word of the result is irrelevant because it\r
+            // will always be zero so this needs only one multiplication\r
+            lo-=(carry*DIVBASE);\r
+            // the correction here will be at most +1; do it\r
+            if (lo>=DIVBASE) {\r
+              lo-=DIVBASE;\r
+              carry++;\r
+              }\r
+            }\r
+        #endif\r
+        if (lo>*ua) {              // borrow needed\r
+          *ua+=DIVBASE;\r
+          carry++;\r
+          }\r
+        *ua-=lo;\r
+        } // ud loop\r
+      if (carry) *ua-=carry;       // accdigits>divdigits [cannot borrow]\r
+      } // inner loop\r
+\r
+    // the outer loop terminates when there is either an exact result\r
+    // or enough digits; first update the quotient digit count and\r
+    // pointer (if any significant digits)\r
+    #if DECTRACE\r
+    if (*lsuq || quodigits) printf("*lsuq=%09ld\n", (LI)*lsuq);\r
+    #endif\r
+    if (quodigits) {\r
+      quodigits+=9;                // had leading unit earlier\r
+      lsuq--;\r
+      if (quodigits>DECPMAX+1) break;   // have enough\r
+      }\r
+     else if (*lsuq) {             // first quotient digits\r
+      const uInt *pow;\r
+      for (pow=DECPOWERS; *lsuq>=*pow; pow++) quodigits++;\r
+      lsuq--;\r
+      // [cannot have >DECPMAX+1 on first unit]\r
+      }\r
+\r
+    if (*msua!=0) continue;        // not an exact result\r
+    // acc is zero iff used all of original units and zero down to lsua\r
+    // (must also continue to original lsu for correct quotient length)\r
+    if (lsua>acc+DIVACCLEN-DIVOPLEN) continue;\r
+    for (; msua>lsua && *msua==0;) msua--;\r
+    if (*msua==0 && msua==lsua) break;\r
+    } // outer loop\r
+\r
+  // all of the original operand in acc has been covered at this point\r
+  // quotient now has at least DECPMAX+2 digits\r
+  // *msua is now non-0 if inexact and sticky bits\r
+  // lsuq is one below the last uint of the quotient\r
+  lsuq++;                          // set -> true lsu of quo\r
+  if (*msua) *lsuq|=1;             // apply sticky bit\r
+\r
+  // quo now holds the (unrounded) quotient in base-billion; one\r
+  // base-billion 'digit' per uInt.\r
+  #if DECTRACE\r
+  printf("DivQuo:");\r
+  for (uq=msuq; uq>=lsuq; uq--) printf(" %09ld", (LI)*uq);\r
+  printf("\n");\r
+  #endif\r
+\r
+  // Now convert to BCD for rounding and cleanup, starting from the\r
+  // most significant end [offset by one into bcdacc to leave room\r
+  // for a possible carry digit if rounding for REMNEAR is needed]\r
+  for (uq=msuq, ub=bcdacc+1; uq>=lsuq; uq--, ub+=9) {\r
+    uInt top, mid, rem;                 // work\r
+    if (*uq==0) {                       // no split needed\r
+      UBFROMUI(ub, 0);                  // clear 9 BCD8s\r
+      UBFROMUI(ub+4, 0);                // ..\r
+      *(ub+8)=0;                        // ..\r
+      continue;\r
+      }\r
+    // *uq is non-zero -- split the base-billion digit into\r
+    // hi, mid, and low three-digits\r
+    #define divsplit9 1000000           // divisor\r
+    #define divsplit6 1000              // divisor\r
+    // The splitting is done by simple divides and remainders,\r
+    // assuming the compiler will optimize these [GCC does]\r
+    top=*uq/divsplit9;\r
+    rem=*uq%divsplit9;\r
+    mid=rem/divsplit6;\r
+    rem=rem%divsplit6;\r
+    // lay out the nine BCD digits (plus one unwanted byte)\r
+    UBFROMUI(ub,   UBTOUI(&BIN2BCD8[top*4]));\r
+    UBFROMUI(ub+3, UBTOUI(&BIN2BCD8[mid*4]));\r
+    UBFROMUI(ub+6, UBTOUI(&BIN2BCD8[rem*4]));\r
+    } // BCD conversion loop\r
+  ub--;                                 // -> lsu\r
+\r
+  // complete the bcdnum; quodigits is correct, so the position of\r
+  // the first non-zero is known\r
+  num.msd=bcdacc+1+(msuq-lsuq+1)*9-quodigits;\r
+  num.lsd=ub;\r
+\r
+  // make exponent adjustments, etc\r
+  if (lsua<acc+DIVACCLEN-DIVOPLEN) {    // used extra digits\r
+    num.exponent-=(Int)((acc+DIVACCLEN-DIVOPLEN-lsua)*9);\r
+    // if the result was exact then there may be up to 8 extra\r
+    // trailing zeros in the overflowed quotient final unit\r
+    if (*msua==0) {\r
+      for (; *ub==0;) ub--;             // drop zeros\r
+      num.exponent+=(Int)(num.lsd-ub);  // and adjust exponent\r
+      num.lsd=ub;\r
+      }\r
+    } // adjustment needed\r
+\r
+  #if DIVCOUNT\r
+  if (divcount>maxcount) {              // new high-water nark\r
+    maxcount=divcount;\r
+    printf("DivNewMaxCount: %ld\n", (LI)maxcount);\r
+    }\r
+  #endif\r
+\r
+  if (op&DIVIDE) return decFinalize(result, &num, set); // all done\r
+\r
+  // Is DIVIDEINT or a remainder; there is more to do -- first form\r
+  // the integer (this is done 'after the fact', unlike as in\r
+  // decNumber, so as not to tax DIVIDE)\r
+\r
+  // The first non-zero digit will be in the first 9 digits, known\r
+  // from quodigits and num.msd, so there is always space for DECPMAX\r
+  // digits\r
+\r
+  length=(Int)(num.lsd-num.msd+1);\r
+  //printf("Length exp: %ld %ld\n", (LI)length, (LI)num.exponent);\r
+\r
+  if (length+num.exponent>DECPMAX) { // cannot fit\r
+    decFloatZero(result);\r
+    DFWORD(result, 0)=DECFLOAT_qNaN;\r
+    set->status|=DEC_Division_impossible;\r
+    return result;\r
+    }\r
+\r
+  if (num.exponent>=0) {           // already an int, or need pad zeros\r
+    for (ub=num.lsd+1; ub<=num.lsd+num.exponent; ub++) *ub=0;\r
+    num.lsd+=num.exponent;\r
+    }\r
+   else {                          // too long: round or truncate needed\r
+    Int drop=-num.exponent;\r
+    if (!(op&REMNEAR)) {           // simple truncate\r
+      num.lsd-=drop;\r
+      if (num.lsd<num.msd) {       // truncated all\r
+        num.lsd=num.msd;           // make 0\r
+        *num.lsd=0;                // .. [sign still relevant]\r
+        }\r
+      }\r
+     else {                        // round to nearest even [sigh]\r
+      // round-to-nearest, in-place; msd is at or to right of bcdacc+1\r
+      // (this is a special case of Quantize -- q.v. for commentary)\r
+      uByte *roundat;              // -> re-round digit\r
+      uByte reround;               // reround value\r
+      *(num.msd-1)=0;              // in case of left carry, or make 0\r
+      if (drop<length) roundat=num.lsd-drop+1;\r
+       else if (drop==length) roundat=num.msd;\r
+       else roundat=num.msd-1;     // [-> 0]\r
+      reround=*roundat;\r
+      for (ub=roundat+1; ub<=num.lsd; ub++) {\r
+        if (*ub!=0) {\r
+          reround=DECSTICKYTAB[reround];\r
+          break;\r
+          }\r
+        } // check stickies\r
+      if (roundat>num.msd) num.lsd=roundat-1;\r
+       else {\r
+        num.msd--;                           // use the 0 ..\r
+        num.lsd=num.msd;                     // .. at the new MSD place\r
+        }\r
+      if (reround!=0) {                      // discarding non-zero\r
+        uInt bump=0;\r
+        // rounding is DEC_ROUND_HALF_EVEN always\r
+        if (reround>5) bump=1;               // >0.5 goes up\r
+         else if (reround==5)                // exactly 0.5000 ..\r
+          bump=*(num.lsd) & 0x01;            // .. up iff [new] lsd is odd\r
+        if (bump!=0) {                       // need increment\r
+          // increment the coefficient; this might end up with 1000...\r
+          ub=num.lsd;\r
+          for (; UBTOUI(ub-3)==0x09090909; ub-=4) UBFROMUI(ub-3, 0);\r
+          for (; *ub==9; ub--) *ub=0;        // at most 3 more\r
+          *ub+=1;\r
+          if (ub<num.msd) num.msd--;         // carried\r
+          } // bump needed\r
+        } // reround!=0\r
+      } // remnear\r
+    } // round or truncate needed\r
+  num.exponent=0;                            // all paths\r
+  //decShowNum(&num, "int");\r
+\r
+  if (op&DIVIDEINT) return decFinalize(result, &num, set); // all done\r
+\r
+  // Have a remainder to calculate\r
+  decFinalize(&quotient, &num, set);         // lay out the integer so far\r
+  DFWORD(&quotient, 0)^=DECFLOAT_Sign;       // negate it\r
+  sign=DFWORD(dfl, 0);                       // save sign of dfl\r
+  decFloatFMA(result, &quotient, dfr, dfl, set);\r
+  if (!DFISZERO(result)) return result;\r
+  // if the result is zero the sign shall be sign of dfl\r
+  DFWORD(&quotient, 0)=sign;                 // construct decFloat of sign\r
+  return decFloatCopySign(result, result, &quotient);\r
+  } // decDivide\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFiniteMultiply -- multiply two finite decFloats                 */\r
+/*                                                                    */\r
+/*   num    gets the result of multiplying dfl and dfr                */\r
+/*   bcdacc .. with the coefficient in this array                     */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*                                                                    */\r
+/* This effects the multiplication of two decFloats, both known to be */\r
+/* finite, leaving the result in a bcdnum ready for decFinalize (for  */\r
+/* use in Multiply) or in a following addition (FMA).                 */\r
+/*                                                                    */\r
+/* bcdacc must have space for at least DECPMAX9*18+1 bytes.           */\r
+/* No error is possible and no status is set.                         */\r
+/* ------------------------------------------------------------------ */\r
+// This routine has two separate implementations of the core\r
+// multiplication; both using base-billion.  One uses only 32-bit\r
+// variables (Ints and uInts) or smaller; the other uses uLongs (for\r
+// multiplication and addition only).  Both implementations cover\r
+// both arithmetic sizes (DOUBLE and QUAD) in order to allow timing\r
+// comparisons.  In any one compilation only one implementation for\r
+// each size can be used, and if DECUSE64 is 0 then use of the 32-bit\r
+// version is forced.\r
+//\r
+// Historical note: an earlier version of this code also supported the\r
+// 256-bit format and has been preserved.  That is somewhat trickier\r
+// during lazy carry splitting because the initial quotient estimate\r
+// (est) can exceed 32 bits.\r
+\r
+#define MULTBASE  ((uInt)BILLION)  // the base used for multiply\r
+#define MULOPLEN  DECPMAX9         // operand length ('digits' base 10**9)\r
+#define MULACCLEN (MULOPLEN*2)              // accumulator length (ditto)\r
+#define LEADZEROS (MULACCLEN*9 - DECPMAX*2) // leading zeros always\r
+\r
+// Assertions: exponent not too large and MULACCLEN is a multiple of 4\r
+#if DECEMAXD>9\r
+  #error Exponent may overflow when doubled for Multiply\r
+#endif\r
+#if MULACCLEN!=(MULACCLEN/4)*4\r
+  // This assumption is used below only for initialization\r
+  #error MULACCLEN is not a multiple of 4\r
+#endif\r
+\r
+static void decFiniteMultiply(bcdnum *num, uByte *bcdacc,\r
+                              const decFloat *dfl, const decFloat *dfr) {\r
+  uInt   bufl[MULOPLEN];           // left  coefficient (base-billion)\r
+  uInt   bufr[MULOPLEN];           // right coefficient (base-billion)\r
+  uInt   *ui, *uj;                 // work\r
+  uByte  *ub;                      // ..\r
+  uInt   uiwork;                   // for macros\r
+\r
+  #if DECUSE64\r
+  uLong  accl[MULACCLEN];          // lazy accumulator (base-billion+)\r
+  uLong  *pl;                      // work -> lazy accumulator\r
+  uInt   acc[MULACCLEN];           // coefficent in base-billion ..\r
+  #else\r
+  uInt   acc[MULACCLEN*2];         // accumulator in base-billion ..\r
+  #endif\r
+  uInt   *pa;                      // work -> accumulator\r
+  //printf("Base10**9: OpLen=%d MulAcclen=%d\n", OPLEN, MULACCLEN);\r
+\r
+  /* Calculate sign and exponent */\r
+  num->sign=(DFWORD(dfl, 0)^DFWORD(dfr, 0)) & DECFLOAT_Sign;\r
+  num->exponent=GETEXPUN(dfl)+GETEXPUN(dfr); // [see assertion above]\r
+\r
+  /* Extract the coefficients and prepare the accumulator */\r
+  // the coefficients of the operands are decoded into base-billion\r
+  // numbers in uInt arrays (bufl and bufr, LSD at offset 0) of the\r
+  // appropriate size.\r
+  GETCOEFFBILL(dfl, bufl);\r
+  GETCOEFFBILL(dfr, bufr);\r
+  #if DECTRACE && 0\r
+    printf("CoeffbL:");\r
+    for (ui=bufl+MULOPLEN-1; ui>=bufl; ui--) printf(" %08lx", (LI)*ui);\r
+    printf("\n");\r
+    printf("CoeffbR:");\r
+    for (uj=bufr+MULOPLEN-1; uj>=bufr; uj--) printf(" %08lx", (LI)*uj);\r
+    printf("\n");\r
+  #endif\r
+\r
+  // start the 64-bit/32-bit differing paths...\r
+#if DECUSE64\r
+\r
+  // zero the accumulator\r
+  #if MULACCLEN==4\r
+    accl[0]=0; accl[1]=0; accl[2]=0; accl[3]=0;\r
+  #else                                      // use a loop\r
+    // MULACCLEN is a multiple of four, asserted above\r
+    for (pl=accl; pl<accl+MULACCLEN; pl+=4) {\r
+      *pl=0; *(pl+1)=0; *(pl+2)=0; *(pl+3)=0;// [reduce overhead]\r
+      } // pl\r
+  #endif\r
+\r
+  /* Effect the multiplication */\r
+  // The multiplcation proceeds using MFC's lazy-carry resolution\r
+  // algorithm from decNumber.  First, the multiplication is\r
+  // effected, allowing accumulation of the partial products (which\r
+  // are in base-billion at each column position) into 64 bits\r
+  // without resolving back to base=billion after each addition.\r
+  // These 64-bit numbers (which may contain up to 19 decimal digits)\r
+  // are then split using the Clark & Cowlishaw algorithm (see below).\r
+  // [Testing for 0 in the inner loop is not really a 'win']\r
+  for (ui=bufr; ui<bufr+MULOPLEN; ui++) { // over each item in rhs\r
+    if (*ui==0) continue;                 // product cannot affect result\r
+    pl=accl+(ui-bufr);                    // where to add the lhs\r
+    for (uj=bufl; uj<bufl+MULOPLEN; uj++, pl++) { // over each item in lhs\r
+      // if (*uj==0) continue;            // product cannot affect result\r
+      *pl+=((uLong)*ui)*(*uj);\r
+      } // uj\r
+    } // ui\r
+\r
+  // The 64-bit carries must now be resolved; this means that a\r
+  // quotient/remainder has to be calculated for base-billion (1E+9).\r
+  // For this, Clark & Cowlishaw's quotient estimation approach (also\r
+  // used in decNumber) is needed, because 64-bit divide is generally\r
+  // extremely slow on 32-bit machines, and may be slower than this\r
+  // approach even on 64-bit machines.  This algorithm splits X\r
+  // using:\r
+  //\r
+  //   magic=2**(A+B)/1E+9;   // 'magic number'\r
+  //   hop=X/2**A;            // high order part of X (by shift)\r
+  //   est=magic*hop/2**B     // quotient estimate (may be low by 1)\r
+  //\r
+  // A and B are quite constrained; hop and magic must fit in 32 bits,\r
+  // and 2**(A+B) must be as large as possible (which is 2**61 if\r
+  // magic is to fit).  Further, maxX increases with the length of\r
+  // the operands (and hence the number of partial products\r
+  // accumulated); maxX is OPLEN*(10**18), which is up to 19 digits.\r
+  //\r
+  // It can be shown that when OPLEN is 2 then the maximum error in\r
+  // the estimated quotient is <1, but for larger maximum x the\r
+  // maximum error is above 1 so a correction that is >1 may be\r
+  // needed.  Values of A and B are chosen to satisfy the constraints\r
+  // just mentioned while minimizing the maximum error (and hence the\r
+  // maximum correction), as shown in the following table:\r
+  //\r
+  //   Type    OPLEN   A   B     maxX    maxError  maxCorrection\r
+  //   ---------------------------------------------------------\r
+  //   DOUBLE    2    29  32  <2*10**18    0.63       1\r
+  //   QUAD      4    30  31  <4*10**18    1.17       2\r
+  //\r
+  // In the OPLEN==2 case there is most choice, but the value for B\r
+  // of 32 has a big advantage as then the calculation of the\r
+  // estimate requires no shifting; the compiler can extract the high\r
+  // word directly after multiplying magic*hop.\r
+  #define MULMAGIC 2305843009U          // 2**61/10**9  [both cases]\r
+  #if DOUBLE\r
+    #define MULSHIFTA 29\r
+    #define MULSHIFTB 32\r
+  #elif QUAD\r
+    #define MULSHIFTA 30\r
+    #define MULSHIFTB 31\r
+  #else\r
+    #error Unexpected type\r
+  #endif\r
+\r
+  #if DECTRACE\r
+  printf("MulAccl:");\r
+  for (pl=accl+MULACCLEN-1; pl>=accl; pl--)\r
+    printf(" %08lx:%08lx", (LI)(*pl>>32), (LI)(*pl&0xffffffff));\r
+  printf("\n");\r
+  #endif\r
+\r
+  for (pl=accl, pa=acc; pl<accl+MULACCLEN; pl++, pa++) { // each column position\r
+    uInt lo, hop;                       // work\r
+    uInt est;                           // cannot exceed 4E+9\r
+    if (*pl>=MULTBASE) {\r
+      // *pl holds a binary number which needs to be split\r
+      hop=(uInt)(*pl>>MULSHIFTA);\r
+      est=(uInt)(((uLong)hop*MULMAGIC)>>MULSHIFTB);\r
+      // the estimate is now in est; now calculate hi:lo-est*10**9;\r
+      // happily the top word of the result is irrelevant because it\r
+      // will always be zero so this needs only one multiplication\r
+      lo=(uInt)(*pl-((uLong)est*MULTBASE));  // low word of result\r
+      // If QUAD, the correction here could be +2\r
+      if (lo>=MULTBASE) {\r
+        lo-=MULTBASE;                   // correct by +1\r
+        est++;\r
+        #if QUAD\r
+        // may need to correct by +2\r
+        if (lo>=MULTBASE) {\r
+          lo-=MULTBASE;\r
+          est++;\r
+          }\r
+        #endif\r
+        }\r
+      // finally place lo as the new coefficient 'digit' and add est to\r
+      // the next place up [this is safe because this path is never\r
+      // taken on the final iteration as *pl will fit]\r
+      *pa=lo;\r
+      *(pl+1)+=est;\r
+      } // *pl needed split\r
+     else {                             // *pl<MULTBASE\r
+      *pa=(uInt)*pl;                    // just copy across\r
+      }\r
+    } // pl loop\r
+\r
+#else  // 32-bit\r
+  for (pa=acc;; pa+=4) {                     // zero the accumulator\r
+    *pa=0; *(pa+1)=0; *(pa+2)=0; *(pa+3)=0;  // [reduce overhead]\r
+    if (pa==acc+MULACCLEN*2-4) break;        // multiple of 4 asserted\r
+    } // pa\r
+\r
+  /* Effect the multiplication */\r
+  // uLongs are not available (and in particular, there is no uLong\r
+  // divide) but it is still possible to use MFC's lazy-carry\r
+  // resolution algorithm from decNumber.  First, the multiplication\r
+  // is effected, allowing accumulation of the partial products\r
+  // (which are in base-billion at each column position) into 64 bits\r
+  // [with the high-order 32 bits in each position being held at\r
+  // offset +ACCLEN from the low-order 32 bits in the accumulator].\r
+  // These 64-bit numbers (which may contain up to 19 decimal digits)\r
+  // are then split using the Clark & Cowlishaw algorithm (see\r
+  // below).\r
+  for (ui=bufr;; ui++) {                // over each item in rhs\r
+    uInt hi, lo;                        // words of exact multiply result\r
+    pa=acc+(ui-bufr);                   // where to add the lhs\r
+    for (uj=bufl;; uj++, pa++) {        // over each item in lhs\r
+      LONGMUL32HI(hi, *ui, *uj);        // calculate product of digits\r
+      lo=(*ui)*(*uj);                   // ..\r
+      *pa+=lo;                          // accumulate low bits and ..\r
+      *(pa+MULACCLEN)+=hi+(*pa<lo);     // .. high bits with any carry\r
+      if (uj==bufl+MULOPLEN-1) break;\r
+      }\r
+    if (ui==bufr+MULOPLEN-1) break;\r
+    }\r
+\r
+  // The 64-bit carries must now be resolved; this means that a\r
+  // quotient/remainder has to be calculated for base-billion (1E+9).\r
+  // For this, Clark & Cowlishaw's quotient estimation approach (also\r
+  // used in decNumber) is needed, because 64-bit divide is generally\r
+  // extremely slow on 32-bit machines.  This algorithm splits X\r
+  // using:\r
+  //\r
+  //   magic=2**(A+B)/1E+9;   // 'magic number'\r
+  //   hop=X/2**A;            // high order part of X (by shift)\r
+  //   est=magic*hop/2**B     // quotient estimate (may be low by 1)\r
+  //\r
+  // A and B are quite constrained; hop and magic must fit in 32 bits,\r
+  // and 2**(A+B) must be as large as possible (which is 2**61 if\r
+  // magic is to fit).  Further, maxX increases with the length of\r
+  // the operands (and hence the number of partial products\r
+  // accumulated); maxX is OPLEN*(10**18), which is up to 19 digits.\r
+  //\r
+  // It can be shown that when OPLEN is 2 then the maximum error in\r
+  // the estimated quotient is <1, but for larger maximum x the\r
+  // maximum error is above 1 so a correction that is >1 may be\r
+  // needed.  Values of A and B are chosen to satisfy the constraints\r
+  // just mentioned while minimizing the maximum error (and hence the\r
+  // maximum correction), as shown in the following table:\r
+  //\r
+  //   Type    OPLEN   A   B     maxX    maxError  maxCorrection\r
+  //   ---------------------------------------------------------\r
+  //   DOUBLE    2    29  32  <2*10**18    0.63       1\r
+  //   QUAD      4    30  31  <4*10**18    1.17       2\r
+  //\r
+  // In the OPLEN==2 case there is most choice, but the value for B\r
+  // of 32 has a big advantage as then the calculation of the\r
+  // estimate requires no shifting; the high word is simply\r
+  // calculated from multiplying magic*hop.\r
+  #define MULMAGIC 2305843009U          // 2**61/10**9  [both cases]\r
+  #if DOUBLE\r
+    #define MULSHIFTA 29\r
+    #define MULSHIFTB 32\r
+  #elif QUAD\r
+    #define MULSHIFTA 30\r
+    #define MULSHIFTB 31\r
+  #else\r
+    #error Unexpected type\r
+  #endif\r
+\r
+  #if DECTRACE\r
+  printf("MulHiLo:");\r
+  for (pa=acc+MULACCLEN-1; pa>=acc; pa--)\r
+    printf(" %08lx:%08lx", (LI)*(pa+MULACCLEN), (LI)*pa);\r
+  printf("\n");\r
+  #endif\r
+\r
+  for (pa=acc;; pa++) {                 // each low uInt\r
+    uInt hi, lo;                        // words of exact multiply result\r
+    uInt hop, estlo;                    // work\r
+    #if QUAD\r
+    uInt esthi;                         // ..\r
+    #endif\r
+\r
+    lo=*pa;\r
+    hi=*(pa+MULACCLEN);                 // top 32 bits\r
+    // hi and lo now hold a binary number which needs to be split\r
+\r
+    #if DOUBLE\r
+      hop=(hi<<3)+(lo>>MULSHIFTA);      // hi:lo/2**29\r
+      LONGMUL32HI(estlo, hop, MULMAGIC);// only need the high word\r
+      // [MULSHIFTB is 32, so estlo can be used directly]\r
+      // the estimate is now in estlo; now calculate hi:lo-est*10**9;\r
+      // happily the top word of the result is irrelevant because it\r
+      // will always be zero so this needs only one multiplication\r
+      lo-=(estlo*MULTBASE);\r
+      // esthi=0;                       // high word is ignored below\r
+      // the correction here will be at most +1; do it\r
+      if (lo>=MULTBASE) {\r
+        lo-=MULTBASE;\r
+        estlo++;\r
+        }\r
+    #elif QUAD\r
+      hop=(hi<<2)+(lo>>MULSHIFTA);      // hi:lo/2**30\r
+      LONGMUL32HI(esthi, hop, MULMAGIC);// shift will be 31 ..\r
+      estlo=hop*MULMAGIC;               // .. so low word needed\r
+      estlo=(esthi<<1)+(estlo>>MULSHIFTB); // [just the top bit]\r
+      // esthi=0;                       // high word is ignored below\r
+      lo-=(estlo*MULTBASE);             // as above\r
+      // the correction here could be +1 or +2\r
+      if (lo>=MULTBASE) {\r
+        lo-=MULTBASE;\r
+        estlo++;\r
+        }\r
+      if (lo>=MULTBASE) {\r
+        lo-=MULTBASE;\r
+        estlo++;\r
+        }\r
+    #else\r
+      #error Unexpected type\r
+    #endif\r
+\r
+    // finally place lo as the new accumulator digit and add est to\r
+    // the next place up; this latter add could cause a carry of 1\r
+    // to the high word of the next place\r
+    *pa=lo;\r
+    *(pa+1)+=estlo;\r
+    // esthi is always 0 for DOUBLE and QUAD so this is skipped\r
+    // *(pa+1+MULACCLEN)+=esthi;\r
+    if (*(pa+1)<estlo) *(pa+1+MULACCLEN)+=1; // carry\r
+    if (pa==acc+MULACCLEN-2) break;          // [MULACCLEN-1 will never need split]\r
+    } // pa loop\r
+#endif\r
+\r
+  // At this point, whether using the 64-bit or the 32-bit paths, the\r
+  // accumulator now holds the (unrounded) result in base-billion;\r
+  // one base-billion 'digit' per uInt.\r
+  #if DECTRACE\r
+  printf("MultAcc:");\r
+  for (pa=acc+MULACCLEN-1; pa>=acc; pa--) printf(" %09ld", (LI)*pa);\r
+  printf("\n");\r
+  #endif\r
+\r
+  // Now convert to BCD for rounding and cleanup, starting from the\r
+  // most significant end\r
+  pa=acc+MULACCLEN-1;\r
+  if (*pa!=0) num->msd=bcdacc+LEADZEROS;// drop known lead zeros\r
+   else {                               // >=1 word of leading zeros\r
+    num->msd=bcdacc;                    // known leading zeros are gone\r
+    pa--;                               // skip first word ..\r
+    for (; *pa==0; pa--) if (pa==acc) break; // .. and any more leading 0s\r
+    }\r
+  for (ub=bcdacc;; pa--, ub+=9) {\r
+    if (*pa!=0) {                       // split(s) needed\r
+      uInt top, mid, rem;               // work\r
+      // *pa is non-zero -- split the base-billion acc digit into\r
+      // hi, mid, and low three-digits\r
+      #define mulsplit9 1000000         // divisor\r
+      #define mulsplit6 1000            // divisor\r
+      // The splitting is done by simple divides and remainders,\r
+      // assuming the compiler will optimize these where useful\r
+      // [GCC does]\r
+      top=*pa/mulsplit9;\r
+      rem=*pa%mulsplit9;\r
+      mid=rem/mulsplit6;\r
+      rem=rem%mulsplit6;\r
+      // lay out the nine BCD digits (plus one unwanted byte)\r
+      UBFROMUI(ub,   UBTOUI(&BIN2BCD8[top*4]));\r
+      UBFROMUI(ub+3, UBTOUI(&BIN2BCD8[mid*4]));\r
+      UBFROMUI(ub+6, UBTOUI(&BIN2BCD8[rem*4]));\r
+      }\r
+     else {                             // *pa==0\r
+      UBFROMUI(ub, 0);                  // clear 9 BCD8s\r
+      UBFROMUI(ub+4, 0);                // ..\r
+      *(ub+8)=0;                        // ..\r
+      }\r
+    if (pa==acc) break;\r
+    } // BCD conversion loop\r
+\r
+  num->lsd=ub+8;                        // complete the bcdnum ..\r
+\r
+  #if DECTRACE\r
+  decShowNum(num, "postmult");\r
+  decFloatShow(dfl, "dfl");\r
+  decFloatShow(dfr, "dfr");\r
+  #endif\r
+  return;\r
+  } // decFiniteMultiply\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatAbs -- absolute value, heeding NaNs, etc.                  */\r
+/*                                                                    */\r
+/*   result gets the canonicalized df with sign 0                     */\r
+/*   df     is the decFloat to abs                                    */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This has the same effect as decFloatPlus unless df is negative,    */\r
+/* in which case it has the same effect as decFloatMinus.  The        */\r
+/* effect is also the same as decFloatCopyAbs except that NaNs are    */\r
+/* handled normally (the sign of a NaN is not affected, and an sNaN   */\r
+/* will signal) and the result will be canonical.                     */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatAbs(decFloat *result, const decFloat *df,\r
+                       decContext *set) {\r
+  if (DFISNAN(df)) return decNaNs(result, df, NULL, set);\r
+  decCanonical(result, df);             // copy and check\r
+  DFBYTE(result, 0)&=~0x80;             // zero sign bit\r
+  return result;\r
+  } // decFloatAbs\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatAdd -- add two decFloats                                   */\r
+/*                                                                    */\r
+/*   result gets the result of adding dfl and dfr:                    */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+#if QUAD\r
+// Table for testing MSDs for fastpath elimination; returns the MSD of\r
+// a decDouble or decQuad (top 6 bits tested) ignoring the sign.\r
+// Infinities return -32 and NaNs return -128 so that summing the two\r
+// MSDs also allows rapid tests for the Specials (see code below).\r
+const Int DECTESTMSD[64]={\r
+  0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5,   6,    7,\r
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, -32, -128,\r
+  0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5,   6,    7,\r
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, -32, -128};\r
+#else\r
+// The table for testing MSDs is shared between the modules\r
+extern const Int DECTESTMSD[64];\r
+#endif\r
+\r
+decFloat * decFloatAdd(decFloat *result,\r
+                       const decFloat *dfl, const decFloat *dfr,\r
+                       decContext *set) {\r
+  bcdnum num;                      // for final conversion\r
+  Int    bexpl, bexpr;             // left and right biased exponents\r
+  uByte  *ub, *us, *ut;            // work\r
+  uInt   uiwork;                   // for macros\r
+  #if QUAD\r
+  uShort uswork;                   // ..\r
+  #endif\r
+\r
+  uInt sourhil, sourhir;           // top words from source decFloats\r
+                                   // [valid only through end of\r
+                                   // fastpath code -- before swap]\r
+  uInt diffsign;                   // non-zero if signs differ\r
+  uInt carry;                      // carry: 0 or 1 before add loop\r
+  Int  overlap;                    // coefficient overlap (if full)\r
+  Int  summ;                       // sum of the MSDs\r
+  // the following buffers hold coefficients with various alignments\r
+  // (see commentary and diagrams below)\r
+  uByte acc[4+2+DECPMAX*3+8];\r
+  uByte buf[4+2+DECPMAX*2];\r
+  uByte *umsd, *ulsd;              // local MSD and LSD pointers\r
+\r
+  #if DECLITEND\r
+    #define CARRYPAT 0x01000000    // carry=1 pattern\r
+  #else\r
+    #define CARRYPAT 0x00000001    // carry=1 pattern\r
+  #endif\r
+\r
+  /* Start decoding the arguments */\r
+  // The initial exponents are placed into the opposite Ints to\r
+  // that which might be expected; there are two sets of data to\r
+  // keep track of (each decFloat and the corresponding exponent),\r
+  // and this scheme means that at the swap point (after comparing\r
+  // exponents) only one pair of words needs to be swapped\r
+  // whichever path is taken (thereby minimising worst-case path).\r
+  // The calculated exponents will be nonsense when the arguments are\r
+  // Special, but are not used in that path\r
+  sourhil=DFWORD(dfl, 0);          // LHS top word\r
+  summ=DECTESTMSD[sourhil>>26];    // get first MSD for testing\r
+  bexpr=DECCOMBEXP[sourhil>>26];   // get exponent high bits (in place)\r
+  bexpr+=GETECON(dfl);             // .. + continuation\r
+\r
+  sourhir=DFWORD(dfr, 0);          // RHS top word\r
+  summ+=DECTESTMSD[sourhir>>26];   // sum MSDs for testing\r
+  bexpl=DECCOMBEXP[sourhir>>26];\r
+  bexpl+=GETECON(dfr);\r
+\r
+  // here bexpr has biased exponent from lhs, and vice versa\r
+\r
+  diffsign=(sourhil^sourhir)&DECFLOAT_Sign;\r
+\r
+  // now determine whether to take a fast path or the full-function\r
+  // slow path.  The slow path must be taken when:\r
+  //   -- both numbers are finite, and:\r
+  //         the exponents are different, or\r
+  //         the signs are different, or\r
+  //         the sum of the MSDs is >8 (hence might overflow)\r
+  // specialness and the sum of the MSDs can be tested at once using\r
+  // the summ value just calculated, so the test for specials is no\r
+  // longer on the worst-case path (as of 3.60)\r
+\r
+  if (summ<=8) {                   // MSD+MSD is good, or there is a special\r
+    if (summ<0) {                  // there is a special\r
+      // Inf+Inf would give -64; Inf+finite is -32 or higher\r
+      if (summ<-64) return decNaNs(result, dfl, dfr, set);  // one or two NaNs\r
+      // two infinities with different signs is invalid\r
+      if (summ==-64 && diffsign) return decInvalid(result, set);\r
+      if (DFISINF(dfl)) return decInfinity(result, dfl);    // LHS is infinite\r
+      return decInfinity(result, dfr);                      // RHS must be Inf\r
+      }\r
+    // Here when both arguments are finite; fast path is possible\r
+    // (currently only for aligned and same-sign)\r
+    if (bexpr==bexpl && !diffsign) {\r
+      uInt tac[DECLETS+1];              // base-1000 coefficient\r
+      uInt encode;                      // work\r
+\r
+      // Get one coefficient as base-1000 and add the other\r
+      GETCOEFFTHOU(dfl, tac);           // least-significant goes to [0]\r
+      ADDCOEFFTHOU(dfr, tac);\r
+      // here the sum of the MSDs (plus any carry) will be <10 due to\r
+      // the fastpath test earlier\r
+\r
+      // construct the result; low word is the same for both formats\r
+      encode =BIN2DPD[tac[0]];\r
+      encode|=BIN2DPD[tac[1]]<<10;\r
+      encode|=BIN2DPD[tac[2]]<<20;\r
+      encode|=BIN2DPD[tac[3]]<<30;\r
+      DFWORD(result, (DECBYTES/4)-1)=encode;\r
+\r
+      // collect next two declets (all that remains, for Double)\r
+      encode =BIN2DPD[tac[3]]>>2;\r
+      encode|=BIN2DPD[tac[4]]<<8;\r
+\r
+      #if QUAD\r
+      // complete and lay out middling words\r
+      encode|=BIN2DPD[tac[5]]<<18;\r
+      encode|=BIN2DPD[tac[6]]<<28;\r
+      DFWORD(result, 2)=encode;\r
+\r
+      encode =BIN2DPD[tac[6]]>>4;\r
+      encode|=BIN2DPD[tac[7]]<<6;\r
+      encode|=BIN2DPD[tac[8]]<<16;\r
+      encode|=BIN2DPD[tac[9]]<<26;\r
+      DFWORD(result, 1)=encode;\r
+\r
+      // and final two declets\r
+      encode =BIN2DPD[tac[9]]>>6;\r
+      encode|=BIN2DPD[tac[10]]<<4;\r
+      #endif\r
+\r
+      // add exponent continuation and sign (from either argument)\r
+      encode|=sourhil & (ECONMASK | DECFLOAT_Sign);\r
+\r
+      // create lookup index = MSD + top two bits of biased exponent <<4\r
+      tac[DECLETS]|=(bexpl>>DECECONL)<<4;\r
+      encode|=DECCOMBFROM[tac[DECLETS]]; // add constructed combination field\r
+      DFWORD(result, 0)=encode;          // complete\r
+\r
+      // decFloatShow(result, ">");\r
+      return result;\r
+      } // fast path OK\r
+    // drop through to slow path\r
+    } // low sum or Special(s)\r
+\r
+  /* Slow path required -- arguments are finite and might overflow,   */\r
+  /* or require alignment, or might have different signs              */\r
+\r
+  // now swap either exponents or argument pointers\r
+  if (bexpl<=bexpr) {\r
+    // original left is bigger\r
+    Int bexpswap=bexpl;\r
+    bexpl=bexpr;\r
+    bexpr=bexpswap;\r
+    // printf("left bigger\n");\r
+    }\r
+   else {\r
+    const decFloat *dfswap=dfl;\r
+    dfl=dfr;\r
+    dfr=dfswap;\r
+    // printf("right bigger\n");\r
+    }\r
+  // [here dfl and bexpl refer to the datum with the larger exponent,\r
+  // of if the exponents are equal then the original LHS argument]\r
+\r
+  // if lhs is zero then result will be the rhs (now known to have\r
+  // the smaller exponent), which also may need to be tested for zero\r
+  // for the weird IEEE 754 sign rules\r
+  if (DFISZERO(dfl)) {\r
+    decCanonical(result, dfr);               // clean copy\r
+    // "When the sum of two operands with opposite signs is\r
+    // exactly zero, the sign of that sum shall be '+' in all\r
+    // rounding modes except round toward -Infinity, in which\r
+    // mode that sign shall be '-'."\r
+    if (diffsign && DFISZERO(result)) {\r
+      DFWORD(result, 0)&=~DECFLOAT_Sign;     // assume sign 0\r
+      if (set->round==DEC_ROUND_FLOOR) DFWORD(result, 0)|=DECFLOAT_Sign;\r
+      }\r
+    return result;\r
+    } // numfl is zero\r
+  // [here, LHS is non-zero; code below assumes that]\r
+\r
+  // Coefficients layout during the calculations to follow:\r
+  //\r
+  //       Overlap case:\r
+  //       +------------------------------------------------+\r
+  // acc:  |0000|      coeffa      | tail B |               |\r
+  //       +------------------------------------------------+\r
+  // buf:  |0000| pad0s |      coeffb       |               |\r
+  //       +------------------------------------------------+\r
+  //\r
+  //       Touching coefficients or gap:\r
+  //       +------------------------------------------------+\r
+  // acc:  |0000|      coeffa      | gap |      coeffb      |\r
+  //       +------------------------------------------------+\r
+  //       [buf not used or needed; gap clamped to Pmax]\r
+\r
+  // lay out lhs coefficient into accumulator; this starts at acc+4\r
+  // for decDouble or acc+6 for decQuad so the LSD is word-\r
+  // aligned; the top word gap is there only in case a carry digit\r
+  // is prefixed after the add -- it does not need to be zeroed\r
+  #if DOUBLE\r
+    #define COFF 4                      // offset into acc\r
+  #elif QUAD\r
+    UBFROMUS(acc+4, 0);                 // prefix 00\r
+    #define COFF 6                      // offset into acc\r
+  #endif\r
+\r
+  GETCOEFF(dfl, acc+COFF);              // decode from decFloat\r
+  ulsd=acc+COFF+DECPMAX-1;\r
+  umsd=acc+4;                           // [having this here avoids\r
+\r
+  #if DECTRACE\r
+  {bcdnum tum;\r
+  tum.msd=umsd;\r
+  tum.lsd=ulsd;\r
+  tum.exponent=bexpl-DECBIAS;\r
+  tum.sign=DFWORD(dfl, 0) & DECFLOAT_Sign;\r
+  decShowNum(&tum, "dflx");}\r
+  #endif\r
+\r
+  // if signs differ, take ten's complement of lhs (here the\r
+  // coefficient is subtracted from all-nines; the 1 is added during\r
+  // the later add cycle -- zeros to the right do not matter because\r
+  // the complement of zero is zero); these are fixed-length inverts\r
+  // where the lsd is known to be at a 4-byte boundary (so no borrow\r
+  // possible)\r
+  carry=0;                              // assume no carry\r
+  if (diffsign) {\r
+    carry=CARRYPAT;                     // for +1 during add\r
+    UBFROMUI(acc+ 4, 0x09090909-UBTOUI(acc+ 4));\r
+    UBFROMUI(acc+ 8, 0x09090909-UBTOUI(acc+ 8));\r
+    UBFROMUI(acc+12, 0x09090909-UBTOUI(acc+12));\r
+    UBFROMUI(acc+16, 0x09090909-UBTOUI(acc+16));\r
+    #if QUAD\r
+    UBFROMUI(acc+20, 0x09090909-UBTOUI(acc+20));\r
+    UBFROMUI(acc+24, 0x09090909-UBTOUI(acc+24));\r
+    UBFROMUI(acc+28, 0x09090909-UBTOUI(acc+28));\r
+    UBFROMUI(acc+32, 0x09090909-UBTOUI(acc+32));\r
+    UBFROMUI(acc+36, 0x09090909-UBTOUI(acc+36));\r
+    #endif\r
+    } // diffsign\r
+\r
+  // now process the rhs coefficient; if it cannot overlap lhs then\r
+  // it can be put straight into acc (with an appropriate gap, if\r
+  // needed) because no actual addition will be needed (except\r
+  // possibly to complete ten's complement)\r
+  overlap=DECPMAX-(bexpl-bexpr);\r
+  #if DECTRACE\r
+  printf("exps: %ld %ld\n", (LI)(bexpl-DECBIAS), (LI)(bexpr-DECBIAS));\r
+  printf("Overlap=%ld carry=%08lx\n", (LI)overlap, (LI)carry);\r
+  #endif\r
+\r
+  if (overlap<=0) {                     // no overlap possible\r
+    uInt gap;                           // local work\r
+    // since a full addition is not needed, a ten's complement\r
+    // calculation started above may need to be completed\r
+    if (carry) {\r
+      for (ub=ulsd; *ub==9; ub--) *ub=0;\r
+      *ub+=1;\r
+      carry=0;                          // taken care of\r
+      }\r
+    // up to DECPMAX-1 digits of the final result can extend down\r
+    // below the LSD of the lhs, so if the gap is >DECPMAX then the\r
+    // rhs will be simply sticky bits.  In this case the gap is\r
+    // clamped to DECPMAX and the exponent adjusted to suit [this is\r
+    // safe because the lhs is non-zero].\r
+    gap=-overlap;\r
+    if (gap>DECPMAX) {\r
+      bexpr+=gap-1;\r
+      gap=DECPMAX;\r
+      }\r
+    ub=ulsd+gap+1;                      // where MSD will go\r
+    // Fill the gap with 0s; note that there is no addition to do\r
+    ut=acc+COFF+DECPMAX;                // start of gap\r
+    for (; ut<ub; ut+=4) UBFROMUI(ut, 0); // mind the gap\r
+    if (overlap<-DECPMAX) {             // gap was > DECPMAX\r
+      *ub=(uByte)(!DFISZERO(dfr));      // make sticky digit\r
+      }\r
+     else {                             // need full coefficient\r
+      GETCOEFF(dfr, ub);                // decode from decFloat\r
+      ub+=DECPMAX-1;                    // new LSD...\r
+      }\r
+    ulsd=ub;                            // save new LSD\r
+    } // no overlap possible\r
+\r
+   else {                               // overlap>0\r
+    // coefficients overlap (perhaps completely, although also\r
+    // perhaps only where zeros)\r
+    if (overlap==DECPMAX) {             // aligned\r
+      ub=buf+COFF;                      // where msd will go\r
+      #if QUAD\r
+      UBFROMUS(buf+4, 0);               // clear quad's 00\r
+      #endif\r
+      GETCOEFF(dfr, ub);                // decode from decFloat\r
+      }\r
+     else {                             // unaligned\r
+      ub=buf+COFF+DECPMAX-overlap;      // where MSD will go\r
+      // Fill the prefix gap with 0s; 8 will cover most common\r
+      // unalignments, so start with direct assignments (a loop is\r
+      // then used for any remaining -- the loop (and the one in a\r
+      // moment) is not then on the critical path because the number\r
+      // of additions is reduced by (at least) two in this case)\r
+      UBFROMUI(buf+4, 0);               // [clears decQuad 00 too]\r
+      UBFROMUI(buf+8, 0);\r
+      if (ub>buf+12) {\r
+        ut=buf+12;                      // start any remaining\r
+        for (; ut<ub; ut+=4) UBFROMUI(ut, 0); // fill them\r
+        }\r
+      GETCOEFF(dfr, ub);                // decode from decFloat\r
+\r
+      // now move tail of rhs across to main acc; again use direct\r
+      // copies for 8 digits-worth\r
+      UBFROMUI(acc+COFF+DECPMAX,   UBTOUI(buf+COFF+DECPMAX));\r
+      UBFROMUI(acc+COFF+DECPMAX+4, UBTOUI(buf+COFF+DECPMAX+4));\r
+      if (buf+COFF+DECPMAX+8<ub+DECPMAX) {\r
+        us=buf+COFF+DECPMAX+8;          // source\r
+        ut=acc+COFF+DECPMAX+8;          // target\r
+        for (; us<ub+DECPMAX; us+=4, ut+=4) UBFROMUI(ut, UBTOUI(us));\r
+        }\r
+      } // unaligned\r
+\r
+    ulsd=acc+(ub-buf+DECPMAX-1);        // update LSD pointer\r
+\r
+    // Now do the add of the non-tail; this is all nicely aligned,\r
+    // and is over a multiple of four digits (because for Quad two\r
+    // zero digits were added on the left); words in both acc and\r
+    // buf (buf especially) will often be zero\r
+    // [byte-by-byte add, here, is about 15% slower total effect than\r
+    // the by-fours]\r
+\r
+    // Now effect the add; this is harder on a little-endian\r
+    // machine as the inter-digit carry cannot use the usual BCD\r
+    // addition trick because the bytes are loaded in the wrong order\r
+    // [this loop could be unrolled, but probably scarcely worth it]\r
+\r
+    ut=acc+COFF+DECPMAX-4;              // target LSW (acc)\r
+    us=buf+COFF+DECPMAX-4;              // source LSW (buf, to add to acc)\r
+\r
+    #if !DECLITEND\r
+    for (; ut>=acc+4; ut-=4, us-=4) {   // big-endian add loop\r
+      // bcd8 add\r
+      carry+=UBTOUI(us);                // rhs + carry\r
+      if (carry==0) continue;           // no-op\r
+      carry+=UBTOUI(ut);                // lhs\r
+      // Big-endian BCD adjust (uses internal carry)\r
+      carry+=0x76f6f6f6;                // note top nibble not all bits\r
+      // apply BCD adjust and save\r
+      UBFROMUI(ut, (carry & 0x0f0f0f0f) - ((carry & 0x60606060)>>4));\r
+      carry>>=31;                       // true carry was at far left\r
+      } // add loop\r
+    #else\r
+    for (; ut>=acc+4; ut-=4, us-=4) {   // little-endian add loop\r
+      // bcd8 add\r
+      carry+=UBTOUI(us);                // rhs + carry\r
+      if (carry==0) continue;           // no-op [common if unaligned]\r
+      carry+=UBTOUI(ut);                // lhs\r
+      // Little-endian BCD adjust; inter-digit carry must be manual\r
+      // because the lsb from the array will be in the most-significant\r
+      // byte of carry\r
+      carry+=0x76767676;                // note no inter-byte carries\r
+      carry+=(carry & 0x80000000)>>15;\r
+      carry+=(carry & 0x00800000)>>15;\r
+      carry+=(carry & 0x00008000)>>15;\r
+      carry-=(carry & 0x60606060)>>4;   // BCD adjust back\r
+      UBFROMUI(ut, carry & 0x0f0f0f0f); // clear debris and save\r
+      // here, final carry-out bit is at 0x00000080; move it ready\r
+      // for next word-add (i.e., to 0x01000000)\r
+      carry=(carry & 0x00000080)<<17;\r
+      } // add loop\r
+    #endif\r
+\r
+    #if DECTRACE\r
+    {bcdnum tum;\r
+    printf("Add done, carry=%08lx, diffsign=%ld\n", (LI)carry, (LI)diffsign);\r
+    tum.msd=umsd;  // acc+4;\r
+    tum.lsd=ulsd;\r
+    tum.exponent=0;\r
+    tum.sign=0;\r
+    decShowNum(&tum, "dfadd");}\r
+    #endif\r
+    } // overlap possible\r
+\r
+  // ordering here is a little strange in order to have slowest path\r
+  // first in GCC asm listing\r
+  if (diffsign) {                  // subtraction\r
+    if (!carry) {                  // no carry out means RHS<LHS\r
+      // borrowed -- take ten's complement\r
+      // sign is lhs sign\r
+      num.sign=DFWORD(dfl, 0) & DECFLOAT_Sign;\r
+\r
+      // invert the coefficient first by fours, then add one; space\r
+      // at the end of the buffer ensures the by-fours is always\r
+      // safe, but lsd+1 must be cleared to prevent a borrow\r
+      // if big-endian\r
+      #if !DECLITEND\r
+      *(ulsd+1)=0;\r
+      #endif\r
+      // there are always at least four coefficient words\r
+      UBFROMUI(umsd,    0x09090909-UBTOUI(umsd));\r
+      UBFROMUI(umsd+4,  0x09090909-UBTOUI(umsd+4));\r
+      UBFROMUI(umsd+8,  0x09090909-UBTOUI(umsd+8));\r
+      UBFROMUI(umsd+12, 0x09090909-UBTOUI(umsd+12));\r
+      #if DOUBLE\r
+        #define BNEXT 16\r
+      #elif QUAD\r
+        UBFROMUI(umsd+16, 0x09090909-UBTOUI(umsd+16));\r
+        UBFROMUI(umsd+20, 0x09090909-UBTOUI(umsd+20));\r
+        UBFROMUI(umsd+24, 0x09090909-UBTOUI(umsd+24));\r
+        UBFROMUI(umsd+28, 0x09090909-UBTOUI(umsd+28));\r
+        UBFROMUI(umsd+32, 0x09090909-UBTOUI(umsd+32));\r
+        #define BNEXT 36\r
+      #endif\r
+      if (ulsd>=umsd+BNEXT) {           // unaligned\r
+        // eight will handle most unaligments for Double; 16 for Quad\r
+        UBFROMUI(umsd+BNEXT,   0x09090909-UBTOUI(umsd+BNEXT));\r
+        UBFROMUI(umsd+BNEXT+4, 0x09090909-UBTOUI(umsd+BNEXT+4));\r
+        #if DOUBLE\r
+        #define BNEXTY (BNEXT+8)\r
+        #elif QUAD\r
+        UBFROMUI(umsd+BNEXT+8,  0x09090909-UBTOUI(umsd+BNEXT+8));\r
+        UBFROMUI(umsd+BNEXT+12, 0x09090909-UBTOUI(umsd+BNEXT+12));\r
+        #define BNEXTY (BNEXT+16)\r
+        #endif\r
+        if (ulsd>=umsd+BNEXTY) {        // very unaligned\r
+          ut=umsd+BNEXTY;               // -> continue\r
+          for (;;ut+=4) {\r
+            UBFROMUI(ut, 0x09090909-UBTOUI(ut)); // invert four digits\r
+            if (ut>=ulsd-3) break;      // all done\r
+            }\r
+          }\r
+        }\r
+      // complete the ten's complement by adding 1\r
+      for (ub=ulsd; *ub==9; ub--) *ub=0;\r
+      *ub+=1;\r
+      } // borrowed\r
+\r
+     else {                        // carry out means RHS>=LHS\r
+      num.sign=DFWORD(dfr, 0) & DECFLOAT_Sign;\r
+      // all done except for the special IEEE 754 exact-zero-result\r
+      // rule (see above); while testing for zero, strip leading\r
+      // zeros (which will save decFinalize doing it) (this is in\r
+      // diffsign path, so carry impossible and true umsd is\r
+      // acc+COFF)\r
+\r
+      // Check the initial coefficient area using the fast macro;\r
+      // this will often be all that needs to be done (as on the\r
+      // worst-case path when the subtraction was aligned and\r
+      // full-length)\r
+      if (ISCOEFFZERO(acc+COFF)) {\r
+        umsd=acc+COFF+DECPMAX-1;   // so far, so zero\r
+        if (ulsd>umsd) {           // more to check\r
+          umsd++;                  // to align after checked area\r
+          for (; UBTOUI(umsd)==0 && umsd+3<ulsd;) umsd+=4;\r
+          for (; *umsd==0 && umsd<ulsd;) umsd++;\r
+          }\r
+        if (*umsd==0) {            // must be true zero (and diffsign)\r
+          num.sign=0;              // assume +\r
+          if (set->round==DEC_ROUND_FLOOR) num.sign=DECFLOAT_Sign;\r
+          }\r
+        }\r
+      // [else was not zero, might still have leading zeros]\r
+      } // subtraction gave positive result\r
+    } // diffsign\r
+\r
+   else { // same-sign addition\r
+    num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;\r
+    #if DOUBLE\r
+    if (carry) {                   // only possible with decDouble\r
+      *(acc+3)=1;                  // [Quad has leading 00]\r
+      umsd=acc+3;\r
+      }\r
+    #endif\r
+    } // same sign\r
+\r
+  num.msd=umsd;                    // set MSD ..\r
+  num.lsd=ulsd;                    // .. and LSD\r
+  num.exponent=bexpr-DECBIAS;      // set exponent to smaller, unbiassed\r
+\r
+  #if DECTRACE\r
+  decFloatShow(dfl, "dfl");\r
+  decFloatShow(dfr, "dfr");\r
+  decShowNum(&num, "postadd");\r
+  #endif\r
+  return decFinalize(result, &num, set); // round, check, and lay out\r
+  } // decFloatAdd\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatAnd -- logical digitwise AND of two decFloats              */\r
+/*                                                                    */\r
+/*   result gets the result of ANDing dfl and dfr                     */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result, which will be canonical with sign=0              */\r
+/*                                                                    */\r
+/* The operands must be positive, finite with exponent q=0, and       */\r
+/* comprise just zeros and ones; if not, Invalid operation results.   */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatAnd(decFloat *result,\r
+                       const decFloat *dfl, const decFloat *dfr,\r
+                       decContext *set) {\r
+  if (!DFISUINT01(dfl) || !DFISUINT01(dfr)\r
+   || !DFISCC01(dfl)   || !DFISCC01(dfr)) return decInvalid(result, set);\r
+  // the operands are positive finite integers (q=0) with just 0s and 1s\r
+  #if DOUBLE\r
+   DFWORD(result, 0)=ZEROWORD\r
+                   |((DFWORD(dfl, 0) & DFWORD(dfr, 0))&0x04009124);\r
+   DFWORD(result, 1)=(DFWORD(dfl, 1) & DFWORD(dfr, 1))&0x49124491;\r
+  #elif QUAD\r
+   DFWORD(result, 0)=ZEROWORD\r
+                   |((DFWORD(dfl, 0) & DFWORD(dfr, 0))&0x04000912);\r
+   DFWORD(result, 1)=(DFWORD(dfl, 1) & DFWORD(dfr, 1))&0x44912449;\r
+   DFWORD(result, 2)=(DFWORD(dfl, 2) & DFWORD(dfr, 2))&0x12449124;\r
+   DFWORD(result, 3)=(DFWORD(dfl, 3) & DFWORD(dfr, 3))&0x49124491;\r
+  #endif\r
+  return result;\r
+  } // decFloatAnd\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatCanonical -- copy a decFloat, making canonical             */\r
+/*                                                                    */\r
+/*   result gets the canonicalized df                                 */\r
+/*   df     is the decFloat to copy and make canonical                */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This works on specials, too; no error or exception is possible.    */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatCanonical(decFloat *result, const decFloat *df) {\r
+  return decCanonical(result, df);\r
+  } // decFloatCanonical\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatClass -- return the class of a decFloat                    */\r
+/*                                                                    */\r
+/*   df is the decFloat to test                                       */\r
+/*   returns the decClass that df falls into                          */\r
+/* ------------------------------------------------------------------ */\r
+enum decClass decFloatClass(const decFloat *df) {\r
+  Int exp;                         // exponent\r
+  if (DFISSPECIAL(df)) {\r
+    if (DFISQNAN(df)) return DEC_CLASS_QNAN;\r
+    if (DFISSNAN(df)) return DEC_CLASS_SNAN;\r
+    // must be an infinity\r
+    if (DFISSIGNED(df)) return DEC_CLASS_NEG_INF;\r
+    return DEC_CLASS_POS_INF;\r
+    }\r
+  if (DFISZERO(df)) {              // quite common\r
+    if (DFISSIGNED(df)) return DEC_CLASS_NEG_ZERO;\r
+    return DEC_CLASS_POS_ZERO;\r
+    }\r
+  // is finite and non-zero; similar code to decFloatIsNormal, here\r
+  // [this could be speeded up slightly by in-lining decFloatDigits]\r
+  exp=GETEXPUN(df)                 // get unbiased exponent ..\r
+     +decFloatDigits(df)-1;        // .. and make adjusted exponent\r
+  if (exp>=DECEMIN) {              // is normal\r
+    if (DFISSIGNED(df)) return DEC_CLASS_NEG_NORMAL;\r
+    return DEC_CLASS_POS_NORMAL;\r
+    }\r
+  // is subnormal\r
+  if (DFISSIGNED(df)) return DEC_CLASS_NEG_SUBNORMAL;\r
+  return DEC_CLASS_POS_SUBNORMAL;\r
+  } // decFloatClass\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatClassString -- return the class of a decFloat as a string  */\r
+/*                                                                    */\r
+/*   df is the decFloat to test                                       */\r
+/*   returns a constant string describing the class df falls into     */\r
+/* ------------------------------------------------------------------ */\r
+const char *decFloatClassString(const decFloat *df) {\r
+  enum decClass eclass=decFloatClass(df);\r
+  if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;\r
+  if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;\r
+  if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;\r
+  if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;\r
+  if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;\r
+  if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;\r
+  if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;\r
+  if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;\r
+  if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;\r
+  if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;\r
+  return DEC_ClassString_UN;           // Unknown\r
+  } // decFloatClassString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatCompare -- compare two decFloats; quiet NaNs allowed       */\r
+/*                                                                    */\r
+/*   result gets the result of comparing dfl and dfr                  */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result, which may be -1, 0, 1, or NaN (Unordered)        */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatCompare(decFloat *result,\r
+                           const decFloat *dfl, const decFloat *dfr,\r
+                           decContext *set) {\r
+  Int comp;                                  // work\r
+  // NaNs are handled as usual\r
+  if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+  // numeric comparison needed\r
+  comp=decNumCompare(dfl, dfr, 0);\r
+  decFloatZero(result);\r
+  if (comp==0) return result;\r
+  DFBYTE(result, DECBYTES-1)=0x01;      // LSD=1\r
+  if (comp<0) DFBYTE(result, 0)|=0x80;  // set sign bit\r
+  return result;\r
+  } // decFloatCompare\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatCompareSignal -- compare two decFloats; all NaNs signal    */\r
+/*                                                                    */\r
+/*   result gets the result of comparing dfl and dfr                  */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result, which may be -1, 0, 1, or NaN (Unordered)        */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatCompareSignal(decFloat *result,\r
+                                 const decFloat *dfl, const decFloat *dfr,\r
+                                 decContext *set) {\r
+  Int comp;                                  // work\r
+  // NaNs are handled as usual, except that all NaNs signal\r
+  if (DFISNAN(dfl) || DFISNAN(dfr)) {\r
+    set->status|=DEC_Invalid_operation;\r
+    return decNaNs(result, dfl, dfr, set);\r
+    }\r
+  // numeric comparison needed\r
+  comp=decNumCompare(dfl, dfr, 0);\r
+  decFloatZero(result);\r
+  if (comp==0) return result;\r
+  DFBYTE(result, DECBYTES-1)=0x01;      // LSD=1\r
+  if (comp<0) DFBYTE(result, 0)|=0x80;  // set sign bit\r
+  return result;\r
+  } // decFloatCompareSignal\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatCompareTotal -- compare two decFloats with total ordering  */\r
+/*                                                                    */\r
+/*   result gets the result of comparing dfl and dfr                  */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   returns result, which may be -1, 0, or 1                         */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatCompareTotal(decFloat *result,\r
+                                const decFloat *dfl, const decFloat *dfr) {\r
+  Int  comp;                                 // work\r
+  uInt uiwork;                               // for macros\r
+  #if QUAD\r
+  uShort uswork;                             // ..\r
+  #endif\r
+  if (DFISNAN(dfl) || DFISNAN(dfr)) {\r
+    Int nanl, nanr;                          // work\r
+    // morph NaNs to +/- 1 or 2, leave numbers as 0\r
+    nanl=DFISSNAN(dfl)+DFISQNAN(dfl)*2;      // quiet > signalling\r
+    if (DFISSIGNED(dfl)) nanl=-nanl;\r
+    nanr=DFISSNAN(dfr)+DFISQNAN(dfr)*2;\r
+    if (DFISSIGNED(dfr)) nanr=-nanr;\r
+    if (nanl>nanr) comp=+1;\r
+     else if (nanl<nanr) comp=-1;\r
+     else { // NaNs are the same type and sign .. must compare payload\r
+      // buffers need +2 for QUAD\r
+      uByte bufl[DECPMAX+4];                 // for LHS coefficient + foot\r
+      uByte bufr[DECPMAX+4];                 // for RHS coefficient + foot\r
+      uByte *ub, *uc;                        // work\r
+      Int sigl;                              // signum of LHS\r
+      sigl=(DFISSIGNED(dfl) ? -1 : +1);\r
+\r
+      // decode the coefficients\r
+      // (shift both right two if Quad to make a multiple of four)\r
+      #if QUAD\r
+        UBFROMUS(bufl, 0);\r
+        UBFROMUS(bufr, 0);\r
+      #endif\r
+      GETCOEFF(dfl, bufl+QUAD*2);            // decode from decFloat\r
+      GETCOEFF(dfr, bufr+QUAD*2);            // ..\r
+      // all multiples of four, here\r
+      comp=0;                                // assume equal\r
+      for (ub=bufl, uc=bufr; ub<bufl+DECPMAX+QUAD*2; ub+=4, uc+=4) {\r
+        uInt ui=UBTOUI(ub);\r
+        if (ui==UBTOUI(uc)) continue; // so far so same\r
+        // about to find a winner; go by bytes in case little-endian\r
+        for (;; ub++, uc++) {\r
+          if (*ub==*uc) continue;\r
+          if (*ub>*uc) comp=sigl;            // difference found\r
+           else comp=-sigl;                  // ..\r
+           break;\r
+          }\r
+        }\r
+      } // same NaN type and sign\r
+    }\r
+   else {\r
+    // numeric comparison needed\r
+    comp=decNumCompare(dfl, dfr, 1);    // total ordering\r
+    }\r
+  decFloatZero(result);\r
+  if (comp==0) return result;\r
+  DFBYTE(result, DECBYTES-1)=0x01;      // LSD=1\r
+  if (comp<0) DFBYTE(result, 0)|=0x80;  // set sign bit\r
+  return result;\r
+  } // decFloatCompareTotal\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatCompareTotalMag -- compare magnitudes with total ordering  */\r
+/*                                                                    */\r
+/*   result gets the result of comparing abs(dfl) and abs(dfr)        */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   returns result, which may be -1, 0, or 1                         */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatCompareTotalMag(decFloat *result,\r
+                                const decFloat *dfl, const decFloat *dfr) {\r
+  decFloat a, b;                        // for copy if needed\r
+  // copy and redirect signed operand(s)\r
+  if (DFISSIGNED(dfl)) {\r
+    decFloatCopyAbs(&a, dfl);\r
+    dfl=&a;\r
+    }\r
+  if (DFISSIGNED(dfr)) {\r
+    decFloatCopyAbs(&b, dfr);\r
+    dfr=&b;\r
+    }\r
+  return decFloatCompareTotal(result, dfl, dfr);\r
+  } // decFloatCompareTotalMag\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatCopy -- copy a decFloat as-is                              */\r
+/*                                                                    */\r
+/*   result gets the copy of dfl                                      */\r
+/*   dfl    is the decFloat to copy                                   */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This is a bitwise operation; no errors or exceptions are possible. */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatCopy(decFloat *result, const decFloat *dfl) {\r
+  if (dfl!=result) *result=*dfl;             // copy needed\r
+  return result;\r
+  } // decFloatCopy\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatCopyAbs -- copy a decFloat as-is and set sign bit to 0     */\r
+/*                                                                    */\r
+/*   result gets the copy of dfl with sign bit 0                      */\r
+/*   dfl    is the decFloat to copy                                   */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This is a bitwise operation; no errors or exceptions are possible. */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatCopyAbs(decFloat *result, const decFloat *dfl) {\r
+  if (dfl!=result) *result=*dfl;        // copy needed\r
+  DFBYTE(result, 0)&=~0x80;             // zero sign bit\r
+  return result;\r
+  } // decFloatCopyAbs\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatCopyNegate -- copy a decFloat as-is with inverted sign bit */\r
+/*                                                                    */\r
+/*   result gets the copy of dfl with sign bit inverted               */\r
+/*   dfl    is the decFloat to copy                                   */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This is a bitwise operation; no errors or exceptions are possible. */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatCopyNegate(decFloat *result, const decFloat *dfl) {\r
+  if (dfl!=result) *result=*dfl;        // copy needed\r
+  DFBYTE(result, 0)^=0x80;              // invert sign bit\r
+  return result;\r
+  } // decFloatCopyNegate\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatCopySign -- copy a decFloat with the sign of another       */\r
+/*                                                                    */\r
+/*   result gets the result of copying dfl with the sign of dfr       */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This is a bitwise operation; no errors or exceptions are possible. */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatCopySign(decFloat *result,\r
+                            const decFloat *dfl, const decFloat *dfr) {\r
+  uByte sign=(uByte)(DFBYTE(dfr, 0)&0x80);   // save sign bit\r
+  if (dfl!=result) *result=*dfl;             // copy needed\r
+  DFBYTE(result, 0)&=~0x80;                  // clear sign ..\r
+  DFBYTE(result, 0)=(uByte)(DFBYTE(result, 0)|sign); // .. and set saved\r
+  return result;\r
+  } // decFloatCopySign\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatDigits -- return the number of digits in a decFloat        */\r
+/*                                                                    */\r
+/*   df is the decFloat to investigate                                */\r
+/*   returns the number of significant digits in the decFloat; a      */\r
+/*     zero coefficient returns 1 as does an infinity (a NaN returns  */\r
+/*     the number of digits in the payload)                           */\r
+/* ------------------------------------------------------------------ */\r
+// private macro to extract a declet according to provided formula\r
+// (form), and if it is non-zero then return the calculated digits\r
+// depending on the declet number (n), where n=0 for the most\r
+// significant declet; uses uInt dpd for work\r
+#define dpdlenchk(n, form)  dpd=(form)&0x3ff;     \\r
+  if (dpd) return (DECPMAX-1-3*(n))-(3-DPD2BCD8[dpd*4+3])\r
+// next one is used when it is known that the declet must be\r
+// non-zero, or is the final zero declet\r
+#define dpdlendun(n, form)  dpd=(form)&0x3ff;     \\r
+  if (dpd==0) return 1;                           \\r
+  return (DECPMAX-1-3*(n))-(3-DPD2BCD8[dpd*4+3])\r
+\r
+uInt decFloatDigits(const decFloat *df) {\r
+  uInt dpd;                        // work\r
+  uInt sourhi=DFWORD(df, 0);       // top word from source decFloat\r
+  #if QUAD\r
+  uInt sourmh, sourml;\r
+  #endif\r
+  uInt sourlo;\r
+\r
+  if (DFISINF(df)) return 1;\r
+  // A NaN effectively has an MSD of 0; otherwise if non-zero MSD\r
+  // then the coefficient is full-length\r
+  if (!DFISNAN(df) && DECCOMBMSD[sourhi>>26]) return DECPMAX;\r
+\r
+  #if DOUBLE\r
+    if (sourhi&0x0003ffff) {     // ends in first\r
+      dpdlenchk(0, sourhi>>8);\r
+      sourlo=DFWORD(df, 1);\r
+      dpdlendun(1, (sourhi<<2) | (sourlo>>30));\r
+      } // [cannot drop through]\r
+    sourlo=DFWORD(df, 1);  // sourhi not involved now\r
+    if (sourlo&0xfff00000) {     // in one of first two\r
+      dpdlenchk(1, sourlo>>30);  // very rare\r
+      dpdlendun(2, sourlo>>20);\r
+      } // [cannot drop through]\r
+    dpdlenchk(3, sourlo>>10);\r
+    dpdlendun(4, sourlo);\r
+    // [cannot drop through]\r
+\r
+  #elif QUAD\r
+    if (sourhi&0x00003fff) {     // ends in first\r
+      dpdlenchk(0, sourhi>>4);\r
+      sourmh=DFWORD(df, 1);\r
+      dpdlendun(1, ((sourhi)<<6) | (sourmh>>26));\r
+      } // [cannot drop through]\r
+    sourmh=DFWORD(df, 1);\r
+    if (sourmh) {\r
+      dpdlenchk(1, sourmh>>26);\r
+      dpdlenchk(2, sourmh>>16);\r
+      dpdlenchk(3, sourmh>>6);\r
+      sourml=DFWORD(df, 2);\r
+      dpdlendun(4, ((sourmh)<<4) | (sourml>>28));\r
+      } // [cannot drop through]\r
+    sourml=DFWORD(df, 2);\r
+    if (sourml) {\r
+      dpdlenchk(4, sourml>>28);\r
+      dpdlenchk(5, sourml>>18);\r
+      dpdlenchk(6, sourml>>8);\r
+      sourlo=DFWORD(df, 3);\r
+      dpdlendun(7, ((sourml)<<2) | (sourlo>>30));\r
+      } // [cannot drop through]\r
+    sourlo=DFWORD(df, 3);\r
+    if (sourlo&0xfff00000) {     // in one of first two\r
+      dpdlenchk(7, sourlo>>30);  // very rare\r
+      dpdlendun(8, sourlo>>20);\r
+      } // [cannot drop through]\r
+    dpdlenchk(9, sourlo>>10);\r
+    dpdlendun(10, sourlo);\r
+    // [cannot drop through]\r
+  #endif\r
+  } // decFloatDigits\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatDivide -- divide a decFloat by another                     */\r
+/*                                                                    */\r
+/*   result gets the result of dividing dfl by dfr:                   */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+// This is just a wrapper.\r
+decFloat * decFloatDivide(decFloat *result,\r
+                          const decFloat *dfl, const decFloat *dfr,\r
+                          decContext *set) {\r
+  return decDivide(result, dfl, dfr, set, DIVIDE);\r
+  } // decFloatDivide\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatDivideInteger -- integer divide a decFloat by another      */\r
+/*                                                                    */\r
+/*   result gets the result of dividing dfl by dfr:                   */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatDivideInteger(decFloat *result,\r
+                             const decFloat *dfl, const decFloat *dfr,\r
+                             decContext *set) {\r
+  return decDivide(result, dfl, dfr, set, DIVIDEINT);\r
+  } // decFloatDivideInteger\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatFMA -- multiply and add three decFloats, fused             */\r
+/*                                                                    */\r
+/*   result gets the result of (dfl*dfr)+dff with a single rounding   */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   dff    is the final decFloat (fhs)                               */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatFMA(decFloat *result, const decFloat *dfl,\r
+                       const decFloat *dfr, const decFloat *dff,\r
+                       decContext *set) {\r
+\r
+  // The accumulator has the bytes needed for FiniteMultiply, plus\r
+  // one byte to the left in case of carry, plus DECPMAX+2 to the\r
+  // right for the final addition (up to full fhs + round & sticky)\r
+  #define FMALEN (ROUNDUP4(1+ (DECPMAX9*18+1) +DECPMAX+2))\r
+  uByte  acc[FMALEN];              // for multiplied coefficient in BCD\r
+                                   // .. and for final result\r
+  bcdnum mul;                      // for multiplication result\r
+  bcdnum fin;                      // for final operand, expanded\r
+  uByte  coe[ROUNDUP4(DECPMAX)];   // dff coefficient in BCD\r
+  bcdnum *hi, *lo;                 // bcdnum with higher/lower exponent\r
+  uInt   diffsign;                 // non-zero if signs differ\r
+  uInt   hipad;                    // pad digit for hi if needed\r
+  Int    padding;                  // excess exponent\r
+  uInt   carry;                    // +1 for ten's complement and during add\r
+  uByte  *ub, *uh, *ul;            // work\r
+  uInt   uiwork;                   // for macros\r
+\r
+  // handle all the special values [any special operand leads to a\r
+  // special result]\r
+  if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr) || DFISSPECIAL(dff)) {\r
+    decFloat proxy;                // multiplication result proxy\r
+    // NaNs are handled as usual, giving priority to sNaNs\r
+    if (DFISSNAN(dfl) || DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+    if (DFISSNAN(dff)) return decNaNs(result, dff, NULL, set);\r
+    if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+    if (DFISNAN(dff)) return decNaNs(result, dff, NULL, set);\r
+    // One or more of the three is infinite\r
+    // infinity times zero is bad\r
+    decFloatZero(&proxy);\r
+    if (DFISINF(dfl)) {\r
+      if (DFISZERO(dfr)) return decInvalid(result, set);\r
+      decInfinity(&proxy, &proxy);\r
+      }\r
+     else if (DFISINF(dfr)) {\r
+      if (DFISZERO(dfl)) return decInvalid(result, set);\r
+      decInfinity(&proxy, &proxy);\r
+      }\r
+    // compute sign of multiplication and place in proxy\r
+    DFWORD(&proxy, 0)|=(DFWORD(dfl, 0)^DFWORD(dfr, 0))&DECFLOAT_Sign;\r
+    if (!DFISINF(dff)) return decFloatCopy(result, &proxy);\r
+    // dff is Infinite\r
+    if (!DFISINF(&proxy)) return decInfinity(result, dff);\r
+    // both sides of addition are infinite; different sign is bad\r
+    if ((DFWORD(dff, 0)&DECFLOAT_Sign)!=(DFWORD(&proxy, 0)&DECFLOAT_Sign))\r
+      return decInvalid(result, set);\r
+    return decFloatCopy(result, &proxy);\r
+    }\r
+\r
+  /* Here when all operands are finite */\r
+\r
+  // First multiply dfl*dfr\r
+  decFiniteMultiply(&mul, acc+1, dfl, dfr);\r
+  // The multiply is complete, exact and unbounded, and described in\r
+  // mul with the coefficient held in acc[1...]\r
+\r
+  // now add in dff; the algorithm is essentially the same as\r
+  // decFloatAdd, but the code is different because the code there\r
+  // is highly optimized for adding two numbers of the same size\r
+  fin.exponent=GETEXPUN(dff);           // get dff exponent and sign\r
+  fin.sign=DFWORD(dff, 0)&DECFLOAT_Sign;\r
+  diffsign=mul.sign^fin.sign;           // note if signs differ\r
+  fin.msd=coe;\r
+  fin.lsd=coe+DECPMAX-1;\r
+  GETCOEFF(dff, coe);                   // extract the coefficient\r
+\r
+  // now set hi and lo so that hi points to whichever of mul and fin\r
+  // has the higher exponent and lo points to the other [don't care,\r
+  // if the same].  One coefficient will be in acc, the other in coe.\r
+  if (mul.exponent>=fin.exponent) {\r
+    hi=&mul;\r
+    lo=&fin;\r
+    }\r
+   else {\r
+    hi=&fin;\r
+    lo=&mul;\r
+    }\r
+\r
+  // remove leading zeros on both operands; this will save time later\r
+  // and make testing for zero trivial (tests are safe because acc\r
+  // and coe are rounded up to uInts)\r
+  for (; UBTOUI(hi->msd)==0 && hi->msd+3<hi->lsd;) hi->msd+=4;\r
+  for (; *hi->msd==0 && hi->msd<hi->lsd;) hi->msd++;\r
+  for (; UBTOUI(lo->msd)==0 && lo->msd+3<lo->lsd;) lo->msd+=4;\r
+  for (; *lo->msd==0 && lo->msd<lo->lsd;) lo->msd++;\r
+\r
+  // if hi is zero then result will be lo (which has the smaller\r
+  // exponent), which also may need to be tested for zero for the\r
+  // weird IEEE 754 sign rules\r
+  if (*hi->msd==0) {                         // hi is zero\r
+    // "When the sum of two operands with opposite signs is\r
+    // exactly zero, the sign of that sum shall be '+' in all\r
+    // rounding modes except round toward -Infinity, in which\r
+    // mode that sign shall be '-'."\r
+    if (diffsign) {\r
+      if (*lo->msd==0) {                     // lo is zero\r
+        lo->sign=0;\r
+        if (set->round==DEC_ROUND_FLOOR) lo->sign=DECFLOAT_Sign;\r
+        } // diffsign && lo=0\r
+      } // diffsign\r
+    return decFinalize(result, lo, set);     // may need clamping\r
+    } // numfl is zero\r
+  // [here, both are minimal length and hi is non-zero]\r
+  // (if lo is zero then padding with zeros may be needed, below)\r
+\r
+  // if signs differ, take the ten's complement of hi (zeros to the\r
+  // right do not matter because the complement of zero is zero); the\r
+  // +1 is done later, as part of the addition, inserted at the\r
+  // correct digit\r
+  hipad=0;\r
+  carry=0;\r
+  if (diffsign) {\r
+    hipad=9;\r
+    carry=1;\r
+    // exactly the correct number of digits must be inverted\r
+    for (uh=hi->msd; uh<hi->lsd-3; uh+=4) UBFROMUI(uh, 0x09090909-UBTOUI(uh));\r
+    for (; uh<=hi->lsd; uh++) *uh=(uByte)(0x09-*uh);\r
+    }\r
+\r
+  // ready to add; note that hi has no leading zeros so gap\r
+  // calculation does not have to be as pessimistic as in decFloatAdd\r
+  // (this is much more like the arbitrary-precision algorithm in\r
+  // Rexx and decNumber)\r
+\r
+  // padding is the number of zeros that would need to be added to hi\r
+  // for its lsd to be aligned with the lsd of lo\r
+  padding=hi->exponent-lo->exponent;\r
+  // printf("FMA pad %ld\n", (LI)padding);\r
+\r
+  // the result of the addition will be built into the accumulator,\r
+  // starting from the far right; this could be either hi or lo, and\r
+  // will be aligned\r
+  ub=acc+FMALEN-1;                 // where lsd of result will go\r
+  ul=lo->lsd;                      // lsd of rhs\r
+\r
+  if (padding!=0) {                // unaligned\r
+    // if the msd of lo is more than DECPMAX+2 digits to the right of\r
+    // the original msd of hi then it can be reduced to a single\r
+    // digit at the right place, as it stays clear of hi digits\r
+    // [it must be DECPMAX+2 because during a subtraction the msd\r
+    // could become 0 after a borrow from 1.000 to 0.9999...]\r
+\r
+    Int hilen=(Int)(hi->lsd-hi->msd+1); // length of hi\r
+    Int lolen=(Int)(lo->lsd-lo->msd+1); // and of lo\r
+\r
+    if (hilen+padding-lolen > DECPMAX+2) {   // can reduce lo to single\r
+      // make sure it is virtually at least DECPMAX from hi->msd, at\r
+      // least to right of hi->lsd (in case of destructive subtract),\r
+      // and separated by at least two digits from either of those\r
+      // (the tricky DOUBLE case is when hi is a 1 that will become a\r
+      // 0.9999... by subtraction:\r
+      //   hi:   1                                   E+16\r
+      //   lo:    .................1000000000000000  E-16\r
+      // which for the addition pads to:\r
+      //   hi:   1000000000000000000                 E-16\r
+      //   lo:    .................1000000000000000  E-16\r
+      Int newexp=MINI(hi->exponent, hi->exponent+hilen-DECPMAX)-3;\r
+\r
+      // printf("FMA reduce: %ld\n", (LI)reduce);\r
+      lo->lsd=lo->msd;                       // to single digit [maybe 0]\r
+      lo->exponent=newexp;                   // new lowest exponent\r
+      padding=hi->exponent-lo->exponent;     // recalculate\r
+      ul=lo->lsd;                            // .. and repoint\r
+      }\r
+\r
+    // padding is still > 0, but will fit in acc (less leading carry slot)\r
+    #if DECCHECK\r
+      if (padding<=0) printf("FMA low padding: %ld\n", (LI)padding);\r
+      if (hilen+padding+1>FMALEN)\r
+        printf("FMA excess hilen+padding: %ld+%ld \n", (LI)hilen, (LI)padding);\r
+      // printf("FMA padding: %ld\n", (LI)padding);\r
+    #endif\r
+\r
+    // padding digits can now be set in the result; one or more of\r
+    // these will come from lo; others will be zeros in the gap\r
+    for (; ul-3>=lo->msd && padding>3; padding-=4, ul-=4, ub-=4) {\r
+      UBFROMUI(ub-3, UBTOUI(ul-3));          // [cannot overlap]\r
+      }\r
+    for (; ul>=lo->msd && padding>0; padding--, ul--, ub--) *ub=*ul;\r
+    for (;padding>0; padding--, ub--) *ub=0; // mind the gap\r
+    }\r
+\r
+  // addition now complete to the right of the rightmost digit of hi\r
+  uh=hi->lsd;\r
+\r
+  // dow do the add from hi->lsd to the left\r
+  // [bytewise, because either operand can run out at any time]\r
+  // carry was set up depending on ten's complement above\r
+  // first assume both operands have some digits\r
+  for (;; ub--) {\r
+    if (uh<hi->msd || ul<lo->msd) break;\r
+    *ub=(uByte)(carry+(*uh--)+(*ul--));\r
+    carry=0;\r
+    if (*ub<10) continue;\r
+    *ub-=10;\r
+    carry=1;\r
+    } // both loop\r
+\r
+  if (ul<lo->msd) {           // to left of lo\r
+    for (;; ub--) {\r
+      if (uh<hi->msd) break;\r
+      *ub=(uByte)(carry+(*uh--));  // [+0]\r
+      carry=0;\r
+      if (*ub<10) continue;\r
+      *ub-=10;\r
+      carry=1;\r
+      } // hi loop\r
+    }\r
+   else {                     // to left of hi\r
+    for (;; ub--) {\r
+      if (ul<lo->msd) break;\r
+      *ub=(uByte)(carry+hipad+(*ul--));\r
+      carry=0;\r
+      if (*ub<10) continue;\r
+      *ub-=10;\r
+      carry=1;\r
+      } // lo loop\r
+    }\r
+\r
+  // addition complete -- now handle carry, borrow, etc.\r
+  // use lo to set up the num (its exponent is already correct, and\r
+  // sign usually is)\r
+  lo->msd=ub+1;\r
+  lo->lsd=acc+FMALEN-1;\r
+  // decShowNum(lo, "lo");\r
+  if (!diffsign) {                 // same-sign addition\r
+    if (carry) {                   // carry out\r
+      *ub=1;                       // place the 1 ..\r
+      lo->msd--;                   // .. and update\r
+      }\r
+    } // same sign\r
+   else {                          // signs differed (subtraction)\r
+    if (!carry) {                  // no carry out means hi<lo\r
+      // borrowed -- take ten's complement of the right digits\r
+      lo->sign=hi->sign;           // sign is lhs sign\r
+      for (ul=lo->msd; ul<lo->lsd-3; ul+=4) UBFROMUI(ul, 0x09090909-UBTOUI(ul));\r
+      for (; ul<=lo->lsd; ul++) *ul=(uByte)(0x09-*ul); // [leaves ul at lsd+1]\r
+      // complete the ten's complement by adding 1 [cannot overrun]\r
+      for (ul--; *ul==9; ul--) *ul=0;\r
+      *ul+=1;\r
+      } // borrowed\r
+     else {                        // carry out means hi>=lo\r
+      // sign to use is lo->sign\r
+      // all done except for the special IEEE 754 exact-zero-result\r
+      // rule (see above); while testing for zero, strip leading\r
+      // zeros (which will save decFinalize doing it)\r
+      for (; UBTOUI(lo->msd)==0 && lo->msd+3<lo->lsd;) lo->msd+=4;\r
+      for (; *lo->msd==0 && lo->msd<lo->lsd;) lo->msd++;\r
+      if (*lo->msd==0) {           // must be true zero (and diffsign)\r
+        lo->sign=0;                // assume +\r
+        if (set->round==DEC_ROUND_FLOOR) lo->sign=DECFLOAT_Sign;\r
+        }\r
+      // [else was not zero, might still have leading zeros]\r
+      } // subtraction gave positive result\r
+    } // diffsign\r
+\r
+  #if DECCHECK\r
+  // assert no left underrun\r
+  if (lo->msd<acc) {\r
+    printf("FMA underrun by %ld \n", (LI)(acc-lo->msd));\r
+    }\r
+  #endif\r
+\r
+  return decFinalize(result, lo, set);  // round, check, and lay out\r
+  } // decFloatFMA\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatFromInt -- initialise a decFloat from an Int               */\r
+/*                                                                    */\r
+/*   result gets the converted Int                                    */\r
+/*   n      is the Int to convert                                     */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* The result is Exact; no errors or exceptions are possible.         */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatFromInt32(decFloat *result, Int n) {\r
+  uInt u=(uInt)n;                       // copy as bits\r
+  uInt encode;                          // work\r
+  DFWORD(result, 0)=ZEROWORD;           // always\r
+  #if QUAD\r
+    DFWORD(result, 1)=0;\r
+    DFWORD(result, 2)=0;\r
+  #endif\r
+  if (n<0) {                            // handle -n with care\r
+    // [This can be done without the test, but is then slightly slower]\r
+    u=(~u)+1;\r
+    DFWORD(result, 0)|=DECFLOAT_Sign;\r
+    }\r
+  // Since the maximum value of u now is 2**31, only the low word of\r
+  // result is affected\r
+  encode=BIN2DPD[u%1000];\r
+  u/=1000;\r
+  encode|=BIN2DPD[u%1000]<<10;\r
+  u/=1000;\r
+  encode|=BIN2DPD[u%1000]<<20;\r
+  u/=1000;                              // now 0, 1, or 2\r
+  encode|=u<<30;\r
+  DFWORD(result, DECWORDS-1)=encode;\r
+  return result;\r
+  } // decFloatFromInt32\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatFromUInt -- initialise a decFloat from a uInt              */\r
+/*                                                                    */\r
+/*   result gets the converted uInt                                   */\r
+/*   n      is the uInt to convert                                    */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* The result is Exact; no errors or exceptions are possible.         */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatFromUInt32(decFloat *result, uInt u) {\r
+  uInt encode;                          // work\r
+  DFWORD(result, 0)=ZEROWORD;           // always\r
+  #if QUAD\r
+    DFWORD(result, 1)=0;\r
+    DFWORD(result, 2)=0;\r
+  #endif\r
+  encode=BIN2DPD[u%1000];\r
+  u/=1000;\r
+  encode|=BIN2DPD[u%1000]<<10;\r
+  u/=1000;\r
+  encode|=BIN2DPD[u%1000]<<20;\r
+  u/=1000;                              // now 0 -> 4\r
+  encode|=u<<30;\r
+  DFWORD(result, DECWORDS-1)=encode;\r
+  DFWORD(result, DECWORDS-2)|=u>>2;     // rarely non-zero\r
+  return result;\r
+  } // decFloatFromUInt32\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatInvert -- logical digitwise INVERT of a decFloat           */\r
+/*                                                                    */\r
+/*   result gets the result of INVERTing df                           */\r
+/*   df     is the decFloat to invert                                 */\r
+/*   set    is the context                                            */\r
+/*   returns result, which will be canonical with sign=0              */\r
+/*                                                                    */\r
+/* The operand must be positive, finite with exponent q=0, and        */\r
+/* comprise just zeros and ones; if not, Invalid operation results.   */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatInvert(decFloat *result, const decFloat *df,\r
+                          decContext *set) {\r
+  uInt sourhi=DFWORD(df, 0);            // top word of dfs\r
+\r
+  if (!DFISUINT01(df) || !DFISCC01(df)) return decInvalid(result, set);\r
+  // the operand is a finite integer (q=0)\r
+  #if DOUBLE\r
+   DFWORD(result, 0)=ZEROWORD|((~sourhi)&0x04009124);\r
+   DFWORD(result, 1)=(~DFWORD(df, 1))   &0x49124491;\r
+  #elif QUAD\r
+   DFWORD(result, 0)=ZEROWORD|((~sourhi)&0x04000912);\r
+   DFWORD(result, 1)=(~DFWORD(df, 1))   &0x44912449;\r
+   DFWORD(result, 2)=(~DFWORD(df, 2))   &0x12449124;\r
+   DFWORD(result, 3)=(~DFWORD(df, 3))   &0x49124491;\r
+  #endif\r
+  return result;\r
+  } // decFloatInvert\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatIs -- decFloat tests (IsSigned, etc.)                      */\r
+/*                                                                    */\r
+/*   df is the decFloat to test                                       */\r
+/*   returns 0 or 1 in a uInt                                         */\r
+/*                                                                    */\r
+/* Many of these could be macros, but having them as real functions   */\r
+/* is a little cleaner (and they can be referred to here by the       */\r
+/* generic names)                                                     */\r
+/* ------------------------------------------------------------------ */\r
+uInt decFloatIsCanonical(const decFloat *df) {\r
+  if (DFISSPECIAL(df)) {\r
+    if (DFISINF(df)) {\r
+      if (DFWORD(df, 0)&ECONMASK) return 0;  // exponent continuation\r
+      if (!DFISCCZERO(df)) return 0;         // coefficient continuation\r
+      return 1;\r
+      }\r
+    // is a NaN\r
+    if (DFWORD(df, 0)&ECONNANMASK) return 0; // exponent continuation\r
+    if (DFISCCZERO(df)) return 1;            // coefficient continuation\r
+    // drop through to check payload\r
+    }\r
+  { // declare block\r
+  #if DOUBLE\r
+    uInt sourhi=DFWORD(df, 0);\r
+    uInt sourlo=DFWORD(df, 1);\r
+    if (CANONDPDOFF(sourhi, 8)\r
+     && CANONDPDTWO(sourhi, sourlo, 30)\r
+     && CANONDPDOFF(sourlo, 20)\r
+     && CANONDPDOFF(sourlo, 10)\r
+     && CANONDPDOFF(sourlo, 0)) return 1;\r
+  #elif QUAD\r
+    uInt sourhi=DFWORD(df, 0);\r
+    uInt sourmh=DFWORD(df, 1);\r
+    uInt sourml=DFWORD(df, 2);\r
+    uInt sourlo=DFWORD(df, 3);\r
+    if (CANONDPDOFF(sourhi, 4)\r
+     && CANONDPDTWO(sourhi, sourmh, 26)\r
+     && CANONDPDOFF(sourmh, 16)\r
+     && CANONDPDOFF(sourmh, 6)\r
+     && CANONDPDTWO(sourmh, sourml, 28)\r
+     && CANONDPDOFF(sourml, 18)\r
+     && CANONDPDOFF(sourml, 8)\r
+     && CANONDPDTWO(sourml, sourlo, 30)\r
+     && CANONDPDOFF(sourlo, 20)\r
+     && CANONDPDOFF(sourlo, 10)\r
+     && CANONDPDOFF(sourlo, 0)) return 1;\r
+  #endif\r
+  } // block\r
+  return 0;    // a declet is non-canonical\r
+  }\r
+\r
+uInt decFloatIsFinite(const decFloat *df) {\r
+  return !DFISSPECIAL(df);\r
+  }\r
+uInt decFloatIsInfinite(const decFloat *df) {\r
+  return DFISINF(df);\r
+  }\r
+uInt decFloatIsInteger(const decFloat *df) {\r
+  return DFISINT(df);\r
+  }\r
+uInt decFloatIsLogical(const decFloat *df) {\r
+  return DFISUINT01(df) & DFISCC01(df);\r
+  }\r
+uInt decFloatIsNaN(const decFloat *df) {\r
+  return DFISNAN(df);\r
+  }\r
+uInt decFloatIsNegative(const decFloat *df) {\r
+  return DFISSIGNED(df) && !DFISZERO(df) && !DFISNAN(df);\r
+  }\r
+uInt decFloatIsNormal(const decFloat *df) {\r
+  Int exp;                         // exponent\r
+  if (DFISSPECIAL(df)) return 0;\r
+  if (DFISZERO(df)) return 0;\r
+  // is finite and non-zero\r
+  exp=GETEXPUN(df)                 // get unbiased exponent ..\r
+     +decFloatDigits(df)-1;        // .. and make adjusted exponent\r
+  return (exp>=DECEMIN);           // < DECEMIN is subnormal\r
+  }\r
+uInt decFloatIsPositive(const decFloat *df) {\r
+  return !DFISSIGNED(df) && !DFISZERO(df) && !DFISNAN(df);\r
+  }\r
+uInt decFloatIsSignaling(const decFloat *df) {\r
+  return DFISSNAN(df);\r
+  }\r
+uInt decFloatIsSignalling(const decFloat *df) {\r
+  return DFISSNAN(df);\r
+  }\r
+uInt decFloatIsSigned(const decFloat *df) {\r
+  return DFISSIGNED(df);\r
+  }\r
+uInt decFloatIsSubnormal(const decFloat *df) {\r
+  if (DFISSPECIAL(df)) return 0;\r
+  // is finite\r
+  if (decFloatIsNormal(df)) return 0;\r
+  // it is <Nmin, but could be zero\r
+  if (DFISZERO(df)) return 0;\r
+  return 1;                                  // is subnormal\r
+  }\r
+uInt decFloatIsZero(const decFloat *df) {\r
+  return DFISZERO(df);\r
+  } // decFloatIs...\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatLogB -- return adjusted exponent, by 754 rules             */\r
+/*                                                                    */\r
+/*   result gets the adjusted exponent as an integer, or a NaN etc.   */\r
+/*   df     is the decFloat to be examined                            */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* Notable cases:                                                     */\r
+/*   A<0 -> Use |A|                                                   */\r
+/*   A=0 -> -Infinity (Division by zero)                              */\r
+/*   A=Infinite -> +Infinity (Exact)                                  */\r
+/*   A=1 exactly -> 0 (Exact)                                         */\r
+/*   NaNs are propagated as usual                                     */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatLogB(decFloat *result, const decFloat *df,\r
+                        decContext *set) {\r
+  Int ae;                                    // adjusted exponent\r
+  if (DFISNAN(df)) return decNaNs(result, df, NULL, set);\r
+  if (DFISINF(df)) {\r
+    DFWORD(result, 0)=0;                     // need +ve\r
+    return decInfinity(result, result);      // canonical +Infinity\r
+    }\r
+  if (DFISZERO(df)) {\r
+    set->status|=DEC_Division_by_zero;       // as per 754\r
+    DFWORD(result, 0)=DECFLOAT_Sign;         // make negative\r
+    return decInfinity(result, result);      // canonical -Infinity\r
+    }\r
+  ae=GETEXPUN(df)                       // get unbiased exponent ..\r
+    +decFloatDigits(df)-1;              // .. and make adjusted exponent\r
+  // ae has limited range (3 digits for DOUBLE and 4 for QUAD), so\r
+  // it is worth using a special case of decFloatFromInt32\r
+  DFWORD(result, 0)=ZEROWORD;           // always\r
+  if (ae<0) {\r
+    DFWORD(result, 0)|=DECFLOAT_Sign;   // -0 so far\r
+    ae=-ae;\r
+    }\r
+  #if DOUBLE\r
+    DFWORD(result, 1)=BIN2DPD[ae];      // a single declet\r
+  #elif QUAD\r
+    DFWORD(result, 1)=0;\r
+    DFWORD(result, 2)=0;\r
+    DFWORD(result, 3)=(ae/1000)<<10;    // is <10, so need no DPD encode\r
+    DFWORD(result, 3)|=BIN2DPD[ae%1000];\r
+  #endif\r
+  return result;\r
+  } // decFloatLogB\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatMax -- return maxnum of two operands                       */\r
+/*                                                                    */\r
+/*   result gets the chosen decFloat                                  */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* If just one operand is a quiet NaN it is ignored.                  */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatMax(decFloat *result,\r
+                       const decFloat *dfl, const decFloat *dfr,\r
+                       decContext *set) {\r
+  Int comp;\r
+  if (DFISNAN(dfl)) {\r
+    // sNaN or both NaNs leads to normal NaN processing\r
+    if (DFISNAN(dfr) || DFISSNAN(dfl)) return decNaNs(result, dfl, dfr, set);\r
+    return decCanonical(result, dfr);        // RHS is numeric\r
+    }\r
+  if (DFISNAN(dfr)) {\r
+    // sNaN leads to normal NaN processing (both NaN handled above)\r
+    if (DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+    return decCanonical(result, dfl);        // LHS is numeric\r
+    }\r
+  // Both operands are numeric; numeric comparison needed -- use\r
+  // total order for a well-defined choice (and +0 > -0)\r
+  comp=decNumCompare(dfl, dfr, 1);\r
+  if (comp>=0) return decCanonical(result, dfl);\r
+  return decCanonical(result, dfr);\r
+  } // decFloatMax\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatMaxMag -- return maxnummag of two operands                 */\r
+/*                                                                    */\r
+/*   result gets the chosen decFloat                                  */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* Returns according to the magnitude comparisons if both numeric and */\r
+/* unequal, otherwise returns maxnum                                  */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatMaxMag(decFloat *result,\r
+                       const decFloat *dfl, const decFloat *dfr,\r
+                       decContext *set) {\r
+  Int comp;\r
+  decFloat absl, absr;\r
+  if (DFISNAN(dfl) || DFISNAN(dfr)) return decFloatMax(result, dfl, dfr, set);\r
+\r
+  decFloatCopyAbs(&absl, dfl);\r
+  decFloatCopyAbs(&absr, dfr);\r
+  comp=decNumCompare(&absl, &absr, 0);\r
+  if (comp>0) return decCanonical(result, dfl);\r
+  if (comp<0) return decCanonical(result, dfr);\r
+  return decFloatMax(result, dfl, dfr, set);\r
+  } // decFloatMaxMag\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatMin -- return minnum of two operands                       */\r
+/*                                                                    */\r
+/*   result gets the chosen decFloat                                  */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* If just one operand is a quiet NaN it is ignored.                  */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatMin(decFloat *result,\r
+                       const decFloat *dfl, const decFloat *dfr,\r
+                       decContext *set) {\r
+  Int comp;\r
+  if (DFISNAN(dfl)) {\r
+    // sNaN or both NaNs leads to normal NaN processing\r
+    if (DFISNAN(dfr) || DFISSNAN(dfl)) return decNaNs(result, dfl, dfr, set);\r
+    return decCanonical(result, dfr);        // RHS is numeric\r
+    }\r
+  if (DFISNAN(dfr)) {\r
+    // sNaN leads to normal NaN processing (both NaN handled above)\r
+    if (DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+    return decCanonical(result, dfl);        // LHS is numeric\r
+    }\r
+  // Both operands are numeric; numeric comparison needed -- use\r
+  // total order for a well-defined choice (and +0 > -0)\r
+  comp=decNumCompare(dfl, dfr, 1);\r
+  if (comp<=0) return decCanonical(result, dfl);\r
+  return decCanonical(result, dfr);\r
+  } // decFloatMin\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatMinMag -- return minnummag of two operands                 */\r
+/*                                                                    */\r
+/*   result gets the chosen decFloat                                  */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* Returns according to the magnitude comparisons if both numeric and */\r
+/* unequal, otherwise returns minnum                                  */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatMinMag(decFloat *result,\r
+                       const decFloat *dfl, const decFloat *dfr,\r
+                       decContext *set) {\r
+  Int comp;\r
+  decFloat absl, absr;\r
+  if (DFISNAN(dfl) || DFISNAN(dfr)) return decFloatMin(result, dfl, dfr, set);\r
+\r
+  decFloatCopyAbs(&absl, dfl);\r
+  decFloatCopyAbs(&absr, dfr);\r
+  comp=decNumCompare(&absl, &absr, 0);\r
+  if (comp<0) return decCanonical(result, dfl);\r
+  if (comp>0) return decCanonical(result, dfr);\r
+  return decFloatMin(result, dfl, dfr, set);\r
+  } // decFloatMinMag\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatMinus -- negate value, heeding NaNs, etc.                  */\r
+/*                                                                    */\r
+/*   result gets the canonicalized 0-df                               */\r
+/*   df     is the decFloat to minus                                  */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This has the same effect as 0-df where the exponent of the zero is */\r
+/* the same as that of df (if df is finite).                          */\r
+/* The effect is also the same as decFloatCopyNegate except that NaNs */\r
+/* are handled normally (the sign of a NaN is not affected, and an    */\r
+/* sNaN will signal), the result is canonical, and zero gets sign 0.  */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatMinus(decFloat *result, const decFloat *df,\r
+                         decContext *set) {\r
+  if (DFISNAN(df)) return decNaNs(result, df, NULL, set);\r
+  decCanonical(result, df);                       // copy and check\r
+  if (DFISZERO(df)) DFBYTE(result, 0)&=~0x80;     // turn off sign bit\r
+   else DFBYTE(result, 0)^=0x80;                  // flip sign bit\r
+  return result;\r
+  } // decFloatMinus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatMultiply -- multiply two decFloats                         */\r
+/*                                                                    */\r
+/*   result gets the result of multiplying dfl and dfr:               */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatMultiply(decFloat *result,\r
+                            const decFloat *dfl, const decFloat *dfr,\r
+                            decContext *set) {\r
+  bcdnum num;                      // for final conversion\r
+  uByte  bcdacc[DECPMAX9*18+1];    // for coefficent in BCD\r
+\r
+  if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) { // either is special?\r
+    // NaNs are handled as usual\r
+    if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+    // infinity times zero is bad\r
+    if (DFISINF(dfl) && DFISZERO(dfr)) return decInvalid(result, set);\r
+    if (DFISINF(dfr) && DFISZERO(dfl)) return decInvalid(result, set);\r
+    // both infinite; return canonical infinity with computed sign\r
+    DFWORD(result, 0)=DFWORD(dfl, 0)^DFWORD(dfr, 0); // compute sign\r
+    return decInfinity(result, result);\r
+    }\r
+\r
+  /* Here when both operands are finite */\r
+  decFiniteMultiply(&num, bcdacc, dfl, dfr);\r
+  return decFinalize(result, &num, set); // round, check, and lay out\r
+  } // decFloatMultiply\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatNextMinus -- next towards -Infinity                        */\r
+/*                                                                    */\r
+/*   result gets the next lesser decFloat                             */\r
+/*   dfl    is the decFloat to start with                             */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This is 754 nextdown; Invalid is the only status possible (from    */\r
+/* an sNaN).                                                          */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatNextMinus(decFloat *result, const decFloat *dfl,\r
+                             decContext *set) {\r
+  decFloat delta;                       // tiny increment\r
+  uInt savestat;                        // saves status\r
+  enum rounding saveround;              // .. and mode\r
+\r
+  // +Infinity is the special case\r
+  if (DFISINF(dfl) && !DFISSIGNED(dfl)) {\r
+    DFSETNMAX(result);\r
+    return result;                      // [no status to set]\r
+    }\r
+  // other cases are effected by sutracting a tiny delta -- this\r
+  // should be done in a wider format as the delta is unrepresentable\r
+  // here (but can be done with normal add if the sign of zero is\r
+  // treated carefully, because no Inexactitude is interesting);\r
+  // rounding to -Infinity then pushes the result to next below\r
+  decFloatZero(&delta);                 // set up tiny delta\r
+  DFWORD(&delta, DECWORDS-1)=1;         // coefficient=1\r
+  DFWORD(&delta, 0)=DECFLOAT_Sign;      // Sign=1 + biased exponent=0\r
+  // set up for the directional round\r
+  saveround=set->round;                 // save mode\r
+  set->round=DEC_ROUND_FLOOR;           // .. round towards -Infinity\r
+  savestat=set->status;                 // save status\r
+  decFloatAdd(result, dfl, &delta, set);\r
+  // Add rules mess up the sign when going from +Ntiny to 0\r
+  if (DFISZERO(result)) DFWORD(result, 0)^=DECFLOAT_Sign; // correct\r
+  set->status&=DEC_Invalid_operation;   // preserve only sNaN status\r
+  set->status|=savestat;                // restore pending flags\r
+  set->round=saveround;                 // .. and mode\r
+  return result;\r
+  } // decFloatNextMinus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatNextPlus -- next towards +Infinity                         */\r
+/*                                                                    */\r
+/*   result gets the next larger decFloat                             */\r
+/*   dfl    is the decFloat to start with                             */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This is 754 nextup; Invalid is the only status possible (from      */\r
+/* an sNaN).                                                          */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatNextPlus(decFloat *result, const decFloat *dfl,\r
+                            decContext *set) {\r
+  uInt savestat;                        // saves status\r
+  enum rounding saveround;              // .. and mode\r
+  decFloat delta;                       // tiny increment\r
+\r
+  // -Infinity is the special case\r
+  if (DFISINF(dfl) && DFISSIGNED(dfl)) {\r
+    DFSETNMAX(result);\r
+    DFWORD(result, 0)|=DECFLOAT_Sign;   // make negative\r
+    return result;                      // [no status to set]\r
+    }\r
+  // other cases are effected by sutracting a tiny delta -- this\r
+  // should be done in a wider format as the delta is unrepresentable\r
+  // here (but can be done with normal add if the sign of zero is\r
+  // treated carefully, because no Inexactitude is interesting);\r
+  // rounding to +Infinity then pushes the result to next above\r
+  decFloatZero(&delta);                 // set up tiny delta\r
+  DFWORD(&delta, DECWORDS-1)=1;         // coefficient=1\r
+  DFWORD(&delta, 0)=0;                  // Sign=0 + biased exponent=0\r
+  // set up for the directional round\r
+  saveround=set->round;                 // save mode\r
+  set->round=DEC_ROUND_CEILING;         // .. round towards +Infinity\r
+  savestat=set->status;                 // save status\r
+  decFloatAdd(result, dfl, &delta, set);\r
+  // Add rules mess up the sign when going from -Ntiny to -0\r
+  if (DFISZERO(result)) DFWORD(result, 0)^=DECFLOAT_Sign; // correct\r
+  set->status&=DEC_Invalid_operation;   // preserve only sNaN status\r
+  set->status|=savestat;                // restore pending flags\r
+  set->round=saveround;                 // .. and mode\r
+  return result;\r
+  } // decFloatNextPlus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatNextToward -- next towards a decFloat                      */\r
+/*                                                                    */\r
+/*   result gets the next decFloat                                    */\r
+/*   dfl    is the decFloat to start with                             */\r
+/*   dfr    is the decFloat to move toward                            */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This is 754-1985 nextafter, as modified during revision (dropped   */\r
+/* from 754-2008); status may be set unless the result is a normal    */\r
+/* number.                                                            */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatNextToward(decFloat *result,\r
+                              const decFloat *dfl, const decFloat *dfr,\r
+                              decContext *set) {\r
+  decFloat delta;                       // tiny increment or decrement\r
+  decFloat pointone;                    // 1e-1\r
+  uInt  savestat;                       // saves status\r
+  enum  rounding saveround;             // .. and mode\r
+  uInt  deltatop;                       // top word for delta\r
+  Int   comp;                           // work\r
+\r
+  if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+  // Both are numeric, so Invalid no longer a possibility\r
+  comp=decNumCompare(dfl, dfr, 0);\r
+  if (comp==0) return decFloatCopySign(result, dfl, dfr); // equal\r
+  // unequal; do NextPlus or NextMinus but with different status rules\r
+\r
+  if (comp<0) { // lhs<rhs, do NextPlus, see above for commentary\r
+    if (DFISINF(dfl) && DFISSIGNED(dfl)) {   // -Infinity special case\r
+      DFSETNMAX(result);\r
+      DFWORD(result, 0)|=DECFLOAT_Sign;\r
+      return result;\r
+      }\r
+    saveround=set->round;                    // save mode\r
+    set->round=DEC_ROUND_CEILING;            // .. round towards +Infinity\r
+    deltatop=0;                              // positive delta\r
+    }\r
+   else { // lhs>rhs, do NextMinus, see above for commentary\r
+    if (DFISINF(dfl) && !DFISSIGNED(dfl)) {  // +Infinity special case\r
+      DFSETNMAX(result);\r
+      return result;\r
+      }\r
+    saveround=set->round;                    // save mode\r
+    set->round=DEC_ROUND_FLOOR;              // .. round towards -Infinity\r
+    deltatop=DECFLOAT_Sign;                  // negative delta\r
+    }\r
+  savestat=set->status;                      // save status\r
+  // Here, Inexact is needed where appropriate (and hence Underflow,\r
+  // etc.).  Therefore the tiny delta which is otherwise\r
+  // unrepresentable (see NextPlus and NextMinus) is constructed\r
+  // using the multiplication of FMA.\r
+  decFloatZero(&delta);                 // set up tiny delta\r
+  DFWORD(&delta, DECWORDS-1)=1;         // coefficient=1\r
+  DFWORD(&delta, 0)=deltatop;           // Sign + biased exponent=0\r
+  decFloatFromString(&pointone, "1E-1", set); // set up multiplier\r
+  decFloatFMA(result, &delta, &pointone, dfl, set);\r
+  // [Delta is truly tiny, so no need to correct sign of zero]\r
+  // use new status unless the result is normal\r
+  if (decFloatIsNormal(result)) set->status=savestat; // else goes forward\r
+  set->round=saveround;                 // restore mode\r
+  return result;\r
+  } // decFloatNextToward\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatOr -- logical digitwise OR of two decFloats                */\r
+/*                                                                    */\r
+/*   result gets the result of ORing dfl and dfr                      */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result, which will be canonical with sign=0              */\r
+/*                                                                    */\r
+/* The operands must be positive, finite with exponent q=0, and       */\r
+/* comprise just zeros and ones; if not, Invalid operation results.   */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatOr(decFloat *result,\r
+                       const decFloat *dfl, const decFloat *dfr,\r
+                       decContext *set) {\r
+  if (!DFISUINT01(dfl) || !DFISUINT01(dfr)\r
+   || !DFISCC01(dfl)   || !DFISCC01(dfr)) return decInvalid(result, set);\r
+  // the operands are positive finite integers (q=0) with just 0s and 1s\r
+  #if DOUBLE\r
+   DFWORD(result, 0)=ZEROWORD\r
+                   |((DFWORD(dfl, 0) | DFWORD(dfr, 0))&0x04009124);\r
+   DFWORD(result, 1)=(DFWORD(dfl, 1) | DFWORD(dfr, 1))&0x49124491;\r
+  #elif QUAD\r
+   DFWORD(result, 0)=ZEROWORD\r
+                   |((DFWORD(dfl, 0) | DFWORD(dfr, 0))&0x04000912);\r
+   DFWORD(result, 1)=(DFWORD(dfl, 1) | DFWORD(dfr, 1))&0x44912449;\r
+   DFWORD(result, 2)=(DFWORD(dfl, 2) | DFWORD(dfr, 2))&0x12449124;\r
+   DFWORD(result, 3)=(DFWORD(dfl, 3) | DFWORD(dfr, 3))&0x49124491;\r
+  #endif\r
+  return result;\r
+  } // decFloatOr\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatPlus -- add value to 0, heeding NaNs, etc.                 */\r
+/*                                                                    */\r
+/*   result gets the canonicalized 0+df                               */\r
+/*   df     is the decFloat to plus                                   */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This has the same effect as 0+df where the exponent of the zero is */\r
+/* the same as that of df (if df is finite).                          */\r
+/* The effect is also the same as decFloatCopy except that NaNs       */\r
+/* are handled normally (the sign of a NaN is not affected, and an    */\r
+/* sNaN will signal), the result is canonical, and zero gets sign 0.  */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatPlus(decFloat *result, const decFloat *df,\r
+                        decContext *set) {\r
+  if (DFISNAN(df)) return decNaNs(result, df, NULL, set);\r
+  decCanonical(result, df);                       // copy and check\r
+  if (DFISZERO(df)) DFBYTE(result, 0)&=~0x80;     // turn off sign bit\r
+  return result;\r
+  } // decFloatPlus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatQuantize -- quantize a decFloat                            */\r
+/*                                                                    */\r
+/*   result gets the result of quantizing dfl to match dfr            */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs), which sets the exponent     */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* Unless there is an error or the result is infinite, the exponent   */\r
+/* of result is guaranteed to be the same as that of dfr.             */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatQuantize(decFloat *result,\r
+                            const decFloat *dfl, const decFloat *dfr,\r
+                            decContext *set) {\r
+  Int   explb, exprb;         // left and right biased exponents\r
+  uByte *ulsd;                // local LSD pointer\r
+  uByte *ub, *uc;             // work\r
+  Int   drop;                 // ..\r
+  uInt  dpd;                  // ..\r
+  uInt  encode;               // encoding accumulator\r
+  uInt  sourhil, sourhir;     // top words from source decFloats\r
+  uInt  uiwork;               // for macros\r
+  #if QUAD\r
+  uShort uswork;              // ..\r
+  #endif\r
+  // the following buffer holds the coefficient for manipulation\r
+  uByte buf[4+DECPMAX*3+2*QUAD];   // + space for zeros to left or right\r
+  #if DECTRACE\r
+  bcdnum num;                      // for trace displays\r
+  #endif\r
+\r
+  /* Start decoding the arguments */\r
+  sourhil=DFWORD(dfl, 0);          // LHS top word\r
+  explb=DECCOMBEXP[sourhil>>26];   // get exponent high bits (in place)\r
+  sourhir=DFWORD(dfr, 0);          // RHS top word\r
+  exprb=DECCOMBEXP[sourhir>>26];\r
+\r
+  if (EXPISSPECIAL(explb | exprb)) { // either is special?\r
+    // NaNs are handled as usual\r
+    if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+    // one infinity but not both is bad\r
+    if (DFISINF(dfl)!=DFISINF(dfr)) return decInvalid(result, set);\r
+    // both infinite; return canonical infinity with sign of LHS\r
+    return decInfinity(result, dfl);\r
+    }\r
+\r
+  /* Here when both arguments are finite */\r
+  // complete extraction of the exponents [no need to unbias]\r
+  explb+=GETECON(dfl);             // + continuation\r
+  exprb+=GETECON(dfr);             // ..\r
+\r
+  // calculate the number of digits to drop from the coefficient\r
+  drop=exprb-explb;                // 0 if nothing to do\r
+  if (drop==0) return decCanonical(result, dfl); // return canonical\r
+\r
+  // the coefficient is needed; lay it out into buf, offset so zeros\r
+  // can be added before or after as needed -- an extra heading is\r
+  // added so can safely pad Quad DECPMAX-1 zeros to the left by\r
+  // fours\r
+  #define BUFOFF (buf+4+DECPMAX)\r
+  GETCOEFF(dfl, BUFOFF);           // decode from decFloat\r
+  // [now the msd is at BUFOFF and the lsd is at BUFOFF+DECPMAX-1]\r
+\r
+  #if DECTRACE\r
+  num.msd=BUFOFF;\r
+  num.lsd=BUFOFF+DECPMAX-1;\r
+  num.exponent=explb-DECBIAS;\r
+  num.sign=sourhil & DECFLOAT_Sign;\r
+  decShowNum(&num, "dfl");\r
+  #endif\r
+\r
+  if (drop>0) {                         // [most common case]\r
+    // (this code is very similar to that in decFloatFinalize, but\r
+    // has many differences so is duplicated here -- so any changes\r
+    // may need to be made there, too)\r
+    uByte *roundat;                          // -> re-round digit\r
+    uByte reround;                           // reround value\r
+    // printf("Rounding; drop=%ld\n", (LI)drop);\r
+\r
+    // there is at least one zero needed to the left, in all but one\r
+    // exceptional (all-nines) case, so place four zeros now; this is\r
+    // needed almost always and makes rounding all-nines by fours safe\r
+    UBFROMUI(BUFOFF-4, 0);\r
+\r
+    // Three cases here:\r
+    //   1. new LSD is in coefficient (almost always)\r
+    //   2. new LSD is digit to left of coefficient (so MSD is\r
+    //      round-for-reround digit)\r
+    //   3. new LSD is to left of case 2 (whole coefficient is sticky)\r
+    // Note that leading zeros can safely be treated as useful digits\r
+\r
+    // [duplicate check-stickies code to save a test]\r
+    // [by-digit check for stickies as runs of zeros are rare]\r
+    if (drop<DECPMAX) {                      // NB lengths not addresses\r
+      roundat=BUFOFF+DECPMAX-drop;\r
+      reround=*roundat;\r
+      for (ub=roundat+1; ub<BUFOFF+DECPMAX; ub++) {\r
+        if (*ub!=0) {                        // non-zero to be discarded\r
+          reround=DECSTICKYTAB[reround];     // apply sticky bit\r
+          break;                             // [remainder don't-care]\r
+          }\r
+        } // check stickies\r
+      ulsd=roundat-1;                        // set LSD\r
+      }\r
+     else {                                  // edge case\r
+      if (drop==DECPMAX) {\r
+        roundat=BUFOFF;\r
+        reround=*roundat;\r
+        }\r
+       else {\r
+        roundat=BUFOFF-1;\r
+        reround=0;\r
+        }\r
+      for (ub=roundat+1; ub<BUFOFF+DECPMAX; ub++) {\r
+        if (*ub!=0) {                        // non-zero to be discarded\r
+          reround=DECSTICKYTAB[reround];     // apply sticky bit\r
+          break;                             // [remainder don't-care]\r
+          }\r
+        } // check stickies\r
+      *BUFOFF=0;                             // make a coefficient of 0\r
+      ulsd=BUFOFF;                           // .. at the MSD place\r
+      }\r
+\r
+    if (reround!=0) {                        // discarding non-zero\r
+      uInt bump=0;\r
+      set->status|=DEC_Inexact;\r
+\r
+      // next decide whether to increment the coefficient\r
+      if (set->round==DEC_ROUND_HALF_EVEN) { // fastpath slowest case\r
+        if (reround>5) bump=1;               // >0.5 goes up\r
+         else if (reround==5)                // exactly 0.5000 ..\r
+          bump=*ulsd & 0x01;                 // .. up iff [new] lsd is odd\r
+        } // r-h-e\r
+       else switch (set->round) {\r
+        case DEC_ROUND_DOWN: {\r
+          // no change\r
+          break;} // r-d\r
+        case DEC_ROUND_HALF_DOWN: {\r
+          if (reround>5) bump=1;\r
+          break;} // r-h-d\r
+        case DEC_ROUND_HALF_UP: {\r
+          if (reround>=5) bump=1;\r
+          break;} // r-h-u\r
+        case DEC_ROUND_UP: {\r
+          if (reround>0) bump=1;\r
+          break;} // r-u\r
+        case DEC_ROUND_CEILING: {\r
+          // same as _UP for positive numbers, and as _DOWN for negatives\r
+          if (!(sourhil&DECFLOAT_Sign) && reround>0) bump=1;\r
+          break;} // r-c\r
+        case DEC_ROUND_FLOOR: {\r
+          // same as _UP for negative numbers, and as _DOWN for positive\r
+          // [negative reround cannot occur on 0]\r
+          if (sourhil&DECFLOAT_Sign && reround>0) bump=1;\r
+          break;} // r-f\r
+        case DEC_ROUND_05UP: {\r
+          if (reround>0) { // anything out there is 'sticky'\r
+            // bump iff lsd=0 or 5; this cannot carry so it could be\r
+            // effected immediately with no bump -- but the code\r
+            // is clearer if this is done the same way as the others\r
+            if (*ulsd==0 || *ulsd==5) bump=1;\r
+            }\r
+          break;} // r-r\r
+        default: {      // e.g., DEC_ROUND_MAX\r
+          set->status|=DEC_Invalid_context;\r
+          #if DECCHECK\r
+          printf("Unknown rounding mode: %ld\n", (LI)set->round);\r
+          #endif\r
+          break;}\r
+        } // switch (not r-h-e)\r
+      // printf("ReRound: %ld  bump: %ld\n", (LI)reround, (LI)bump);\r
+\r
+      if (bump!=0) {                         // need increment\r
+        // increment the coefficient; this could give 1000... (after\r
+        // the all nines case)\r
+        ub=ulsd;\r
+        for (; UBTOUI(ub-3)==0x09090909; ub-=4) UBFROMUI(ub-3, 0);\r
+        // now at most 3 digits left to non-9 (usually just the one)\r
+        for (; *ub==9; ub--) *ub=0;\r
+        *ub+=1;\r
+        // [the all-nines case will have carried one digit to the\r
+        // left of the original MSD -- just where it is needed]\r
+        } // bump needed\r
+      } // inexact rounding\r
+\r
+    // now clear zeros to the left so exactly DECPMAX digits will be\r
+    // available in the coefficent -- the first word to the left was\r
+    // cleared earlier for safe carry; now add any more needed\r
+    if (drop>4) {\r
+      UBFROMUI(BUFOFF-8, 0);                 // must be at least 5\r
+      for (uc=BUFOFF-12; uc>ulsd-DECPMAX-3; uc-=4) UBFROMUI(uc, 0);\r
+      }\r
+    } // need round (drop>0)\r
+\r
+   else { // drop<0; padding with -drop digits is needed\r
+    // This is the case where an error can occur if the padded\r
+    // coefficient will not fit; checking for this can be done in the\r
+    // same loop as padding for zeros if the no-hope and zero cases\r
+    // are checked first\r
+    if (-drop>DECPMAX-1) {                   // cannot fit unless 0\r
+      if (!ISCOEFFZERO(BUFOFF)) return decInvalid(result, set);\r
+      // a zero can have any exponent; just drop through and use it\r
+      ulsd=BUFOFF+DECPMAX-1;\r
+      }\r
+     else { // padding will fit (but may still be too long)\r
+      // final-word mask depends on endianess\r
+      #if DECLITEND\r
+      static const uInt dmask[]={0, 0x000000ff, 0x0000ffff, 0x00ffffff};\r
+      #else\r
+      static const uInt dmask[]={0, 0xff000000, 0xffff0000, 0xffffff00};\r
+      #endif\r
+      // note that here zeros to the right are added by fours, so in\r
+      // the Quad case this could write 36 zeros if the coefficient has\r
+      // fewer than three significant digits (hence the +2*QUAD for buf)\r
+      for (uc=BUFOFF+DECPMAX;; uc+=4) {\r
+        UBFROMUI(uc, 0);\r
+        if (UBTOUI(uc-DECPMAX)!=0) {              // could be bad\r
+          // if all four digits should be zero, definitely bad\r
+          if (uc<=BUFOFF+DECPMAX+(-drop)-4)\r
+            return decInvalid(result, set);\r
+          // must be a 1- to 3-digit sequence; check more carefully\r
+          if ((UBTOUI(uc-DECPMAX)&dmask[(-drop)%4])!=0)\r
+            return decInvalid(result, set);\r
+          break;    // no need for loop end test\r
+          }\r
+        if (uc>=BUFOFF+DECPMAX+(-drop)-4) break;  // done\r
+        }\r
+      ulsd=BUFOFF+DECPMAX+(-drop)-1;\r
+      } // pad and check leading zeros\r
+    } // drop<0\r
+\r
+  #if DECTRACE\r
+  num.msd=ulsd-DECPMAX+1;\r
+  num.lsd=ulsd;\r
+  num.exponent=explb-DECBIAS;\r
+  num.sign=sourhil & DECFLOAT_Sign;\r
+  decShowNum(&num, "res");\r
+  #endif\r
+\r
+  /*------------------------------------------------------------------*/\r
+  /* At this point the result is DECPMAX digits, ending at ulsd, so   */\r
+  /* fits the encoding exactly; there is no possibility of error      */\r
+  /*------------------------------------------------------------------*/\r
+  encode=((exprb>>DECECONL)<<4) + *(ulsd-DECPMAX+1); // make index\r
+  encode=DECCOMBFROM[encode];                // indexed by (0-2)*16+msd\r
+  // the exponent continuation can be extracted from the original RHS\r
+  encode|=sourhir & ECONMASK;\r
+  encode|=sourhil&DECFLOAT_Sign;             // add the sign from LHS\r
+\r
+  // finally encode the coefficient\r
+  // private macro to encode a declet; this version can be used\r
+  // because all coefficient digits exist\r
+  #define getDPD3q(dpd, n) ub=ulsd-(3*(n))-2;                   \\r
+    dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)];\r
+\r
+  #if DOUBLE\r
+    getDPD3q(dpd, 4); encode|=dpd<<8;\r
+    getDPD3q(dpd, 3); encode|=dpd>>2;\r
+    DFWORD(result, 0)=encode;\r
+    encode=dpd<<30;\r
+    getDPD3q(dpd, 2); encode|=dpd<<20;\r
+    getDPD3q(dpd, 1); encode|=dpd<<10;\r
+    getDPD3q(dpd, 0); encode|=dpd;\r
+    DFWORD(result, 1)=encode;\r
+\r
+  #elif QUAD\r
+    getDPD3q(dpd,10); encode|=dpd<<4;\r
+    getDPD3q(dpd, 9); encode|=dpd>>6;\r
+    DFWORD(result, 0)=encode;\r
+    encode=dpd<<26;\r
+    getDPD3q(dpd, 8); encode|=dpd<<16;\r
+    getDPD3q(dpd, 7); encode|=dpd<<6;\r
+    getDPD3q(dpd, 6); encode|=dpd>>4;\r
+    DFWORD(result, 1)=encode;\r
+    encode=dpd<<28;\r
+    getDPD3q(dpd, 5); encode|=dpd<<18;\r
+    getDPD3q(dpd, 4); encode|=dpd<<8;\r
+    getDPD3q(dpd, 3); encode|=dpd>>2;\r
+    DFWORD(result, 2)=encode;\r
+    encode=dpd<<30;\r
+    getDPD3q(dpd, 2); encode|=dpd<<20;\r
+    getDPD3q(dpd, 1); encode|=dpd<<10;\r
+    getDPD3q(dpd, 0); encode|=dpd;\r
+    DFWORD(result, 3)=encode;\r
+  #endif\r
+  return result;\r
+  } // decFloatQuantize\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatReduce -- reduce finite coefficient to minimum length      */\r
+/*                                                                    */\r
+/*   result gets the reduced decFloat                                 */\r
+/*   df     is the source decFloat                                    */\r
+/*   set    is the context                                            */\r
+/*   returns result, which will be canonical                          */\r
+/*                                                                    */\r
+/* This removes all possible trailing zeros from the coefficient;     */\r
+/* some may remain when the number is very close to Nmax.             */\r
+/* Special values are unchanged and no status is set unless df=sNaN.  */\r
+/* Reduced zero has an exponent q=0.                                  */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatReduce(decFloat *result, const decFloat *df,\r
+                          decContext *set) {\r
+  bcdnum num;                           // work\r
+  uByte buf[DECPMAX], *ub;              // coefficient and pointer\r
+  if (df!=result) *result=*df;          // copy, if needed\r
+  if (DFISNAN(df)) return decNaNs(result, df, NULL, set);   // sNaN\r
+  // zeros and infinites propagate too\r
+  if (DFISINF(df)) return decInfinity(result, df);     // canonical\r
+  if (DFISZERO(df)) {\r
+    uInt sign=DFWORD(df, 0)&DECFLOAT_Sign;\r
+    decFloatZero(result);\r
+    DFWORD(result, 0)|=sign;\r
+    return result;                      // exponent dropped, sign OK\r
+    }\r
+  // non-zero finite\r
+  GETCOEFF(df, buf);\r
+  ub=buf+DECPMAX-1;                     // -> lsd\r
+  if (*ub) return result;               // no trailing zeros\r
+  for (ub--; *ub==0;) ub--;             // terminates because non-zero\r
+  // *ub is the first non-zero from the right\r
+  num.sign=DFWORD(df, 0)&DECFLOAT_Sign; // set up number...\r
+  num.exponent=GETEXPUN(df)+(Int)(buf+DECPMAX-1-ub); // adjusted exponent\r
+  num.msd=buf;\r
+  num.lsd=ub;\r
+  return decFinalize(result, &num, set);\r
+  } // decFloatReduce\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatRemainder -- integer divide and return remainder           */\r
+/*                                                                    */\r
+/*   result gets the remainder of dividing dfl by dfr:                */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatRemainder(decFloat *result,\r
+                             const decFloat *dfl, const decFloat *dfr,\r
+                             decContext *set) {\r
+  return decDivide(result, dfl, dfr, set, REMAINDER);\r
+  } // decFloatRemainder\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatRemainderNear -- integer divide to nearest and remainder   */\r
+/*                                                                    */\r
+/*   result gets the remainder of dividing dfl by dfr:                */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This is the IEEE remainder, where the nearest integer is used.     */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatRemainderNear(decFloat *result,\r
+                             const decFloat *dfl, const decFloat *dfr,\r
+                             decContext *set) {\r
+  return decDivide(result, dfl, dfr, set, REMNEAR);\r
+  } // decFloatRemainderNear\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatRotate -- rotate the coefficient of a decFloat left/right  */\r
+/*                                                                    */\r
+/*   result gets the result of rotating dfl                           */\r
+/*   dfl    is the source decFloat to rotate                          */\r
+/*   dfr    is the count of digits to rotate, an integer (with q=0)   */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* The digits of the coefficient of dfl are rotated to the left (if   */\r
+/* dfr is positive) or to the right (if dfr is negative) without      */\r
+/* adjusting the exponent or the sign of dfl.                         */\r
+/*                                                                    */\r
+/* dfr must be in the range -DECPMAX through +DECPMAX.                */\r
+/* NaNs are propagated as usual.  An infinite dfl is unaffected (but  */\r
+/* dfr must be valid).  No status is set unless dfr is invalid or an  */\r
+/* operand is an sNaN.  The result is canonical.                      */\r
+/* ------------------------------------------------------------------ */\r
+#define PHALF (ROUNDUP(DECPMAX/2, 4))   // half length, rounded up\r
+decFloat * decFloatRotate(decFloat *result,\r
+                         const decFloat *dfl, const decFloat *dfr,\r
+                         decContext *set) {\r
+  Int rotate;                           // dfr as an Int\r
+  uByte buf[DECPMAX+PHALF];             // coefficient + half\r
+  uInt digits, savestat;                // work\r
+  bcdnum num;                           // ..\r
+  uByte *ub;                            // ..\r
+\r
+  if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+  if (!DFISINT(dfr)) return decInvalid(result, set);\r
+  digits=decFloatDigits(dfr);                    // calculate digits\r
+  if (digits>2) return decInvalid(result, set);  // definitely out of range\r
+  rotate=DPD2BIN[DFWORD(dfr, DECWORDS-1)&0x3ff]; // is in bottom declet\r
+  if (rotate>DECPMAX) return decInvalid(result, set); // too big\r
+  // [from here on no error or status change is possible]\r
+  if (DFISINF(dfl)) return decInfinity(result, dfl);  // canonical\r
+  // handle no-rotate cases\r
+  if (rotate==0 || rotate==DECPMAX) return decCanonical(result, dfl);\r
+  // a real rotate is needed: 0 < rotate < DECPMAX\r
+  // reduce the rotation to no more than half to reduce copying later\r
+  // (for QUAD in fact half + 2 digits)\r
+  if (DFISSIGNED(dfr)) rotate=-rotate;\r
+  if (abs(rotate)>PHALF) {\r
+    if (rotate<0) rotate=DECPMAX+rotate;\r
+     else rotate=rotate-DECPMAX;\r
+    }\r
+  // now lay out the coefficient, leaving room to the right or the\r
+  // left depending on the direction of rotation\r
+  ub=buf;\r
+  if (rotate<0) ub+=PHALF;    // rotate right, so space to left\r
+  GETCOEFF(dfl, ub);\r
+  // copy half the digits to left or right, and set num.msd\r
+  if (rotate<0) {\r
+    memcpy(buf, buf+DECPMAX, PHALF);\r
+    num.msd=buf+PHALF+rotate;\r
+    }\r
+   else {\r
+    memcpy(buf+DECPMAX, buf, PHALF);\r
+    num.msd=buf+rotate;\r
+    }\r
+  // fill in rest of num\r
+  num.lsd=num.msd+DECPMAX-1;\r
+  num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;\r
+  num.exponent=GETEXPUN(dfl);\r
+  savestat=set->status;                 // record\r
+  decFinalize(result, &num, set);\r
+  set->status=savestat;                 // restore\r
+  return result;\r
+  } // decFloatRotate\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatSameQuantum -- test decFloats for same quantum             */\r
+/*                                                                    */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   returns 1 if the operands have the same quantum, 0 otherwise     */\r
+/*                                                                    */\r
+/* No error is possible and no status results.                        */\r
+/* ------------------------------------------------------------------ */\r
+uInt decFloatSameQuantum(const decFloat *dfl, const decFloat *dfr) {\r
+  if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) {\r
+    if (DFISNAN(dfl) && DFISNAN(dfr)) return 1;\r
+    if (DFISINF(dfl) && DFISINF(dfr)) return 1;\r
+    return 0;  // any other special mixture gives false\r
+    }\r
+  if (GETEXP(dfl)==GETEXP(dfr)) return 1; // biased exponents match\r
+  return 0;\r
+  } // decFloatSameQuantum\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatScaleB -- multiply by a power of 10, as per 754            */\r
+/*                                                                    */\r
+/*   result gets the result of the operation                          */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs), am integer (with q=0)       */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* This computes result=dfl x 10**dfr where dfr is an integer in the  */\r
+/* range +/-2*(emax+pmax), typically resulting from LogB.             */\r
+/* Underflow and Overflow (with Inexact) may occur.  NaNs propagate   */\r
+/* as usual.                                                          */\r
+/* ------------------------------------------------------------------ */\r
+#define SCALEBMAX 2*(DECEMAX+DECPMAX)   // D=800, Q=12356\r
+decFloat * decFloatScaleB(decFloat *result,\r
+                          const decFloat *dfl, const decFloat *dfr,\r
+                          decContext *set) {\r
+  uInt digits;                          // work\r
+  Int  expr;                            // dfr as an Int\r
+\r
+  if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+  if (!DFISINT(dfr)) return decInvalid(result, set);\r
+  digits=decFloatDigits(dfr);                // calculate digits\r
+\r
+  #if DOUBLE\r
+  if (digits>3) return decInvalid(result, set);   // definitely out of range\r
+  expr=DPD2BIN[DFWORD(dfr, 1)&0x3ff];             // must be in bottom declet\r
+  #elif QUAD\r
+  if (digits>5) return decInvalid(result, set);   // definitely out of range\r
+  expr=DPD2BIN[DFWORD(dfr, 3)&0x3ff]              // in bottom 2 declets ..\r
+      +DPD2BIN[(DFWORD(dfr, 3)>>10)&0x3ff]*1000;  // ..\r
+  #endif\r
+  if (expr>SCALEBMAX) return decInvalid(result, set);  // oops\r
+  // [from now on no error possible]\r
+  if (DFISINF(dfl)) return decInfinity(result, dfl);   // canonical\r
+  if (DFISSIGNED(dfr)) expr=-expr;\r
+  // dfl is finite and expr is valid\r
+  *result=*dfl;                              // copy to target\r
+  return decFloatSetExponent(result, set, GETEXPUN(result)+expr);\r
+  } // decFloatScaleB\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatShift -- shift the coefficient of a decFloat left or right */\r
+/*                                                                    */\r
+/*   result gets the result of shifting dfl                           */\r
+/*   dfl    is the source decFloat to shift                           */\r
+/*   dfr    is the count of digits to shift, an integer (with q=0)    */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* The digits of the coefficient of dfl are shifted to the left (if   */\r
+/* dfr is positive) or to the right (if dfr is negative) without      */\r
+/* adjusting the exponent or the sign of dfl.                         */\r
+/*                                                                    */\r
+/* dfr must be in the range -DECPMAX through +DECPMAX.                */\r
+/* NaNs are propagated as usual.  An infinite dfl is unaffected (but  */\r
+/* dfr must be valid).  No status is set unless dfr is invalid or an  */\r
+/* operand is an sNaN.  The result is canonical.                      */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatShift(decFloat *result,\r
+                         const decFloat *dfl, const decFloat *dfr,\r
+                         decContext *set) {\r
+  Int    shift;                         // dfr as an Int\r
+  uByte  buf[DECPMAX*2];                // coefficient + padding\r
+  uInt   digits, savestat;              // work\r
+  bcdnum num;                           // ..\r
+  uInt   uiwork;                        // for macros\r
+\r
+  if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);\r
+  if (!DFISINT(dfr)) return decInvalid(result, set);\r
+  digits=decFloatDigits(dfr);                     // calculate digits\r
+  if (digits>2) return decInvalid(result, set);   // definitely out of range\r
+  shift=DPD2BIN[DFWORD(dfr, DECWORDS-1)&0x3ff];   // is in bottom declet\r
+  if (shift>DECPMAX) return decInvalid(result, set);   // too big\r
+  // [from here on no error or status change is possible]\r
+\r
+  if (DFISINF(dfl)) return decInfinity(result, dfl); // canonical\r
+  // handle no-shift and all-shift (clear to zero) cases\r
+  if (shift==0) return decCanonical(result, dfl);\r
+  if (shift==DECPMAX) {                      // zero with sign\r
+    uByte sign=(uByte)(DFBYTE(dfl, 0)&0x80); // save sign bit\r
+    decFloatZero(result);                    // make +0\r
+    DFBYTE(result, 0)=(uByte)(DFBYTE(result, 0)|sign); // and set sign\r
+    // [cannot safely use CopySign]\r
+    return result;\r
+    }\r
+  // a real shift is needed: 0 < shift < DECPMAX\r
+  num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;\r
+  num.exponent=GETEXPUN(dfl);\r
+  num.msd=buf;\r
+  GETCOEFF(dfl, buf);\r
+  if (DFISSIGNED(dfr)) { // shift right\r
+    // edge cases are taken care of, so this is easy\r
+    num.lsd=buf+DECPMAX-shift-1;\r
+    }\r
+   else { // shift left -- zero padding needed to right\r
+    UBFROMUI(buf+DECPMAX, 0);           // 8 will handle most cases\r
+    UBFROMUI(buf+DECPMAX+4, 0);         // ..\r
+    if (shift>8) memset(buf+DECPMAX+8, 0, 8+QUAD*18); // all other cases\r
+    num.msd+=shift;\r
+    num.lsd=num.msd+DECPMAX-1;\r
+    }\r
+  savestat=set->status;                 // record\r
+  decFinalize(result, &num, set);\r
+  set->status=savestat;                 // restore\r
+  return result;\r
+  } // decFloatShift\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatSubtract -- subtract a decFloat from another               */\r
+/*                                                                    */\r
+/*   result gets the result of subtracting dfr from dfl:              */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatSubtract(decFloat *result,\r
+                            const decFloat *dfl, const decFloat *dfr,\r
+                            decContext *set) {\r
+  decFloat temp;\r
+  // NaNs must propagate without sign change\r
+  if (DFISNAN(dfr)) return decFloatAdd(result, dfl, dfr, set);\r
+  temp=*dfr;                                   // make a copy\r
+  DFBYTE(&temp, 0)^=0x80;                      // flip sign\r
+  return decFloatAdd(result, dfl, &temp, set); // and add to the lhs\r
+  } // decFloatSubtract\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatToInt -- round to 32-bit binary integer (4 flavours)       */\r
+/*                                                                    */\r
+/*   df    is the decFloat to round                                   */\r
+/*   set   is the context                                             */\r
+/*   round is the rounding mode to use                                */\r
+/*   returns a uInt or an Int, rounded according to the name          */\r
+/*                                                                    */\r
+/* Invalid will always be signaled if df is a NaN, is Infinite, or is */\r
+/* outside the range of the target; Inexact will not be signaled for  */\r
+/* simple rounding unless 'Exact' appears in the name.                */\r
+/* ------------------------------------------------------------------ */\r
+uInt decFloatToUInt32(const decFloat *df, decContext *set,\r
+                      enum rounding round) {\r
+  return decToInt32(df, set, round, 0, 1);}\r
+\r
+uInt decFloatToUInt32Exact(const decFloat *df, decContext *set,\r
+                           enum rounding round) {\r
+  return decToInt32(df, set, round, 1, 1);}\r
+\r
+Int decFloatToInt32(const decFloat *df, decContext *set,\r
+                    enum rounding round) {\r
+  return (Int)decToInt32(df, set, round, 0, 0);}\r
+\r
+Int decFloatToInt32Exact(const decFloat *df, decContext *set,\r
+                         enum rounding round) {\r
+  return (Int)decToInt32(df, set, round, 1, 0);}\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatToIntegral -- round to integral value (two flavours)       */\r
+/*                                                                    */\r
+/*   result gets the result                                           */\r
+/*   df     is the decFloat to round                                  */\r
+/*   set    is the context                                            */\r
+/*   round  is the rounding mode to use                               */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* No exceptions, even Inexact, are raised except for sNaN input, or  */\r
+/* if 'Exact' appears in the name.                                    */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatToIntegralValue(decFloat *result, const decFloat *df,\r
+                                   decContext *set, enum rounding round) {\r
+  return decToIntegral(result, df, set, round, 0);}\r
+\r
+decFloat * decFloatToIntegralExact(decFloat *result, const decFloat *df,\r
+                                   decContext *set) {\r
+  return decToIntegral(result, df, set, set->round, 1);}\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatXor -- logical digitwise XOR of two decFloats              */\r
+/*                                                                    */\r
+/*   result gets the result of XORing dfl and dfr                     */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs)                              */\r
+/*   set    is the context                                            */\r
+/*   returns result, which will be canonical with sign=0              */\r
+/*                                                                    */\r
+/* The operands must be positive, finite with exponent q=0, and       */\r
+/* comprise just zeros and ones; if not, Invalid operation results.   */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatXor(decFloat *result,\r
+                       const decFloat *dfl, const decFloat *dfr,\r
+                       decContext *set) {\r
+  if (!DFISUINT01(dfl) || !DFISUINT01(dfr)\r
+   || !DFISCC01(dfl)   || !DFISCC01(dfr)) return decInvalid(result, set);\r
+  // the operands are positive finite integers (q=0) with just 0s and 1s\r
+  #if DOUBLE\r
+   DFWORD(result, 0)=ZEROWORD\r
+                   |((DFWORD(dfl, 0) ^ DFWORD(dfr, 0))&0x04009124);\r
+   DFWORD(result, 1)=(DFWORD(dfl, 1) ^ DFWORD(dfr, 1))&0x49124491;\r
+  #elif QUAD\r
+   DFWORD(result, 0)=ZEROWORD\r
+                   |((DFWORD(dfl, 0) ^ DFWORD(dfr, 0))&0x04000912);\r
+   DFWORD(result, 1)=(DFWORD(dfl, 1) ^ DFWORD(dfr, 1))&0x44912449;\r
+   DFWORD(result, 2)=(DFWORD(dfl, 2) ^ DFWORD(dfr, 2))&0x12449124;\r
+   DFWORD(result, 3)=(DFWORD(dfl, 3) ^ DFWORD(dfr, 3))&0x49124491;\r
+  #endif\r
+  return result;\r
+  } // decFloatXor\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decInvalid -- set Invalid_operation result                         */\r
+/*                                                                    */\r
+/*   result gets a canonical NaN                                      */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* status has Invalid_operation added                                 */\r
+/* ------------------------------------------------------------------ */\r
+static decFloat *decInvalid(decFloat *result, decContext *set) {\r
+  decFloatZero(result);\r
+  DFWORD(result, 0)=DECFLOAT_qNaN;\r
+  set->status|=DEC_Invalid_operation;\r
+  return result;\r
+  } // decInvalid\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decInfinity -- set canonical Infinity with sign from a decFloat    */\r
+/*                                                                    */\r
+/*   result gets a canonical Infinity                                 */\r
+/*   df     is source decFloat (only the sign is used)                */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* df may be the same as result                                       */\r
+/* ------------------------------------------------------------------ */\r
+static decFloat *decInfinity(decFloat *result, const decFloat *df) {\r
+  uInt sign=DFWORD(df, 0);         // save source signword\r
+  decFloatZero(result);            // clear everything\r
+  DFWORD(result, 0)=DECFLOAT_Inf | (sign & DECFLOAT_Sign);\r
+  return result;\r
+  } // decInfinity\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNaNs -- handle NaN argument(s)                                  */\r
+/*                                                                    */\r
+/*   result gets the result of handling dfl and dfr, one or both of   */\r
+/*          which is a NaN                                            */\r
+/*   dfl    is the first decFloat (lhs)                               */\r
+/*   dfr    is the second decFloat (rhs) -- may be NULL for a single- */\r
+/*          operand operation                                         */\r
+/*   set    is the context                                            */\r
+/*   returns result                                                   */\r
+/*                                                                    */\r
+/* Called when one or both operands is a NaN, and propagates the      */\r
+/* appropriate result to res.  When an sNaN is found, it is changed   */\r
+/* to a qNaN and Invalid operation is set.                            */\r
+/* ------------------------------------------------------------------ */\r
+static decFloat *decNaNs(decFloat *result,\r
+                         const decFloat *dfl, const decFloat *dfr,\r
+                         decContext *set) {\r
+  // handle sNaNs first\r
+  if (dfr!=NULL && DFISSNAN(dfr) && !DFISSNAN(dfl)) dfl=dfr; // use RHS\r
+  if (DFISSNAN(dfl)) {\r
+    decCanonical(result, dfl);          // propagate canonical sNaN\r
+    DFWORD(result, 0)&=~(DECFLOAT_qNaN ^ DECFLOAT_sNaN); // quiet\r
+    set->status|=DEC_Invalid_operation;\r
+    return result;\r
+    }\r
+  // one or both is a quiet NaN\r
+  if (!DFISNAN(dfl)) dfl=dfr;           // RHS must be NaN, use it\r
+  return decCanonical(result, dfl);     // propagate canonical qNaN\r
+  } // decNaNs\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumCompare -- numeric comparison of two decFloats               */\r
+/*                                                                    */\r
+/*   dfl    is the left-hand decFloat, which is not a NaN             */\r
+/*   dfr    is the right-hand decFloat, which is not a NaN            */\r
+/*   tot    is 1 for total order compare, 0 for simple numeric        */\r
+/*   returns -1, 0, or +1 for dfl<dfr, dfl=dfr, dfl>dfr               */\r
+/*                                                                    */\r
+/* No error is possible; status and mode are unchanged.               */\r
+/* ------------------------------------------------------------------ */\r
+static Int decNumCompare(const decFloat *dfl, const decFloat *dfr, Flag tot) {\r
+  Int   sigl, sigr;                     // LHS and RHS non-0 signums\r
+  Int   shift;                          // shift needed to align operands\r
+  uByte *ub, *uc;                       // work\r
+  uInt  uiwork;                         // for macros\r
+  // buffers +2 if Quad (36 digits), need double plus 4 for safe padding\r
+  uByte bufl[DECPMAX*2+QUAD*2+4];       // for LHS coefficient + padding\r
+  uByte bufr[DECPMAX*2+QUAD*2+4];       // for RHS coefficient + padding\r
+\r
+  sigl=1;\r
+  if (DFISSIGNED(dfl)) {\r
+    if (!DFISSIGNED(dfr)) {             // -LHS +RHS\r
+      if (DFISZERO(dfl) && DFISZERO(dfr) && !tot) return 0;\r
+      return -1;                        // RHS wins\r
+      }\r
+    sigl=-1;\r
+    }\r
+  if (DFISSIGNED(dfr)) {\r
+    if (!DFISSIGNED(dfl)) {             // +LHS -RHS\r
+      if (DFISZERO(dfl) && DFISZERO(dfr) && !tot) return 0;\r
+      return +1;                        // LHS wins\r
+      }\r
+    }\r
+\r
+  // signs are the same; operand(s) could be zero\r
+  sigr=-sigl;                           // sign to return if abs(RHS) wins\r
+\r
+  if (DFISINF(dfl)) {\r
+    if (DFISINF(dfr)) return 0;         // both infinite & same sign\r
+    return sigl;                        // inf > n\r
+    }\r
+  if (DFISINF(dfr)) return sigr;        // n < inf [dfl is finite]\r
+\r
+  // here, both are same sign and finite; calculate their offset\r
+  shift=GETEXP(dfl)-GETEXP(dfr);        // [0 means aligned]\r
+  // [bias can be ignored -- the absolute exponent is not relevant]\r
+\r
+  if (DFISZERO(dfl)) {\r
+    if (!DFISZERO(dfr)) return sigr;    // LHS=0, RHS!=0\r
+    // both are zero, return 0 if both same exponent or numeric compare\r
+    if (shift==0 || !tot) return 0;\r
+    if (shift>0) return sigl;\r
+    return sigr;                        // [shift<0]\r
+    }\r
+   else {                               // LHS!=0\r
+    if (DFISZERO(dfr)) return sigl;     // LHS!=0, RHS=0\r
+    }\r
+  // both are known to be non-zero at this point\r
+\r
+  // if the exponents are so different that the coefficients do not\r
+  // overlap (by even one digit) then a full comparison is not needed\r
+  if (abs(shift)>=DECPMAX) {            // no overlap\r
+    // coefficients are known to be non-zero\r
+    if (shift>0) return sigl;\r
+    return sigr;                        // [shift<0]\r
+    }\r
+\r
+  // decode the coefficients\r
+  // (shift both right two if Quad to make a multiple of four)\r
+  #if QUAD\r
+    UBFROMUI(bufl, 0);\r
+    UBFROMUI(bufr, 0);\r
+  #endif\r
+  GETCOEFF(dfl, bufl+QUAD*2);           // decode from decFloat\r
+  GETCOEFF(dfr, bufr+QUAD*2);           // ..\r
+  if (shift==0) {                       // aligned; common and easy\r
+    // all multiples of four, here\r
+    for (ub=bufl, uc=bufr; ub<bufl+DECPMAX+QUAD*2; ub+=4, uc+=4) {\r
+      uInt ui=UBTOUI(ub);\r
+      if (ui==UBTOUI(uc)) continue;     // so far so same\r
+      // about to find a winner; go by bytes in case little-endian\r
+      for (;; ub++, uc++) {\r
+        if (*ub>*uc) return sigl;       // difference found\r
+        if (*ub<*uc) return sigr;       // ..\r
+        }\r
+      }\r
+    } // aligned\r
+   else if (shift>0) {                  // lhs to left\r
+    ub=bufl;                            // RHS pointer\r
+    // pad bufl so right-aligned; most shifts will fit in 8\r
+    UBFROMUI(bufl+DECPMAX+QUAD*2, 0);   // add eight zeros\r
+    UBFROMUI(bufl+DECPMAX+QUAD*2+4, 0); // ..\r
+    if (shift>8) {\r
+      // more than eight; fill the rest, and also worth doing the\r
+      // lead-in by fours\r
+      uByte *up;                        // work\r
+      uByte *upend=bufl+DECPMAX+QUAD*2+shift;\r
+      for (up=bufl+DECPMAX+QUAD*2+8; up<upend; up+=4) UBFROMUI(up, 0);\r
+      // [pads up to 36 in all for Quad]\r
+      for (;; ub+=4) {\r
+        if (UBTOUI(ub)!=0) return sigl;\r
+        if (ub+4>bufl+shift-4) break;\r
+        }\r
+      }\r
+    // check remaining leading digits\r
+    for (; ub<bufl+shift; ub++) if (*ub!=0) return sigl;\r
+    // now start the overlapped part; bufl has been padded, so the\r
+    // comparison can go for the full length of bufr, which is a\r
+    // multiple of 4 bytes\r
+    for (uc=bufr; ; uc+=4, ub+=4) {\r
+      uInt ui=UBTOUI(ub);\r
+      if (ui!=UBTOUI(uc)) {             // mismatch found\r
+        for (;; uc++, ub++) {           // check from left [little-endian?]\r
+          if (*ub>*uc) return sigl;     // difference found\r
+          if (*ub<*uc) return sigr;     // ..\r
+          }\r
+        } // mismatch\r
+      if (uc==bufr+QUAD*2+DECPMAX-4) break; // all checked\r
+      }\r
+    } // shift>0\r
+\r
+   else { // shift<0) .. RHS is to left of LHS; mirror shift>0\r
+    uc=bufr;                            // RHS pointer\r
+    // pad bufr so right-aligned; most shifts will fit in 8\r
+    UBFROMUI(bufr+DECPMAX+QUAD*2, 0);   // add eight zeros\r
+    UBFROMUI(bufr+DECPMAX+QUAD*2+4, 0); // ..\r
+    if (shift<-8) {\r
+      // more than eight; fill the rest, and also worth doing the\r
+      // lead-in by fours\r
+      uByte *up;                        // work\r
+      uByte *upend=bufr+DECPMAX+QUAD*2-shift;\r
+      for (up=bufr+DECPMAX+QUAD*2+8; up<upend; up+=4) UBFROMUI(up, 0);\r
+      // [pads up to 36 in all for Quad]\r
+      for (;; uc+=4) {\r
+        if (UBTOUI(uc)!=0) return sigr;\r
+        if (uc+4>bufr-shift-4) break;\r
+        }\r
+      }\r
+    // check remaining leading digits\r
+    for (; uc<bufr-shift; uc++) if (*uc!=0) return sigr;\r
+    // now start the overlapped part; bufr has been padded, so the\r
+    // comparison can go for the full length of bufl, which is a\r
+    // multiple of 4 bytes\r
+    for (ub=bufl; ; ub+=4, uc+=4) {\r
+      uInt ui=UBTOUI(ub);\r
+      if (ui!=UBTOUI(uc)) {             // mismatch found\r
+        for (;; ub++, uc++) {           // check from left [little-endian?]\r
+          if (*ub>*uc) return sigl;     // difference found\r
+          if (*ub<*uc) return sigr;     // ..\r
+          }\r
+        } // mismatch\r
+      if (ub==bufl+QUAD*2+DECPMAX-4) break; // all checked\r
+      }\r
+    } // shift<0\r
+\r
+  // Here when compare equal\r
+  if (!tot) return 0;                   // numerically equal\r
+  // total ordering .. exponent matters\r
+  if (shift>0) return sigl;             // total order by exponent\r
+  if (shift<0) return sigr;             // ..\r
+  return 0;\r
+  } // decNumCompare\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decToInt32 -- local routine to effect ToInteger conversions        */\r
+/*                                                                    */\r
+/*   df     is the decFloat to convert                                */\r
+/*   set    is the context                                            */\r
+/*   rmode  is the rounding mode to use                               */\r
+/*   exact  is 1 if Inexact should be signalled                       */\r
+/*   unsign is 1 if the result a uInt, 0 if an Int (cast to uInt)     */\r
+/*   returns 32-bit result as a uInt                                  */\r
+/*                                                                    */\r
+/* Invalid is set is df is a NaN, is infinite, or is out-of-range; in */\r
+/* these cases 0 is returned.                                         */\r
+/* ------------------------------------------------------------------ */\r
+static uInt decToInt32(const decFloat *df, decContext *set,\r
+                       enum rounding rmode, Flag exact, Flag unsign) {\r
+  Int  exp;                        // exponent\r
+  uInt sourhi, sourpen, sourlo;    // top word from source decFloat ..\r
+  uInt hi, lo;                     // .. penultimate, least, etc.\r
+  decFloat zero, result;           // work\r
+  Int  i;                          // ..\r
+\r
+  /* Start decoding the argument */\r
+  sourhi=DFWORD(df, 0);                 // top word\r
+  exp=DECCOMBEXP[sourhi>>26];           // get exponent high bits (in place)\r
+  if (EXPISSPECIAL(exp)) {              // is special?\r
+    set->status|=DEC_Invalid_operation; // signal\r
+    return 0;\r
+    }\r
+\r
+  /* Here when the argument is finite */\r
+  if (GETEXPUN(df)==0) result=*df;      // already a true integer\r
+   else {                               // need to round to integer\r
+    enum rounding saveround;            // saver\r
+    uInt savestatus;                    // ..\r
+    saveround=set->round;               // save rounding mode ..\r
+    savestatus=set->status;             // .. and status\r
+    set->round=rmode;                   // set mode\r
+    decFloatZero(&zero);                // make 0E+0\r
+    set->status=0;                      // clear\r
+    decFloatQuantize(&result, df, &zero, set); // [this may fail]\r
+    set->round=saveround;               // restore rounding mode ..\r
+    if (exact) set->status|=savestatus; // include Inexact\r
+     else set->status=savestatus;       // .. or just original status\r
+    }\r
+\r
+  // only the last four declets of the coefficient can contain\r
+  // non-zero; check for others (and also NaN or Infinity from the\r
+  // Quantize) first (see DFISZERO for explanation):\r
+  // decFloatShow(&result, "sofar");\r
+  #if DOUBLE\r
+  if ((DFWORD(&result, 0)&0x1c03ff00)!=0\r
+   || (DFWORD(&result, 0)&0x60000000)==0x60000000) {\r
+  #elif QUAD\r
+  if ((DFWORD(&result, 2)&0xffffff00)!=0\r
+   ||  DFWORD(&result, 1)!=0\r
+   || (DFWORD(&result, 0)&0x1c003fff)!=0\r
+   || (DFWORD(&result, 0)&0x60000000)==0x60000000) {\r
+  #endif\r
+    set->status|=DEC_Invalid_operation; // Invalid or out of range\r
+    return 0;\r
+    }\r
+  // get last twelve digits of the coefficent into hi & ho, base\r
+  // 10**9 (see GETCOEFFBILL):\r
+  sourlo=DFWORD(&result, DECWORDS-1);\r
+  lo=DPD2BIN0[sourlo&0x3ff]\r
+    +DPD2BINK[(sourlo>>10)&0x3ff]\r
+    +DPD2BINM[(sourlo>>20)&0x3ff];\r
+  sourpen=DFWORD(&result, DECWORDS-2);\r
+  hi=DPD2BIN0[((sourpen<<2) | (sourlo>>30))&0x3ff];\r
+\r
+  // according to request, check range carefully\r
+  if (unsign) {\r
+    if (hi>4 || (hi==4 && lo>294967295) || (hi+lo!=0 && DFISSIGNED(&result))) {\r
+      set->status|=DEC_Invalid_operation; // out of range\r
+      return 0;\r
+      }\r
+    return hi*BILLION+lo;\r
+    }\r
+  // signed\r
+  if (hi>2 || (hi==2 && lo>147483647)) {\r
+    // handle the usual edge case\r
+    if (lo==147483648 && hi==2 && DFISSIGNED(&result)) return 0x80000000;\r
+    set->status|=DEC_Invalid_operation; // truly out of range\r
+    return 0;\r
+    }\r
+  i=hi*BILLION+lo;\r
+  if (DFISSIGNED(&result)) i=-i;\r
+  return (uInt)i;\r
+  } // decToInt32\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decToIntegral -- local routine to effect ToIntegral value          */\r
+/*                                                                    */\r
+/*   result gets the result                                           */\r
+/*   df     is the decFloat to round                                  */\r
+/*   set    is the context                                            */\r
+/*   rmode  is the rounding mode to use                               */\r
+/*   exact  is 1 if Inexact should be signalled                       */\r
+/*   returns result                                                   */\r
+/* ------------------------------------------------------------------ */\r
+static decFloat * decToIntegral(decFloat *result, const decFloat *df,\r
+                                decContext *set, enum rounding rmode,\r
+                                Flag exact) {\r
+  Int  exp;                        // exponent\r
+  uInt sourhi;                     // top word from source decFloat\r
+  enum rounding saveround;         // saver\r
+  uInt savestatus;                 // ..\r
+  decFloat zero;                   // work\r
+\r
+  /* Start decoding the argument */\r
+  sourhi=DFWORD(df, 0);            // top word\r
+  exp=DECCOMBEXP[sourhi>>26];      // get exponent high bits (in place)\r
+\r
+  if (EXPISSPECIAL(exp)) {         // is special?\r
+    // NaNs are handled as usual\r
+    if (DFISNAN(df)) return decNaNs(result, df, NULL, set);\r
+    // must be infinite; return canonical infinity with sign of df\r
+    return decInfinity(result, df);\r
+    }\r
+\r
+  /* Here when the argument is finite */\r
+  // complete extraction of the exponent\r
+  exp+=GETECON(df)-DECBIAS;             // .. + continuation and unbias\r
+\r
+  if (exp>=0) return decCanonical(result, df); // already integral\r
+\r
+  saveround=set->round;                 // save rounding mode ..\r
+  savestatus=set->status;               // .. and status\r
+  set->round=rmode;                     // set mode\r
+  decFloatZero(&zero);                  // make 0E+0\r
+  decFloatQuantize(result, df, &zero, set); // 'integrate'; cannot fail\r
+  set->round=saveround;                 // restore rounding mode ..\r
+  if (!exact) set->status=savestatus;   // .. and status, unless exact\r
+  return result;\r
+  } // decToIntegral\r
diff --git a/src/decNumber/decCommon.c b/src/decNumber/decCommon.c
new file mode 100644 (file)
index 0000000..0825781
--- /dev/null
@@ -0,0 +1,1835 @@
+/* ------------------------------------------------------------------ */\r
+/* decCommon.c -- common code for all three fixed-size types          */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2010.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is included in the package as decNumber.pdf.  This   */\r
+/* document is also available in HTML, together with specifications,  */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises code that is shared between all the formats  */\r
+/* (decSingle, decDouble, and decQuad); it includes set and extract   */\r
+/* of format components, widening, narrowing, and string conversions. */\r
+/*                                                                    */\r
+/* Unlike decNumber, parameterization takes place at compile time     */\r
+/* rather than at runtime.  The parameters are set in the decDouble.c */\r
+/* (etc.) files, which then include this one to produce the compiled  */\r
+/* code.  The functions here, therefore, are code shared between      */\r
+/* multiple formats.                                                  */\r
+/* ------------------------------------------------------------------ */\r
+// Names here refer to decFloat rather than to decDouble, etc., and\r
+// the functions are in strict alphabetical order.\r
+// Constants, tables, and debug function(s) are included only for QUAD\r
+// (which will always be compiled if DOUBLE or SINGLE are used).\r
+//\r
+// Whenever a decContext is used, only the status may be set (using\r
+// OR) or the rounding mode read; all other fields are ignored and\r
+// untouched.\r
+\r
+// names for simpler testing and default context\r
+#if DECPMAX==7\r
+  #define SINGLE     1\r
+  #define DOUBLE     0\r
+  #define QUAD       0\r
+  #define DEFCONTEXT DEC_INIT_DECIMAL32\r
+#elif DECPMAX==16\r
+  #define SINGLE     0\r
+  #define DOUBLE     1\r
+  #define QUAD       0\r
+  #define DEFCONTEXT DEC_INIT_DECIMAL64\r
+#elif DECPMAX==34\r
+  #define SINGLE     0\r
+  #define DOUBLE     0\r
+  #define QUAD       1\r
+  #define DEFCONTEXT DEC_INIT_DECIMAL128\r
+#else\r
+  #error Unexpected DECPMAX value\r
+#endif\r
+\r
+/* Assertions */\r
+\r
+#if DECPMAX!=7 && DECPMAX!=16 && DECPMAX!=34\r
+  #error Unexpected Pmax (DECPMAX) value for this module\r
+#endif\r
+\r
+// Assert facts about digit characters, etc.\r
+#if ('9'&0x0f)!=9\r
+  #error This module assumes characters are of the form 0b....nnnn\r
+  // where .... are don't care 4 bits and nnnn is 0000 through 1001\r
+#endif\r
+#if ('9'&0xf0)==('.'&0xf0)\r
+  #error This module assumes '.' has a different mask than a digit\r
+#endif\r
+\r
+// Assert ToString lay-out conditions\r
+#if DECSTRING<DECPMAX+9\r
+  #error ToString needs at least 8 characters for lead-in and dot\r
+#endif\r
+#if DECPMAX+DECEMAXD+5 > DECSTRING\r
+  #error Exponent form can be too long for ToString to lay out safely\r
+#endif\r
+#if DECEMAXD > 4\r
+  #error Exponent form is too long for ToString to lay out\r
+  // Note: code for up to 9 digits exists in archives [decOct]\r
+#endif\r
+\r
+/* Private functions used here and possibly in decBasic.c, etc. */\r
+static decFloat * decFinalize(decFloat *, bcdnum *, decContext *);\r
+static Flag decBiStr(const char *, const char *, const char *);\r
+\r
+/* Macros and private tables; those which are not format-dependent    */\r
+/* are only included if decQuad is being built.                       */\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* Combination field lookup tables (uInts to save measurable work)    */\r
+/*                                                                    */\r
+/*   DECCOMBEXP  - 2 most-significant-bits of exponent (00, 01, or    */\r
+/*                 10), shifted left for format, or DECFLOAT_Inf/NaN  */\r
+/*   DECCOMBWEXP - The same, for the next-wider format (unless QUAD)  */\r
+/*   DECCOMBMSD  - 4-bit most-significant-digit                       */\r
+/*                 [0 if the index is a special (Infinity or NaN)]    */\r
+/*   DECCOMBFROM - 5-bit combination field from EXP top bits and MSD  */\r
+/*                 (placed in uInt so no shift is needed)             */\r
+/*                                                                    */\r
+/* DECCOMBEXP, DECCOMBWEXP, and DECCOMBMSD are indexed by the sign    */\r
+/*   and 5-bit combination field (0-63, the second half of the table  */\r
+/*   identical to the first half)                                     */\r
+/* DECCOMBFROM is indexed by expTopTwoBits*16 + msd                   */\r
+/*                                                                    */\r
+/* DECCOMBMSD and DECCOMBFROM are not format-dependent and so are     */\r
+/* only included once, when QUAD is being built                       */\r
+/* ------------------------------------------------------------------ */\r
+static const uInt DECCOMBEXP[64]={\r
+  0, 0, 0, 0, 0, 0, 0, 0,\r
+  1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,\r
+  1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,\r
+  2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,\r
+  2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,\r
+  0,           0,           1<<DECECONL, 1<<DECECONL,\r
+  2<<DECECONL, 2<<DECECONL, DECFLOAT_Inf, DECFLOAT_NaN,\r
+  0, 0, 0, 0, 0, 0, 0, 0,\r
+  1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,\r
+  1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,\r
+  2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,\r
+  2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,\r
+  0,           0,           1<<DECECONL, 1<<DECECONL,\r
+  2<<DECECONL, 2<<DECECONL, DECFLOAT_Inf, DECFLOAT_NaN};\r
+#if !QUAD\r
+static const uInt DECCOMBWEXP[64]={\r
+  0, 0, 0, 0, 0, 0, 0, 0,\r
+  1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,\r
+  1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,\r
+  2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,\r
+  2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,\r
+  0,            0,            1<<DECWECONL, 1<<DECWECONL,\r
+  2<<DECWECONL, 2<<DECWECONL, DECFLOAT_Inf, DECFLOAT_NaN,\r
+  0, 0, 0, 0, 0, 0, 0, 0,\r
+  1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,\r
+  1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,\r
+  2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,\r
+  2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,\r
+  0,            0,            1<<DECWECONL, 1<<DECWECONL,\r
+  2<<DECWECONL, 2<<DECWECONL, DECFLOAT_Inf, DECFLOAT_NaN};\r
+#endif\r
+\r
+#if QUAD\r
+const uInt DECCOMBMSD[64]={\r
+  0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,\r
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, 0, 0,\r
+  0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,\r
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, 0, 0};\r
+\r
+const uInt DECCOMBFROM[48]={\r
+  0x00000000, 0x04000000, 0x08000000, 0x0C000000, 0x10000000, 0x14000000,\r
+  0x18000000, 0x1C000000, 0x60000000, 0x64000000, 0x00000000, 0x00000000,\r
+  0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x20000000, 0x24000000,\r
+  0x28000000, 0x2C000000, 0x30000000, 0x34000000, 0x38000000, 0x3C000000,\r
+  0x68000000, 0x6C000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,\r
+  0x00000000, 0x00000000, 0x40000000, 0x44000000, 0x48000000, 0x4C000000,\r
+  0x50000000, 0x54000000, 0x58000000, 0x5C000000, 0x70000000, 0x74000000,\r
+  0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000};\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* Request and include the tables to use for conversions              */\r
+/* ------------------------------------------------------------------ */\r
+#define DEC_BCD2DPD  1        // 0-0x999 -> DPD\r
+#define DEC_BIN2DPD  1        // 0-999 -> DPD\r
+#define DEC_BIN2BCD8 1        // 0-999 -> ddd, len\r
+#define DEC_DPD2BCD8 1        // DPD -> ddd, len\r
+#define DEC_DPD2BIN  1        // DPD -> 0-999\r
+#define DEC_DPD2BINK 1        // DPD -> 0-999000\r
+#define DEC_DPD2BINM 1        // DPD -> 0-999000000\r
+#include "decDPD.h"           // source of the lookup tables\r
+\r
+#endif\r
+\r
+/* ----------------------------------------------------------------- */\r
+/* decBiStr -- compare string with pairwise options                  */\r
+/*                                                                   */\r
+/*   targ is the string to compare                                   */\r
+/*   str1 is one of the strings to compare against (length may be 0) */\r
+/*   str2 is the other; it must be the same length as str1           */\r
+/*                                                                   */\r
+/*   returns 1 if strings compare equal, (that is, targ is the same  */\r
+/*   length as str1 and str2, and each character of targ is in one   */\r
+/*   of str1 or str2 in the corresponding position), or 0 otherwise  */\r
+/*                                                                   */\r
+/* This is used for generic caseless compare, including the awkward  */\r
+/* case of the Turkish dotted and dotless Is.  Use as (for example): */\r
+/*   if (decBiStr(test, "mike", "MIKE")) ...                         */\r
+/* ----------------------------------------------------------------- */\r
+static Flag decBiStr(const char *targ, const char *str1, const char *str2) {\r
+  for (;;targ++, str1++, str2++) {\r
+    if (*targ!=*str1 && *targ!=*str2) return 0;\r
+    // *targ has a match in one (or both, if terminator)\r
+    if (*targ=='\0') break;\r
+    } // forever\r
+  return 1;\r
+  } // decBiStr\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFinalize -- adjust and store a final result                     */\r
+/*                                                                    */\r
+/*  df  is the decFloat format number which gets the final result     */\r
+/*  num is the descriptor of the number to be checked and encoded     */\r
+/*         [its values, including the coefficient, may be modified]   */\r
+/*  set is the context to use                                         */\r
+/*  returns df                                                        */\r
+/*                                                                    */\r
+/* The num descriptor may point to a bcd8 string of any length; this  */\r
+/* string may have leading insignificant zeros.  If it has more than  */\r
+/* DECPMAX digits then the final digit can be a round-for-reround     */\r
+/* digit (i.e., it may include a sticky bit residue).                 */\r
+/*                                                                    */\r
+/* The exponent (q) may be one of the codes for a special value and   */\r
+/* can be up to 999999999 for conversion from string.                 */\r
+/*                                                                    */\r
+/* No error is possible, but Inexact, Underflow, and/or Overflow may  */\r
+/* be set.                                                            */\r
+/* ------------------------------------------------------------------ */\r
+// Constant whose size varies with format; also the check for surprises\r
+static uByte allnines[DECPMAX]=\r
+#if SINGLE\r
+  {9, 9, 9, 9, 9, 9, 9};\r
+#elif DOUBLE\r
+  {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9};\r
+#elif QUAD\r
+  {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,\r
+   9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9};\r
+#endif\r
+\r
+static decFloat * decFinalize(decFloat *df, bcdnum *num,\r
+                              decContext *set) {\r
+  uByte *ub;                  // work\r
+  uInt   dpd;                 // ..\r
+  uInt   uiwork;              // for macros\r
+  uByte *umsd=num->msd;       // local copy\r
+  uByte *ulsd=num->lsd;       // ..\r
+  uInt   encode;              // encoding accumulator\r
+  Int    length;              // coefficient length\r
+\r
+  #if DECCHECK\r
+  Int clen=ulsd-umsd+1;\r
+  #if QUAD\r
+    #define COEXTRA 2                        // extra-long coefficent\r
+  #else\r
+    #define COEXTRA 0\r
+  #endif\r
+  if (clen<1 || clen>DECPMAX*3+2+COEXTRA)\r
+    printf("decFinalize: suspect coefficient [length=%ld]\n", (LI)clen);\r
+  if (num->sign!=0 && num->sign!=DECFLOAT_Sign)\r
+    printf("decFinalize: bad sign [%08lx]\n", (LI)num->sign);\r
+  if (!EXPISSPECIAL(num->exponent)\r
+      && (num->exponent>1999999999 || num->exponent<-1999999999))\r
+    printf("decFinalize: improbable exponent [%ld]\n", (LI)num->exponent);\r
+  // decShowNum(num, "final");\r
+  #endif\r
+\r
+  // A special will have an 'exponent' which is very positive and a\r
+  // coefficient < DECPMAX\r
+  length=(uInt)(ulsd-umsd+1);                // coefficient length\r
+\r
+  if (!NUMISSPECIAL(num)) {\r
+    Int   drop;                              // digits to be dropped\r
+    // skip leading insignificant zeros to calculate an exact length\r
+    // [this is quite expensive]\r
+    if (*umsd==0) {\r
+      for (; umsd+3<ulsd && UBTOUI(umsd)==0;) umsd+=4;\r
+      for (; *umsd==0 && umsd<ulsd;) umsd++;\r
+      length=ulsd-umsd+1;                    // recalculate\r
+      }\r
+    drop=MAXI(length-DECPMAX, DECQTINY-num->exponent);\r
+    // drop can now be > digits for bottom-clamp (subnormal) cases\r
+    if (drop>0) {                            // rounding needed\r
+      // (decFloatQuantize has very similar code to this, so any\r
+      // changes may need to be made there, too)\r
+      uByte *roundat;                        // -> re-round digit\r
+      uByte reround;                         // reround value\r
+      // printf("Rounding; drop=%ld\n", (LI)drop);\r
+\r
+      num->exponent+=drop;                   // always update exponent\r
+\r
+      // Three cases here:\r
+      //   1. new LSD is in coefficient (almost always)\r
+      //   2. new LSD is digit to left of coefficient (so MSD is\r
+      //      round-for-reround digit)\r
+      //   3. new LSD is to left of case 2 (whole coefficient is sticky)\r
+      // [duplicate check-stickies code to save a test]\r
+      // [by-digit check for stickies as runs of zeros are rare]\r
+      if (drop<length) {                     // NB lengths not addresses\r
+        roundat=umsd+length-drop;\r
+        reround=*roundat;\r
+        for (ub=roundat+1; ub<=ulsd; ub++) {\r
+          if (*ub!=0) {                      // non-zero to be discarded\r
+            reround=DECSTICKYTAB[reround];   // apply sticky bit\r
+            break;                           // [remainder don't-care]\r
+            }\r
+          } // check stickies\r
+        ulsd=roundat-1;                      // new LSD\r
+        }\r
+       else {                                // edge case\r
+        if (drop==length) {\r
+          roundat=umsd;\r
+          reround=*roundat;\r
+          }\r
+         else {\r
+          roundat=umsd-1;\r
+          reround=0;\r
+          }\r
+        for (ub=roundat+1; ub<=ulsd; ub++) {\r
+          if (*ub!=0) {                      // non-zero to be discarded\r
+            reround=DECSTICKYTAB[reround];   // apply sticky bit\r
+            break;                           // [remainder don't-care]\r
+            }\r
+          } // check stickies\r
+        *umsd=0;                             // coefficient is a 0\r
+        ulsd=umsd;                           // ..\r
+        }\r
+\r
+      if (reround!=0) {                      // discarding non-zero\r
+        uInt bump=0;\r
+        set->status|=DEC_Inexact;\r
+        // if adjusted exponent [exp+digits-1] is < EMIN then num is\r
+        // subnormal -- so raise Underflow\r
+        if (num->exponent<DECEMIN && (num->exponent+(ulsd-umsd+1)-1)<DECEMIN)\r
+          set->status|=DEC_Underflow;\r
+\r
+        // next decide whether increment of the coefficient is needed\r
+        if (set->round==DEC_ROUND_HALF_EVEN) {    // fastpath slowest case\r
+          if (reround>5) bump=1;                  // >0.5 goes up\r
+           else if (reround==5)                   // exactly 0.5000 ..\r
+            bump=*ulsd & 0x01;                    // .. up iff [new] lsd is odd\r
+          } // r-h-e\r
+         else switch (set->round) {\r
+          case DEC_ROUND_DOWN: {\r
+            // no change\r
+            break;} // r-d\r
+          case DEC_ROUND_HALF_DOWN: {\r
+            if (reround>5) bump=1;\r
+            break;} // r-h-d\r
+          case DEC_ROUND_HALF_UP: {\r
+            if (reround>=5) bump=1;\r
+            break;} // r-h-u\r
+          case DEC_ROUND_UP: {\r
+            if (reround>0) bump=1;\r
+            break;} // r-u\r
+          case DEC_ROUND_CEILING: {\r
+            // same as _UP for positive numbers, and as _DOWN for negatives\r
+            if (!num->sign && reround>0) bump=1;\r
+            break;} // r-c\r
+          case DEC_ROUND_FLOOR: {\r
+            // same as _UP for negative numbers, and as _DOWN for positive\r
+            // [negative reround cannot occur on 0]\r
+            if (num->sign && reround>0) bump=1;\r
+            break;} // r-f\r
+          case DEC_ROUND_05UP: {\r
+            if (reround>0) { // anything out there is 'sticky'\r
+              // bump iff lsd=0 or 5; this cannot carry so it could be\r
+              // effected immediately with no bump -- but the code\r
+              // is clearer if this is done the same way as the others\r
+              if (*ulsd==0 || *ulsd==5) bump=1;\r
+              }\r
+            break;} // r-r\r
+          default: {      // e.g., DEC_ROUND_MAX\r
+            set->status|=DEC_Invalid_context;\r
+            #if DECCHECK\r
+            printf("Unknown rounding mode: %ld\n", (LI)set->round);\r
+            #endif\r
+            break;}\r
+          } // switch (not r-h-e)\r
+        // printf("ReRound: %ld  bump: %ld\n", (LI)reround, (LI)bump);\r
+\r
+        if (bump!=0) {                       // need increment\r
+          // increment the coefficient; this might end up with 1000...\r
+          // (after the all nines case)\r
+          ub=ulsd;\r
+          for(; ub-3>=umsd && UBTOUI(ub-3)==0x09090909; ub-=4)  {\r
+            UBFROMUI(ub-3, 0);               // to 00000000\r
+            }\r
+          // [note ub could now be to left of msd, and it is not safe\r
+          // to write to the the left of the msd]\r
+          // now at most 3 digits left to non-9 (usually just the one)\r
+          for (; ub>=umsd; *ub=0, ub--) {\r
+            if (*ub==9) continue;            // carry\r
+            *ub+=1;\r
+            break;\r
+            }\r
+          if (ub<umsd) {                     // had all-nines\r
+            *umsd=1;                         // coefficient to 1000...\r
+            // usually the 1000... coefficient can be used as-is\r
+            if ((ulsd-umsd+1)==DECPMAX) {\r
+              num->exponent++;\r
+              }\r
+             else {\r
+              // if coefficient is shorter than Pmax then num is\r
+              // subnormal, so extend it; this is safe as drop>0\r
+              // (or, if the coefficient was supplied above, it could\r
+              // not be 9); this may make the result normal.\r
+              ulsd++;\r
+              *ulsd=0;\r
+              // [exponent unchanged]\r
+              #if DECCHECK\r
+              if (num->exponent!=DECQTINY) // sanity check\r
+                printf("decFinalize: bad all-nines extend [^%ld, %ld]\n",\r
+                       (LI)num->exponent, (LI)(ulsd-umsd+1));\r
+              #endif\r
+              } // subnormal extend\r
+            } // had all-nines\r
+          } // bump needed\r
+        } // inexact rounding\r
+\r
+      length=ulsd-umsd+1;               // recalculate (may be <DECPMAX)\r
+      } // need round (drop>0)\r
+\r
+    // The coefficient will now fit and has final length unless overflow\r
+    // decShowNum(num, "rounded");\r
+\r
+    // if exponent is >=emax may have to clamp, overflow, or fold-down\r
+    if (num->exponent>DECEMAX-(DECPMAX-1)) { // is edge case\r
+      // printf("overflow checks...\n");\r
+      if (*ulsd==0 && ulsd==umsd) {     // have zero\r
+        num->exponent=DECEMAX-(DECPMAX-1); // clamp to max\r
+        }\r
+       else if ((num->exponent+length-1)>DECEMAX) { // > Nmax\r
+        // Overflow -- these could go straight to encoding, here, but\r
+        // instead num is adjusted to keep the code cleaner\r
+        Flag needmax=0;                 // 1 for finite result\r
+        set->status|=(DEC_Overflow | DEC_Inexact);\r
+        switch (set->round) {\r
+          case DEC_ROUND_DOWN: {\r
+            needmax=1;                  // never Infinity\r
+            break;} // r-d\r
+          case DEC_ROUND_05UP: {\r
+            needmax=1;                  // never Infinity\r
+            break;} // r-05\r
+          case DEC_ROUND_CEILING: {\r
+            if (num->sign) needmax=1;   // Infinity iff non-negative\r
+            break;} // r-c\r
+          case DEC_ROUND_FLOOR: {\r
+            if (!num->sign) needmax=1;  // Infinity iff negative\r
+            break;} // r-f\r
+          default: break;               // Infinity in all other cases\r
+          }\r
+        if (!needmax) {                 // easy .. set Infinity\r
+          num->exponent=DECFLOAT_Inf;\r
+          *umsd=0;                      // be clean: coefficient to 0\r
+          ulsd=umsd;                    // ..\r
+          }\r
+         else {                         // return Nmax\r
+          umsd=allnines;                // use constant array\r
+          ulsd=allnines+DECPMAX-1;\r
+          num->exponent=DECEMAX-(DECPMAX-1);\r
+          }\r
+        }\r
+       else { // no overflow but non-zero and may have to fold-down\r
+        Int shift=num->exponent-(DECEMAX-(DECPMAX-1));\r
+        if (shift>0) {                  // fold-down needed\r
+          // fold down needed; must copy to buffer in order to pad\r
+          // with zeros safely; fortunately this is not the worst case\r
+          // path because cannot have had a round\r
+          uByte buffer[ROUNDUP(DECPMAX+3, 4)]; // [+3 allows uInt padding]\r
+          uByte *s=umsd;                // source\r
+          uByte *t=buffer;              // safe target\r
+          uByte *tlsd=buffer+(ulsd-umsd)+shift; // target LSD\r
+          // printf("folddown shift=%ld\n", (LI)shift);\r
+          for (; s<=ulsd; s+=4, t+=4) UBFROMUI(t, UBTOUI(s));\r
+          for (t=tlsd-shift+1; t<=tlsd; t+=4) UBFROMUI(t, 0);  // pad 0s\r
+          num->exponent-=shift;\r
+          umsd=buffer;\r
+          ulsd=tlsd;\r
+          }\r
+        } // fold-down?\r
+      length=ulsd-umsd+1;               // recalculate length\r
+      } // high-end edge case\r
+    } // finite number\r
+\r
+  /*------------------------------------------------------------------*/\r
+  /* At this point the result will properly fit the decFloat          */\r
+  /* encoding, and it can be encoded with no possibility of error     */\r
+  /*------------------------------------------------------------------*/\r
+  // Following code does not alter coefficient (could be allnines array)\r
+\r
+  // fast path possible when DECPMAX digits\r
+  if (length==DECPMAX) {\r
+    return decFloatFromBCD(df, num->exponent, umsd, num->sign);\r
+    } // full-length\r
+\r
+  // slower path when not a full-length number; must care about length\r
+  // [coefficient length here will be < DECPMAX]\r
+  if (!NUMISSPECIAL(num)) {             // is still finite\r
+    // encode the combination field and exponent continuation\r
+    uInt uexp=(uInt)(num->exponent+DECBIAS); // biased exponent\r
+    uInt code=(uexp>>DECECONL)<<4;      // top two bits of exp\r
+    // [msd==0]\r
+    // look up the combination field and make high word\r
+    encode=DECCOMBFROM[code];           // indexed by (0-2)*16+msd\r
+    encode|=(uexp<<(32-6-DECECONL)) & 0x03ffffff; // exponent continuation\r
+    }\r
+   else encode=num->exponent;           // special [already in word]\r
+  encode|=num->sign;                    // add sign\r
+\r
+  // private macro to extract a declet, n (where 0<=n<DECLETS and 0\r
+  // refers to the declet from the least significant three digits)\r
+  // and put the corresponding DPD code into dpd.  Access to umsd and\r
+  // ulsd (pointers to the most and least significant digit of the\r
+  // variable-length coefficient) is assumed, along with use of a\r
+  // working pointer, uInt *ub.\r
+  // As not full-length then chances are there are many leading zeros\r
+  // [and there may be a partial triad]\r
+  #define getDPDt(dpd, n) ub=ulsd-(3*(n))-2;                          \\r
+    if (ub<umsd-2) dpd=0;                                             \\r
+     else if (ub>=umsd) dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)];  \\r
+     else {dpd=*(ub+2); if (ub+1==umsd) dpd+=*(ub+1)*16; dpd=BCD2DPD[dpd];}\r
+\r
+  // place the declets in the encoding words and copy to result (df),\r
+  // according to endianness; in all cases complete the sign word\r
+  // first\r
+  #if DECPMAX==7\r
+    getDPDt(dpd, 1);\r
+    encode|=dpd<<10;\r
+    getDPDt(dpd, 0);\r
+    encode|=dpd;\r
+    DFWORD(df, 0)=encode;     // just the one word\r
+\r
+  #elif DECPMAX==16\r
+    getDPDt(dpd, 4); encode|=dpd<<8;\r
+    getDPDt(dpd, 3); encode|=dpd>>2;\r
+    DFWORD(df, 0)=encode;\r
+    encode=dpd<<30;\r
+    getDPDt(dpd, 2); encode|=dpd<<20;\r
+    getDPDt(dpd, 1); encode|=dpd<<10;\r
+    getDPDt(dpd, 0); encode|=dpd;\r
+    DFWORD(df, 1)=encode;\r
+\r
+  #elif DECPMAX==34\r
+    getDPDt(dpd,10); encode|=dpd<<4;\r
+    getDPDt(dpd, 9); encode|=dpd>>6;\r
+    DFWORD(df, 0)=encode;\r
+\r
+    encode=dpd<<26;\r
+    getDPDt(dpd, 8); encode|=dpd<<16;\r
+    getDPDt(dpd, 7); encode|=dpd<<6;\r
+    getDPDt(dpd, 6); encode|=dpd>>4;\r
+    DFWORD(df, 1)=encode;\r
+\r
+    encode=dpd<<28;\r
+    getDPDt(dpd, 5); encode|=dpd<<18;\r
+    getDPDt(dpd, 4); encode|=dpd<<8;\r
+    getDPDt(dpd, 3); encode|=dpd>>2;\r
+    DFWORD(df, 2)=encode;\r
+\r
+    encode=dpd<<30;\r
+    getDPDt(dpd, 2); encode|=dpd<<20;\r
+    getDPDt(dpd, 1); encode|=dpd<<10;\r
+    getDPDt(dpd, 0); encode|=dpd;\r
+    DFWORD(df, 3)=encode;\r
+  #endif\r
+\r
+  // printf("Status: %08lx\n", (LI)set->status);\r
+  // decFloatShow(df, "final2");\r
+  return df;\r
+  } // decFinalize\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatFromBCD -- set decFloat from exponent, BCD8, and sign      */\r
+/*                                                                    */\r
+/*  df is the target decFloat                                         */\r
+/*  exp is the in-range unbiased exponent, q, or a special value in   */\r
+/*    the form returned by decFloatGetExponent                        */\r
+/*  bcdar holds DECPMAX digits to set the coefficient from, one       */\r
+/*    digit in each byte (BCD8 encoding); the first (MSD) is ignored  */\r
+/*    if df is a NaN; all are ignored if df is infinite.              */\r
+/*    All bytes must be in 0-9; results are undefined otherwise.      */\r
+/*  sig is DECFLOAT_Sign to set the sign bit, 0 otherwise             */\r
+/*  returns df, which will be canonical                               */\r
+/*                                                                    */\r
+/* No error is possible, and no status will be set.                   */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatFromBCD(decFloat *df, Int exp, const uByte *bcdar,\r
+                           Int sig) {\r
+  uInt encode, dpd;                     // work\r
+  const uByte *ub;                      // ..\r
+\r
+  if (EXPISSPECIAL(exp)) encode=exp|sig;// specials already encoded\r
+   else {                               // is finite\r
+    // encode the combination field and exponent continuation\r
+    uInt uexp=(uInt)(exp+DECBIAS);      // biased exponent\r
+    uInt code=(uexp>>DECECONL)<<4;      // top two bits of exp\r
+    code+=bcdar[0];                     // add msd\r
+    // look up the combination field and make high word\r
+    encode=DECCOMBFROM[code]|sig;       // indexed by (0-2)*16+msd\r
+    encode|=(uexp<<(32-6-DECECONL)) & 0x03ffffff; // exponent continuation\r
+    }\r
+\r
+  // private macro to extract a declet, n (where 0<=n<DECLETS and 0\r
+  // refers to the declet from the least significant three digits)\r
+  // and put the corresponding DPD code into dpd.\r
+  // Use of a working pointer, uInt *ub, is assumed.\r
+\r
+  #define getDPDb(dpd, n) ub=bcdar+DECPMAX-1-(3*(n))-2;     \\r
+    dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)];\r
+\r
+  // place the declets in the encoding words and copy to result (df),\r
+  // according to endianness; in all cases complete the sign word\r
+  // first\r
+  #if DECPMAX==7\r
+    getDPDb(dpd, 1);\r
+    encode|=dpd<<10;\r
+    getDPDb(dpd, 0);\r
+    encode|=dpd;\r
+    DFWORD(df, 0)=encode;     // just the one word\r
+\r
+  #elif DECPMAX==16\r
+    getDPDb(dpd, 4); encode|=dpd<<8;\r
+    getDPDb(dpd, 3); encode|=dpd>>2;\r
+    DFWORD(df, 0)=encode;\r
+    encode=dpd<<30;\r
+    getDPDb(dpd, 2); encode|=dpd<<20;\r
+    getDPDb(dpd, 1); encode|=dpd<<10;\r
+    getDPDb(dpd, 0); encode|=dpd;\r
+    DFWORD(df, 1)=encode;\r
+\r
+  #elif DECPMAX==34\r
+    getDPDb(dpd,10); encode|=dpd<<4;\r
+    getDPDb(dpd, 9); encode|=dpd>>6;\r
+    DFWORD(df, 0)=encode;\r
+\r
+    encode=dpd<<26;\r
+    getDPDb(dpd, 8); encode|=dpd<<16;\r
+    getDPDb(dpd, 7); encode|=dpd<<6;\r
+    getDPDb(dpd, 6); encode|=dpd>>4;\r
+    DFWORD(df, 1)=encode;\r
+\r
+    encode=dpd<<28;\r
+    getDPDb(dpd, 5); encode|=dpd<<18;\r
+    getDPDb(dpd, 4); encode|=dpd<<8;\r
+    getDPDb(dpd, 3); encode|=dpd>>2;\r
+    DFWORD(df, 2)=encode;\r
+\r
+    encode=dpd<<30;\r
+    getDPDb(dpd, 2); encode|=dpd<<20;\r
+    getDPDb(dpd, 1); encode|=dpd<<10;\r
+    getDPDb(dpd, 0); encode|=dpd;\r
+    DFWORD(df, 3)=encode;\r
+  #endif\r
+  // decFloatShow(df, "fromB");\r
+  return df;\r
+  } // decFloatFromBCD\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatFromPacked -- set decFloat from exponent and packed BCD    */\r
+/*                                                                    */\r
+/*  df is the target decFloat                                         */\r
+/*  exp is the in-range unbiased exponent, q, or a special value in   */\r
+/*    the form returned by decFloatGetExponent                        */\r
+/*  packed holds DECPMAX packed decimal digits plus a sign nibble     */\r
+/*    (all 6 codes are OK); the first (MSD) is ignored if df is a NaN */\r
+/*    and all except sign are ignored if df is infinite.  For DOUBLE  */\r
+/*    and QUAD the first (pad) nibble is also ignored in all cases.   */\r
+/*    All coefficient nibbles must be in 0-9 and sign in A-F; results */\r
+/*    are undefined otherwise.                                        */\r
+/*  returns df, which will be canonical                               */\r
+/*                                                                    */\r
+/* No error is possible, and no status will be set.                   */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatFromPacked(decFloat *df, Int exp, const uByte *packed) {\r
+  uByte bcdar[DECPMAX+2];               // work [+1 for pad, +1 for sign]\r
+  const uByte *ip;                      // ..\r
+  uByte *op;                            // ..\r
+  Int   sig=0;                          // sign\r
+\r
+  // expand coefficient and sign to BCDAR\r
+  #if SINGLE\r
+  op=bcdar+1;                           // no pad digit\r
+  #else\r
+  op=bcdar;                             // first (pad) digit ignored\r
+  #endif\r
+  for (ip=packed; ip<packed+((DECPMAX+2)/2); ip++) {\r
+    *op++=*ip>>4;\r
+    *op++=(uByte)(*ip&0x0f);            // [final nibble is sign]\r
+    }\r
+  op--;                                 // -> sign byte\r
+  if (*op==DECPMINUS || *op==DECPMINUSALT) sig=DECFLOAT_Sign;\r
+\r
+  if (EXPISSPECIAL(exp)) {              // Infinity or NaN\r
+    if (!EXPISINF(exp)) bcdar[1]=0;     // a NaN: ignore MSD\r
+     else memset(bcdar+1, 0, DECPMAX);  // Infinite: coefficient to 0\r
+    }\r
+  return decFloatFromBCD(df, exp, bcdar+1, sig);\r
+  } // decFloatFromPacked\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatFromPackedChecked -- set from exponent and packed; checked */\r
+/*                                                                    */\r
+/*  df is the target decFloat                                         */\r
+/*  exp is the in-range unbiased exponent, q, or a special value in   */\r
+/*    the form returned by decFloatGetExponent                        */\r
+/*  packed holds DECPMAX packed decimal digits plus a sign nibble     */\r
+/*    (all 6 codes are OK); the first (MSD) must be 0 if df is a NaN  */\r
+/*    and all digits must be 0 if df is infinite.  For DOUBLE and     */\r
+/*    QUAD the first (pad) nibble must be 0.                          */\r
+/*    All coefficient nibbles must be in 0-9 and sign in A-F.         */\r
+/*  returns df, which will be canonical or NULL if any of the         */\r
+/*    requirements are not met (if this case df is unchanged); that   */\r
+/*    is, the input data must be as returned by decFloatToPacked,     */\r
+/*    except that all six sign codes are acccepted.                   */\r
+/*                                                                    */\r
+/* No status will be set.                                             */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatFromPackedChecked(decFloat *df, Int exp,\r
+                                     const uByte *packed) {\r
+  uByte bcdar[DECPMAX+2];               // work [+1 for pad, +1 for sign]\r
+  const uByte *ip;                      // ..\r
+  uByte *op;                            // ..\r
+  Int   sig=0;                          // sign\r
+\r
+  // expand coefficient and sign to BCDAR\r
+  #if SINGLE\r
+  op=bcdar+1;                           // no pad digit\r
+  #else\r
+  op=bcdar;                             // first (pad) digit here\r
+  #endif\r
+  for (ip=packed; ip<packed+((DECPMAX+2)/2); ip++) {\r
+    *op=*ip>>4;\r
+    if (*op>9) return NULL;\r
+    op++;\r
+    *op=(uByte)(*ip&0x0f);              // [final nibble is sign]\r
+    if (*op>9 && ip<packed+((DECPMAX+2)/2)-1) return NULL;\r
+    op++;\r
+    }\r
+  op--;                                 // -> sign byte\r
+  if (*op<=9) return NULL;              // bad sign\r
+  if (*op==DECPMINUS || *op==DECPMINUSALT) sig=DECFLOAT_Sign;\r
+\r
+  #if !SINGLE\r
+  if (bcdar[0]!=0) return NULL;         // bad pad nibble\r
+  #endif\r
+\r
+  if (EXPISNAN(exp)) {                  // a NaN\r
+    if (bcdar[1]!=0) return NULL;       // bad msd\r
+    } // NaN\r
+   else if (EXPISINF(exp)) {            // is infinite\r
+    Int i;\r
+    for (i=0; i<DECPMAX; i++) {\r
+      if (bcdar[i+1]!=0) return NULL;   // should be all zeros\r
+      }\r
+    } // infinity\r
+   else {                               // finite\r
+    // check the exponent is in range\r
+    if (exp>DECEMAX-DECPMAX+1) return NULL;\r
+    if (exp<DECEMIN-DECPMAX+1) return NULL;\r
+    }\r
+  return decFloatFromBCD(df, exp, bcdar+1, sig);\r
+  } // decFloatFromPacked\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatFromString -- conversion from numeric string               */\r
+/*                                                                    */\r
+/*  result  is the decFloat format number which gets the result of    */\r
+/*          the conversion                                            */\r
+/*  *string is the character string which should contain a valid      */\r
+/*          number (which may be a special value), \0-terminated      */\r
+/*          If there are too many significant digits in the           */\r
+/*          coefficient it will be rounded.                           */\r
+/*  set     is the context                                            */\r
+/*  returns result                                                    */\r
+/*                                                                    */\r
+/* The length of the coefficient and the size of the exponent are     */\r
+/* checked by this routine, so the correct error (Underflow or        */\r
+/* Overflow) can be reported or rounding applied, as necessary.       */\r
+/*                                                                    */\r
+/* There is no limit to the coefficient length for finite inputs;     */\r
+/* NaN payloads must be integers with no more than DECPMAX-1 digits.  */\r
+/* Exponents may have up to nine significant digits.                  */\r
+/*                                                                    */\r
+/* If bad syntax is detected, the result will be a quiet NaN.         */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatFromString(decFloat *result, const char *string,\r
+                              decContext *set) {\r
+  Int    digits;                   // count of digits in coefficient\r
+  const  char *dotchar=NULL;       // where dot was found [NULL if none]\r
+  const  char *cfirst=string;      // -> first character of decimal part\r
+  const  char *c;                  // work\r
+  uByte *ub;                       // ..\r
+  uInt   uiwork;                   // for macros\r
+  bcdnum num;                      // collects data for finishing\r
+  uInt   error=DEC_Conversion_syntax;      // assume the worst\r
+  uByte  buffer[ROUNDUP(DECSTRING+11, 8)]; // room for most coefficents,\r
+                                           // some common rounding, +3, & pad\r
+  #if DECTRACE\r
+  // printf("FromString %s ...\n", string);\r
+  #endif\r
+\r
+  for(;;) {                             // once-only 'loop'\r
+    num.sign=0;                         // assume non-negative\r
+    num.msd=buffer;                     // MSD is here always\r
+\r
+    // detect and validate the coefficient, including any leading,\r
+    // trailing, or embedded '.'\r
+    // [could test four-at-a-time here (saving 10% for decQuads),\r
+    // but that risks storage violation because the position of the\r
+    // terminator is unknown]\r
+    for (c=string;; c++) {              // -> input character\r
+      if (((unsigned)(*c-'0'))<=9) continue; // '0' through '9' is good\r
+      if (*c=='\0') break;              // most common non-digit\r
+      if (*c=='.') {\r
+        if (dotchar!=NULL) break;       // not first '.'\r
+        dotchar=c;                      // record offset into decimal part\r
+        continue;}\r
+      if (c==string) {                  // first in string...\r
+        if (*c=='-') {                  // valid - sign\r
+          cfirst++;\r
+          num.sign=DECFLOAT_Sign;\r
+          continue;}\r
+        if (*c=='+') {                  // valid + sign\r
+          cfirst++;\r
+          continue;}\r
+        }\r
+      // *c is not a digit, terminator, or a valid +, -, or '.'\r
+      break;\r
+      } // c loop\r
+\r
+    digits=(uInt)(c-cfirst);            // digits (+1 if a dot)\r
+\r
+    if (digits>0) {                     // had digits and/or dot\r
+      const char *clast=c-1;            // note last coefficient char position\r
+      Int exp=0;                        // exponent accumulator\r
+      if (*c!='\0') {                   // something follows the coefficient\r
+        uInt edig;                      // unsigned work\r
+        // had some digits and more to come; expect E[+|-]nnn now\r
+        const char *firstexp;           // exponent first non-zero\r
+        if (*c!='E' && *c!='e') break;\r
+        c++;                            // to (optional) sign\r
+        if (*c=='-' || *c=='+') c++;    // step over sign (c=clast+2)\r
+        if (*c=='\0') break;            // no digits!  (e.g., '1.2E')\r
+        for (; *c=='0';) c++;           // skip leading zeros [even last]\r
+        firstexp=c;                     // remember start [maybe '\0']\r
+        // gather exponent digits\r
+        edig=(uInt)*c-(uInt)'0';\r
+        if (edig<=9) {                  // [check not bad or terminator]\r
+          exp+=edig;                    // avoid initial X10\r
+          c++;\r
+          for (;; c++) {\r
+            edig=(uInt)*c-(uInt)'0';\r
+            if (edig>9) break;\r
+            exp=exp*10+edig;\r
+            }\r
+          }\r
+        // if not now on the '\0', *c must not be a digit\r
+        if (*c!='\0') break;\r
+\r
+        // (this next test must be after the syntax checks)\r
+        // if definitely more than the possible digits for format then\r
+        // the exponent may have wrapped, so simply set it to a certain\r
+        // over/underflow value\r
+        if (c>firstexp+DECEMAXD) exp=DECEMAX*2;\r
+        if (*(clast+2)=='-') exp=-exp;  // was negative\r
+        } // exponent part\r
+\r
+      if (dotchar!=NULL) {              // had a '.'\r
+        digits--;                       // remove from digits count\r
+        if (digits==0) break;           // was dot alone: bad syntax\r
+        exp-=(Int)(clast-dotchar);      // adjust exponent\r
+        // [the '.' can now be ignored]\r
+        }\r
+      num.exponent=exp;                 // exponent is good; store it\r
+\r
+      // Here when whole string has been inspected and syntax is good\r
+      // cfirst->first digit or dot, clast->last digit or dot\r
+      error=0;                          // no error possible now\r
+\r
+      // if the number of digits in the coefficient will fit in buffer\r
+      // then it can simply be converted to bcd8 and copied -- decFinalize\r
+      // will take care of leading zeros and rounding; the buffer is big\r
+      // enough for all canonical coefficients, including 0.00000nn...\r
+      ub=buffer;\r
+      if (digits<=(Int)(sizeof(buffer)-3)) { // [-3 allows by-4s copy]\r
+        c=cfirst;\r
+        if (dotchar!=NULL) {                 // a dot to worry about\r
+          if (*(c+1)=='.') {                 // common canonical case\r
+            *ub++=(uByte)(*c-'0');           // copy leading digit\r
+            c+=2;                            // prepare to handle rest\r
+            }\r
+           else for (; c<=clast;) {          // '.' could be anywhere\r
+            // as usual, go by fours when safe; NB it has been asserted\r
+            // that a '.' does not have the same mask as a digit\r
+            if (c<=clast-3                             // safe for four\r
+             && (UBTOUI(c)&0xf0f0f0f0)==CHARMASK) {    // test four\r
+              UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f);      // to BCD8\r
+              ub+=4;\r
+              c+=4;\r
+              continue;\r
+              }\r
+            if (*c=='.') {                   // found the dot\r
+              c++;                           // step over it ..\r
+              break;                         // .. and handle the rest\r
+              }\r
+            *ub++=(uByte)(*c++-'0');\r
+            }\r
+          } // had dot\r
+        // Now no dot; do this by fours (where safe)\r
+        for (; c<=clast-3; c+=4, ub+=4) UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f);\r
+        for (; c<=clast; c++, ub++) *ub=(uByte)(*c-'0');\r
+        num.lsd=buffer+digits-1;             // record new LSD\r
+        } // fits\r
+\r
+       else {                                // too long for buffer\r
+        // [This is a rare and unusual case; arbitrary-length input]\r
+        // strip leading zeros [but leave final 0 if all 0's]\r
+        if (*cfirst=='.') cfirst++;          // step past dot at start\r
+        if (*cfirst=='0') {                  // [cfirst always -> digit]\r
+          for (; cfirst<clast; cfirst++) {\r
+            if (*cfirst!='0') {              // non-zero found\r
+              if (*cfirst=='.') continue;    // [ignore]\r
+              break;                         // done\r
+              }\r
+            digits--;                        // 0 stripped\r
+            } // cfirst\r
+          } // at least one leading 0\r
+\r
+        // the coefficient is now as short as possible, but may still\r
+        // be too long; copy up to Pmax+1 digits to the buffer, then\r
+        // just record any non-zeros (set round-for-reround digit)\r
+        for (c=cfirst; c<=clast && ub<=buffer+DECPMAX; c++) {\r
+          // (see commentary just above)\r
+          if (c<=clast-3                          // safe for four\r
+           && (UBTOUI(c)&0xf0f0f0f0)==CHARMASK) { // four digits\r
+            UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f);   // to BCD8\r
+            ub+=4;\r
+            c+=3;                            // [will become 4]\r
+            continue;\r
+            }\r
+          if (*c=='.') continue;             // [ignore]\r
+          *ub++=(uByte)(*c-'0');\r
+          }\r
+        ub--;                                // -> LSD\r
+        for (; c<=clast; c++) {              // inspect remaining chars\r
+          if (*c!='0') {                     // sticky bit needed\r
+            if (*c=='.') continue;           // [ignore]\r
+            *ub=DECSTICKYTAB[*ub];           // update round-for-reround\r
+            break;                           // no need to look at more\r
+            }\r
+          }\r
+        num.lsd=ub;                          // record LSD\r
+        // adjust exponent for dropped digits\r
+        num.exponent+=digits-(Int)(ub-buffer+1);\r
+        } // too long for buffer\r
+      } // digits and/or dot\r
+\r
+     else {                             // no digits or dot were found\r
+      // only Infinities and NaNs are allowed, here\r
+      if (*c=='\0') break;              // nothing there is bad\r
+      buffer[0]=0;                      // default a coefficient of 0\r
+      num.lsd=buffer;                   // ..\r
+      if (decBiStr(c, "infinity", "INFINITY")\r
+       || decBiStr(c, "inf", "INF")) num.exponent=DECFLOAT_Inf;\r
+       else {                           // should be a NaN\r
+        num.exponent=DECFLOAT_qNaN;     // assume quiet NaN\r
+        if (*c=='s' || *c=='S') {       // probably an sNaN\r
+          num.exponent=DECFLOAT_sNaN;   // effect the 's'\r
+          c++;                          // and step over it\r
+          }\r
+        if (*c!='N' && *c!='n') break;  // check caseless "NaN"\r
+        c++;\r
+        if (*c!='a' && *c!='A') break;  // ..\r
+        c++;\r
+        if (*c!='N' && *c!='n') break;  // ..\r
+        c++;\r
+        // now either nothing, or nnnn payload (no dots), expected\r
+        // -> start of integer, and skip leading 0s [including plain 0]\r
+        for (cfirst=c; *cfirst=='0';) cfirst++;\r
+        if (*cfirst!='\0') {            // not empty or all-0, payload\r
+          // payload found; check all valid digits and copy to buffer as bcd8\r
+          ub=buffer;\r
+          for (c=cfirst;; c++, ub++) {\r
+            if ((unsigned)(*c-'0')>9) break; // quit if not 0-9\r
+            if (c-cfirst==DECPMAX-1) break;  // too many digits\r
+            *ub=(uByte)(*c-'0');        // good bcd8\r
+            }\r
+          if (*c!='\0') break;          // not all digits, or too many\r
+          num.lsd=ub-1;                 // record new LSD\r
+          }\r
+        } // NaN or sNaN\r
+      error=0;                          // syntax is OK\r
+      } // digits=0 (special expected)\r
+    break;                              // drop out\r
+    }                                   // [for(;;) once-loop]\r
+\r
+  // decShowNum(&num, "fromStr");\r
+\r
+  if (error!=0) {\r
+    set->status|=error;\r
+    num.exponent=DECFLOAT_qNaN;         // set up quiet NaN\r
+    num.sign=0;                         // .. with 0 sign\r
+    buffer[0]=0;                        // .. and coefficient\r
+    num.lsd=buffer;                     // ..\r
+    // decShowNum(&num, "oops");\r
+    }\r
+\r
+  // decShowNum(&num, "dffs");\r
+  decFinalize(result, &num, set);       // round, check, and lay out\r
+  // decFloatShow(result, "fromString");\r
+  return result;\r
+  } // decFloatFromString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatFromWider -- conversion from next-wider format             */\r
+/*                                                                    */\r
+/*  result  is the decFloat format number which gets the result of    */\r
+/*          the conversion                                            */\r
+/*  wider   is the decFloatWider format number which will be narrowed */\r
+/*  set     is the context                                            */\r
+/*  returns result                                                    */\r
+/*                                                                    */\r
+/* Narrowing can cause rounding, overflow, etc., but not Invalid      */\r
+/* operation (sNaNs are copied and do not signal).                    */\r
+/* ------------------------------------------------------------------ */\r
+// narrow-to is not possible for decQuad format numbers; simply omit\r
+#if !QUAD\r
+decFloat * decFloatFromWider(decFloat *result, const decFloatWider *wider,\r
+                             decContext *set) {\r
+  bcdnum num;                           // collects data for finishing\r
+  uByte  bcdar[DECWPMAX];               // room for wider coefficient\r
+  uInt   widerhi=DFWWORD(wider, 0);     // top word\r
+  Int    exp;\r
+\r
+  GETWCOEFF(wider, bcdar);\r
+\r
+  num.msd=bcdar;                        // MSD is here always\r
+  num.lsd=bcdar+DECWPMAX-1;             // LSD is here always\r
+  num.sign=widerhi&0x80000000;          // extract sign [DECFLOAT_Sign=Neg]\r
+\r
+  // decode the wider combination field to exponent\r
+  exp=DECCOMBWEXP[widerhi>>26];         // decode from wider combination field\r
+  // if it is a special there's nothing to do unless sNaN; if it's\r
+  // finite then add the (wider) exponent continuation and unbias\r
+  if (EXPISSPECIAL(exp)) exp=widerhi&0x7e000000; // include sNaN selector\r
+   else exp+=GETWECON(wider)-DECWBIAS;\r
+  num.exponent=exp;\r
+\r
+  // decShowNum(&num, "dffw");\r
+  return decFinalize(result, &num, set);// round, check, and lay out\r
+  } // decFloatFromWider\r
+#endif\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatGetCoefficient -- get coefficient as BCD8                  */\r
+/*                                                                    */\r
+/*  df is the decFloat from which to extract the coefficient          */\r
+/*  bcdar is where DECPMAX bytes will be written, one BCD digit in    */\r
+/*    each byte (BCD8 encoding); if df is a NaN the first byte will   */\r
+/*    be zero, and if it is infinite they will all be zero            */\r
+/*  returns the sign of the coefficient (DECFLOAT_Sign if negative,   */\r
+/*    0 otherwise)                                                    */\r
+/*                                                                    */\r
+/* No error is possible, and no status will be set.  If df is a       */\r
+/* special value the array is set to zeros (for Infinity) or to the   */\r
+/* payload of a qNaN or sNaN.                                         */\r
+/* ------------------------------------------------------------------ */\r
+Int decFloatGetCoefficient(const decFloat *df, uByte *bcdar) {\r
+  if (DFISINF(df)) memset(bcdar, 0, DECPMAX);\r
+   else {\r
+    GETCOEFF(df, bcdar);           // use macro\r
+    if (DFISNAN(df)) bcdar[0]=0;   // MSD needs correcting\r
+    }\r
+  return GETSIGN(df);\r
+  } // decFloatGetCoefficient\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatGetExponent -- get unbiased exponent                       */\r
+/*                                                                    */\r
+/*  df is the decFloat from which to extract the exponent             */\r
+/*  returns the exponent, q.                                          */\r
+/*                                                                    */\r
+/* No error is possible, and no status will be set.  If df is a       */\r
+/* special value the first seven bits of the decFloat are returned,   */\r
+/* left adjusted and with the first (sign) bit set to 0 (followed by  */\r
+/* 25 0 bits).  e.g., -sNaN would return 0x7e000000 (DECFLOAT_sNaN).  */\r
+/* ------------------------------------------------------------------ */\r
+Int decFloatGetExponent(const decFloat *df) {\r
+  if (DFISSPECIAL(df)) return DFWORD(df, 0)&0x7e000000;\r
+  return GETEXPUN(df);\r
+  } // decFloatGetExponent\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatSetCoefficient -- set coefficient from BCD8                */\r
+/*                                                                    */\r
+/*  df is the target decFloat (and source of exponent/special value)  */\r
+/*  bcdar holds DECPMAX digits to set the coefficient from, one       */\r
+/*    digit in each byte (BCD8 encoding); the first (MSD) is ignored  */\r
+/*    if df is a NaN; all are ignored if df is infinite.              */\r
+/*  sig is DECFLOAT_Sign to set the sign bit, 0 otherwise             */\r
+/*  returns df, which will be canonical                               */\r
+/*                                                                    */\r
+/* No error is possible, and no status will be set.                   */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatSetCoefficient(decFloat *df, const uByte *bcdar,\r
+                                  Int sig) {\r
+  uInt exp;                        // for exponent\r
+  uByte bcdzero[DECPMAX];          // for infinities\r
+\r
+  // Exponent/special code is extracted from df\r
+  if (DFISSPECIAL(df)) {\r
+    exp=DFWORD(df, 0)&0x7e000000;\r
+    if (DFISINF(df)) {\r
+      memset(bcdzero, 0, DECPMAX);\r
+      return decFloatFromBCD(df, exp, bcdzero, sig);\r
+      }\r
+    }\r
+   else exp=GETEXPUN(df);\r
+  return decFloatFromBCD(df, exp, bcdar, sig);\r
+  } // decFloatSetCoefficient\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatSetExponent -- set exponent or special value               */\r
+/*                                                                    */\r
+/*  df  is the target decFloat (and source of coefficient/payload)    */\r
+/*  set is the context for reporting status                           */\r
+/*  exp is the unbiased exponent, q, or a special value in the form   */\r
+/*    returned by decFloatGetExponent                                 */\r
+/*  returns df, which will be canonical                               */\r
+/*                                                                    */\r
+/* No error is possible, but Overflow or Underflow might occur.       */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatSetExponent(decFloat *df, decContext *set, Int exp) {\r
+  uByte  bcdcopy[DECPMAX];         // for coefficient\r
+  bcdnum num;                      // work\r
+  num.exponent=exp;\r
+  num.sign=decFloatGetCoefficient(df, bcdcopy); // extract coefficient\r
+  if (DFISSPECIAL(df)) {           // MSD or more needs correcting\r
+    if (DFISINF(df)) memset(bcdcopy, 0, DECPMAX);\r
+    bcdcopy[0]=0;\r
+    }\r
+  num.msd=bcdcopy;\r
+  num.lsd=bcdcopy+DECPMAX-1;\r
+  return decFinalize(df, &num, set);\r
+  } // decFloatSetExponent\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatRadix -- returns the base (10)                             */\r
+/*                                                                    */\r
+/*   df is any decFloat of this format                                */\r
+/* ------------------------------------------------------------------ */\r
+uInt decFloatRadix(const decFloat *df) {\r
+  if (df) return 10;                         // to placate compiler\r
+  return 10;\r
+  } // decFloatRadix\r
+\r
+/* The following function is not available if DECPRINT=0              */\r
+#if DECPRINT\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatShow -- printf a decFloat in hexadecimal and decimal       */\r
+/*   df  is the decFloat to show                                      */\r
+/*   tag is a tag string displayed with the number                    */\r
+/*                                                                    */\r
+/* This is a debug aid; the precise format of the string may change.  */\r
+/* ------------------------------------------------------------------ */\r
+void decFloatShow(const decFloat *df, const char *tag) {\r
+  char hexbuf[DECBYTES*2+DECBYTES/4+1]; // NB blank after every fourth\r
+  char buff[DECSTRING];                 // for value in decimal\r
+  Int i, j=0;\r
+\r
+  for (i=0; i<DECBYTES; i++) {\r
+    #if DECLITEND\r
+      sprintf(&hexbuf[j], "%02x", df->bytes[DECBYTES-1-i]);\r
+    #else\r
+      sprintf(&hexbuf[j], "%02x", df->bytes[i]);\r
+    #endif\r
+    j+=2;\r
+    // the next line adds blank (and terminator) after final pair, too\r
+    if ((i+1)%4==0) {strcpy(&hexbuf[j], " "); j++;}\r
+    }\r
+  decFloatToString(df, buff);\r
+  printf(">%s> %s [big-endian]  %s\n", tag, hexbuf, buff);\r
+  return;\r
+  } // decFloatShow\r
+#endif\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatToBCD -- get sign, exponent, and BCD8 from a decFloat      */\r
+/*                                                                    */\r
+/*  df is the source decFloat                                         */\r
+/*  exp will be set to the unbiased exponent, q, or to a special      */\r
+/*    value in the form returned by decFloatGetExponent               */\r
+/*  bcdar is where DECPMAX bytes will be written, one BCD digit in    */\r
+/*    each byte (BCD8 encoding); if df is a NaN the first byte will   */\r
+/*    be zero, and if it is infinite they will all be zero            */\r
+/*  returns the sign of the coefficient (DECFLOAT_Sign if negative,   */\r
+/*    0 otherwise)                                                    */\r
+/*                                                                    */\r
+/* No error is possible, and no status will be set.                   */\r
+/* ------------------------------------------------------------------ */\r
+Int decFloatToBCD(const decFloat *df, Int *exp, uByte *bcdar) {\r
+  if (DFISINF(df)) {\r
+    memset(bcdar, 0, DECPMAX);\r
+    *exp=DFWORD(df, 0)&0x7e000000;\r
+    }\r
+   else {\r
+    GETCOEFF(df, bcdar);           // use macro\r
+    if (DFISNAN(df)) {\r
+      bcdar[0]=0;                  // MSD needs correcting\r
+      *exp=DFWORD(df, 0)&0x7e000000;\r
+      }\r
+     else {                        // finite\r
+      *exp=GETEXPUN(df);\r
+      }\r
+    }\r
+  return GETSIGN(df);\r
+  } // decFloatToBCD\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatToEngString -- conversion to numeric string, engineering   */\r
+/*                                                                    */\r
+/*  df is the decFloat format number to convert                       */\r
+/*  string is the string where the result will be laid out            */\r
+/*                                                                    */\r
+/* string must be at least DECPMAX+9 characters (the worst case is    */\r
+/* "-0.00000nnn...nnn\0", which is as long as the exponent form when  */\r
+/* DECEMAXD<=4); this condition is asserted above                     */\r
+/*                                                                    */\r
+/* No error is possible, and no status will be set                    */\r
+/* ------------------------------------------------------------------ */\r
+char * decFloatToEngString(const decFloat *df, char *string){\r
+  uInt msd;                        // coefficient MSD\r
+  Int  exp;                        // exponent top two bits or full\r
+  uInt comb;                       // combination field\r
+  char *cstart;                    // coefficient start\r
+  char *c;                         // output pointer in string\r
+  char *s, *t;                     // .. (source, target)\r
+  Int  pre, e;                     // work\r
+  const uByte *u;                  // ..\r
+  uInt  uiwork;                    // for macros [one compiler needs\r
+                                   // volatile here to avoid bug, but\r
+                                   // that doubles execution time]\r
+\r
+  // Source words; macro handles endianness\r
+  uInt sourhi=DFWORD(df, 0);       // word with sign\r
+  #if DECPMAX==16\r
+  uInt sourlo=DFWORD(df, 1);\r
+  #elif DECPMAX==34\r
+  uInt sourmh=DFWORD(df, 1);\r
+  uInt sourml=DFWORD(df, 2);\r
+  uInt sourlo=DFWORD(df, 3);\r
+  #endif\r
+\r
+  c=string;                        // where result will go\r
+  if (((Int)sourhi)<0) *c++='-';   // handle sign\r
+  comb=sourhi>>26;                 // sign+combination field\r
+  msd=DECCOMBMSD[comb];            // decode the combination field\r
+  exp=DECCOMBEXP[comb];            // ..\r
+\r
+  if (EXPISSPECIAL(exp)) {         // special\r
+    if (exp==DECFLOAT_Inf) {       // infinity\r
+      strcpy(c,   "Inf");\r
+      strcpy(c+3, "inity");\r
+      return string;               // easy\r
+      }\r
+    if (sourhi&0x02000000) *c++='s'; // sNaN\r
+    strcpy(c, "NaN");              // complete word\r
+    c+=3;                          // step past\r
+    // quick exit if the payload is zero\r
+    #if DECPMAX==7\r
+    if ((sourhi&0x000fffff)==0) return string;\r
+    #elif DECPMAX==16\r
+    if (sourlo==0 && (sourhi&0x0003ffff)==0) return string;\r
+    #elif DECPMAX==34\r
+    if (sourlo==0 && sourml==0 && sourmh==0\r
+     && (sourhi&0x00003fff)==0) return string;\r
+    #endif\r
+    // otherwise drop through to add integer; set correct exp etc.\r
+    exp=0; msd=0;                  // setup for following code\r
+    }\r
+   else { // complete exponent; top two bits are in place\r
+    exp+=GETECON(df)-DECBIAS;      // .. + continuation and unbias\r
+    }\r
+\r
+  /* convert the digits of the significand to characters */\r
+  cstart=c;                        // save start of coefficient\r
+  if (msd) *c++=(char)('0'+(char)msd);  // non-zero most significant digit\r
+\r
+  // Decode the declets.  After extracting each declet, it is\r
+  // decoded to a 4-uByte sequence by table lookup; the four uBytes\r
+  // are the three encoded BCD8 digits followed by a 1-byte length\r
+  // (significant digits, except that 000 has length 0).  This allows\r
+  // us to left-align the first declet with non-zero content, then\r
+  // the remaining ones are full 3-char length.  Fixed-length copies\r
+  // are used because variable-length memcpy causes a subroutine call\r
+  // in at least two compilers.  (The copies are length 4 for speed\r
+  // and are safe because the last item in the array is of length\r
+  // three and has the length byte following.)\r
+  #define dpd2char(dpdin) u=&DPD2BCD8[((dpdin)&0x3ff)*4];        \\r
+         if (c!=cstart) {UBFROMUI(c, UBTOUI(u)|CHARMASK); c+=3;} \\r
+          else if (*(u+3)) {                                     \\r
+           UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); c+=*(u+3);}\r
+\r
+  #if DECPMAX==7\r
+  dpd2char(sourhi>>10);                 // declet 1\r
+  dpd2char(sourhi);                     // declet 2\r
+\r
+  #elif DECPMAX==16\r
+  dpd2char(sourhi>>8);                  // declet 1\r
+  dpd2char((sourhi<<2) | (sourlo>>30)); // declet 2\r
+  dpd2char(sourlo>>20);                 // declet 3\r
+  dpd2char(sourlo>>10);                 // declet 4\r
+  dpd2char(sourlo);                     // declet 5\r
+\r
+  #elif DECPMAX==34\r
+  dpd2char(sourhi>>4);                  // declet 1\r
+  dpd2char((sourhi<<6) | (sourmh>>26)); // declet 2\r
+  dpd2char(sourmh>>16);                 // declet 3\r
+  dpd2char(sourmh>>6);                  // declet 4\r
+  dpd2char((sourmh<<4) | (sourml>>28)); // declet 5\r
+  dpd2char(sourml>>18);                 // declet 6\r
+  dpd2char(sourml>>8);                  // declet 7\r
+  dpd2char((sourml<<2) | (sourlo>>30)); // declet 8\r
+  dpd2char(sourlo>>20);                 // declet 9\r
+  dpd2char(sourlo>>10);                 // declet 10\r
+  dpd2char(sourlo);                     // declet 11\r
+  #endif\r
+\r
+  if (c==cstart) *c++='0';         // all zeros, empty -- make "0"\r
+\r
+  if (exp==0) {                    // integer or NaN case -- easy\r
+    *c='\0';                       // terminate\r
+    return string;\r
+    }\r
+  /* non-0 exponent */\r
+\r
+  e=0;                             // assume no E\r
+  pre=(Int)(c-cstart)+exp;         // length+exp  [c->LSD+1]\r
+  // [here, pre-exp is the digits count (==1 for zero)]\r
+\r
+  if (exp>0 || pre<-5) {           // need exponential form\r
+    e=pre-1;                       // calculate E value\r
+    pre=1;                         // assume one digit before '.'\r
+    if (e!=0) {                    // engineering: may need to adjust\r
+      Int adj;                     // adjustment\r
+      // The C remainder operator is undefined for negative numbers, so\r
+      // a positive remainder calculation must be used here\r
+      if (e<0) {\r
+        adj=(-e)%3;\r
+        if (adj!=0) adj=3-adj;\r
+        }\r
+       else { // e>0\r
+        adj=e%3;\r
+        }\r
+      e=e-adj;\r
+      // if dealing with zero still produce an exponent which is a\r
+      // multiple of three, as expected, but there will only be the\r
+      // one zero before the E, still.  Otherwise note the padding.\r
+      if (!DFISZERO(df)) pre+=adj;\r
+       else {  // is zero\r
+        if (adj!=0) {              // 0.00Esnn needed\r
+          e=e+3;\r
+          pre=-(2-adj);\r
+          }\r
+        } // zero\r
+      } // engineering adjustment\r
+    } // exponential form\r
+  // printf("e=%ld pre=%ld exp=%ld\n", (LI)e, (LI)pre, (LI)exp);\r
+\r
+  /* modify the coefficient, adding 0s, '.', and E+nn as needed */\r
+  if (pre>0) {                     // ddd.ddd (plain), perhaps with E\r
+                                   // or dd00 padding for engineering\r
+    char *dotat=cstart+pre;\r
+    if (dotat<c) {                      // if embedded dot needed...\r
+      // move by fours; there must be space for junk at the end\r
+      // because there is still space for exponent\r
+      s=dotat+ROUNDDOWN4(c-dotat);      // source\r
+      t=s+1;                            // target\r
+      // open the gap [cannot use memcpy]\r
+      for (; s>=dotat; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));\r
+      *dotat='.';\r
+      c++;                              // length increased by one\r
+      } // need dot?\r
+     else for (; c<dotat; c++) *c='0';  // pad for engineering\r
+    } // pre>0\r
+   else {\r
+    /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (may have\r
+       E, but only for 0.00E+3 kind of case -- with plenty of spare\r
+       space in this case */\r
+    pre=-pre+2;                         // gap width, including "0."\r
+    t=cstart+ROUNDDOWN4(c-cstart)+pre;  // preferred first target point\r
+    // backoff if too far to the right\r
+    if (t>string+DECSTRING-5) t=string+DECSTRING-5; // adjust to fit\r
+    // now shift the entire coefficient to the right, being careful not\r
+    // to access to the left of string [cannot use memcpy]\r
+    for (s=t-pre; s>=string; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));\r
+    // for Quads and Singles there may be a character or two left...\r
+    s+=3;                               // where next would come from\r
+    for(; s>=cstart; s--, t--) *(t+3)=*(s);\r
+    // now have fill 0. through 0.00000; use overlaps to avoid tests\r
+    if (pre>=4) {\r
+      memcpy(cstart+pre-4, "0000", 4);\r
+      memcpy(cstart, "0.00", 4);\r
+      }\r
+     else { // 2 or 3\r
+      *(cstart+pre-1)='0';\r
+      memcpy(cstart, "0.", 2);\r
+      }\r
+    c+=pre;                             // to end\r
+    }\r
+\r
+  // finally add the E-part, if needed; it will never be 0, and has\r
+  // a maximum length of 3 or 4 digits (asserted above)\r
+  if (e!=0) {\r
+    memcpy(c, "E+", 2);                 // starts with E, assume +\r
+    c++;\r
+    if (e<0) {\r
+      *c='-';                           // oops, need '-'\r
+      e=-e;                             // uInt, please\r
+      }\r
+    c++;\r
+    // Three-character exponents are easy; 4-character a little trickier\r
+    #if DECEMAXD<=3\r
+      u=&BIN2BCD8[e*4];                 // -> 3 digits + length byte\r
+      // copy fixed 4 characters [is safe], starting at non-zero\r
+      // and with character mask to convert BCD to char\r
+      UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK);\r
+      c+=*(u+3);                        // bump pointer appropriately\r
+    #elif DECEMAXD==4\r
+      if (e<1000) {                     // 3 (or fewer) digits case\r
+        u=&BIN2BCD8[e*4];               // -> 3 digits + length byte\r
+        UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]\r
+        c+=*(u+3);                      // bump pointer appropriately\r
+        }\r
+       else {                           // 4-digits\r
+        Int thou=((e>>3)*1049)>>17;     // e/1000\r
+        Int rem=e-(1000*thou);          // e%1000\r
+        *c++=(char)('0'+(char)thou);    // the thousands digit\r
+        u=&BIN2BCD8[rem*4];             // -> 3 digits + length byte\r
+        UBFROMUI(c, UBTOUI(u)|CHARMASK);// copy fixed 3+1 characters [is safe]\r
+        c+=3;                           // bump pointer, always 3 digits\r
+        }\r
+    #endif\r
+    }\r
+  *c='\0';                              // terminate\r
+  //printf("res %s\n", string);\r
+  return string;\r
+  } // decFloatToEngString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatToPacked -- convert decFloat to Packed decimal + exponent  */\r
+/*                                                                    */\r
+/*  df is the source decFloat                                         */\r
+/*  exp will be set to the unbiased exponent, q, or to a special      */\r
+/*    value in the form returned by decFloatGetExponent               */\r
+/*  packed is where DECPMAX nibbles will be written with the sign as  */\r
+/*    final nibble (0x0c for +, 0x0d for -); a NaN has a first nibble */\r
+/*    of zero, and an infinity is all zeros. decDouble and decQuad    */\r
+/*    have a additional leading zero nibble, leading to result        */\r
+/*    lengths of 4, 9, and 18 bytes.                                  */\r
+/*  returns the sign of the coefficient (DECFLOAT_Sign if negative,   */\r
+/*    0 otherwise)                                                    */\r
+/*                                                                    */\r
+/* No error is possible, and no status will be set.                   */\r
+/* ------------------------------------------------------------------ */\r
+Int decFloatToPacked(const decFloat *df, Int *exp, uByte *packed) {\r
+  uByte bcdar[DECPMAX+2];          // work buffer\r
+  uByte *ip=bcdar, *op=packed;     // work pointers\r
+  if (DFISINF(df)) {\r
+    memset(bcdar, 0, DECPMAX+2);\r
+    *exp=DECFLOAT_Inf;\r
+    }\r
+   else {\r
+    GETCOEFF(df, bcdar+1);         // use macro\r
+    if (DFISNAN(df)) {\r
+      bcdar[1]=0;                  // MSD needs clearing\r
+      *exp=DFWORD(df, 0)&0x7e000000;\r
+      }\r
+     else {                        // finite\r
+      *exp=GETEXPUN(df);\r
+      }\r
+    }\r
+  // now pack; coefficient currently at bcdar+1\r
+  #if SINGLE\r
+    ip++;                          // ignore first byte\r
+  #else\r
+    *ip=0;                         // need leading zero\r
+  #endif\r
+  // set final byte to Packed BCD sign value\r
+  bcdar[DECPMAX+1]=(DFISSIGNED(df) ? DECPMINUS : DECPPLUS);\r
+  // pack an even number of bytes...\r
+  for (; op<packed+((DECPMAX+2)/2); op++, ip+=2) {\r
+    *op=(uByte)((*ip<<4)+*(ip+1));\r
+    }\r
+  return (bcdar[DECPMAX+1]==DECPMINUS ? DECFLOAT_Sign : 0);\r
+  } // decFloatToPacked\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatToString -- conversion to numeric string                   */\r
+/*                                                                    */\r
+/*  df is the decFloat format number to convert                       */\r
+/*  string is the string where the result will be laid out            */\r
+/*                                                                    */\r
+/* string must be at least DECPMAX+9 characters (the worst case is    */\r
+/* "-0.00000nnn...nnn\0", which is as long as the exponent form when  */\r
+/* DECEMAXD<=4); this condition is asserted above                     */\r
+/*                                                                    */\r
+/* No error is possible, and no status will be set                    */\r
+/* ------------------------------------------------------------------ */\r
+char * decFloatToString(const decFloat *df, char *string){\r
+  uInt msd;                        // coefficient MSD\r
+  Int  exp;                        // exponent top two bits or full\r
+  uInt comb;                       // combination field\r
+  char *cstart;                    // coefficient start\r
+  char *c;                         // output pointer in string\r
+  char *s, *t;                     // .. (source, target)\r
+  Int  pre, e;                     // work\r
+  const uByte *u;                  // ..\r
+  uInt  uiwork;                    // for macros [one compiler needs\r
+                                   // volatile here to avoid bug, but\r
+                                   // that doubles execution time]\r
+\r
+  // Source words; macro handles endianness\r
+  uInt sourhi=DFWORD(df, 0);       // word with sign\r
+  #if DECPMAX==16\r
+  uInt sourlo=DFWORD(df, 1);\r
+  #elif DECPMAX==34\r
+  uInt sourmh=DFWORD(df, 1);\r
+  uInt sourml=DFWORD(df, 2);\r
+  uInt sourlo=DFWORD(df, 3);\r
+  #endif\r
+\r
+  c=string;                        // where result will go\r
+  if (((Int)sourhi)<0) *c++='-';   // handle sign\r
+  comb=sourhi>>26;                 // sign+combination field\r
+  msd=DECCOMBMSD[comb];            // decode the combination field\r
+  exp=DECCOMBEXP[comb];            // ..\r
+\r
+  if (!EXPISSPECIAL(exp)) {        // finite\r
+    // complete exponent; top two bits are in place\r
+    exp+=GETECON(df)-DECBIAS;      // .. + continuation and unbias\r
+    }\r
+   else {                          // IS special\r
+    if (exp==DECFLOAT_Inf) {       // infinity\r
+      strcpy(c, "Infinity");\r
+      return string;               // easy\r
+      }\r
+    if (sourhi&0x02000000) *c++='s'; // sNaN\r
+    strcpy(c, "NaN");              // complete word\r
+    c+=3;                          // step past\r
+    // quick exit if the payload is zero\r
+    #if DECPMAX==7\r
+    if ((sourhi&0x000fffff)==0) return string;\r
+    #elif DECPMAX==16\r
+    if (sourlo==0 && (sourhi&0x0003ffff)==0) return string;\r
+    #elif DECPMAX==34\r
+    if (sourlo==0 && sourml==0 && sourmh==0\r
+     && (sourhi&0x00003fff)==0) return string;\r
+    #endif\r
+    // otherwise drop through to add integer; set correct exp etc.\r
+    exp=0; msd=0;                  // setup for following code\r
+    }\r
+\r
+  /* convert the digits of the significand to characters */\r
+  cstart=c;                        // save start of coefficient\r
+  if (msd) *c++=(char)('0'+(char)msd);  // non-zero most significant digit\r
+\r
+  // Decode the declets.  After extracting each declet, it is\r
+  // decoded to a 4-uByte sequence by table lookup; the four uBytes\r
+  // are the three encoded BCD8 digits followed by a 1-byte length\r
+  // (significant digits, except that 000 has length 0).  This allows\r
+  // us to left-align the first declet with non-zero content, then\r
+  // the remaining ones are full 3-char length.  Fixed-length copies\r
+  // are used because variable-length memcpy causes a subroutine call\r
+  // in at least two compilers.  (The copies are length 4 for speed\r
+  // and are safe because the last item in the array is of length\r
+  // three and has the length byte following.)\r
+  #define dpd2char(dpdin) u=&DPD2BCD8[((dpdin)&0x3ff)*4];        \\r
+         if (c!=cstart) {UBFROMUI(c, UBTOUI(u)|CHARMASK); c+=3;} \\r
+          else if (*(u+3)) {                                     \\r
+           UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); c+=*(u+3);}\r
+\r
+  #if DECPMAX==7\r
+  dpd2char(sourhi>>10);                 // declet 1\r
+  dpd2char(sourhi);                     // declet 2\r
+\r
+  #elif DECPMAX==16\r
+  dpd2char(sourhi>>8);                  // declet 1\r
+  dpd2char((sourhi<<2) | (sourlo>>30)); // declet 2\r
+  dpd2char(sourlo>>20);                 // declet 3\r
+  dpd2char(sourlo>>10);                 // declet 4\r
+  dpd2char(sourlo);                     // declet 5\r
+\r
+  #elif DECPMAX==34\r
+  dpd2char(sourhi>>4);                  // declet 1\r
+  dpd2char((sourhi<<6) | (sourmh>>26)); // declet 2\r
+  dpd2char(sourmh>>16);                 // declet 3\r
+  dpd2char(sourmh>>6);                  // declet 4\r
+  dpd2char((sourmh<<4) | (sourml>>28)); // declet 5\r
+  dpd2char(sourml>>18);                 // declet 6\r
+  dpd2char(sourml>>8);                  // declet 7\r
+  dpd2char((sourml<<2) | (sourlo>>30)); // declet 8\r
+  dpd2char(sourlo>>20);                 // declet 9\r
+  dpd2char(sourlo>>10);                 // declet 10\r
+  dpd2char(sourlo);                     // declet 11\r
+  #endif\r
+\r
+  if (c==cstart) *c++='0';         // all zeros, empty -- make "0"\r
+\r
+  //[This fast path is valid but adds 3-5 cycles to worst case length]\r
+  //if (exp==0) {                  // integer or NaN case -- easy\r
+  //  *c='\0';                     // terminate\r
+  //  return string;\r
+  //  }\r
+\r
+  e=0;                             // assume no E\r
+  pre=(Int)(c-cstart)+exp;         // length+exp  [c->LSD+1]\r
+  // [here, pre-exp is the digits count (==1 for zero)]\r
+\r
+  if (exp>0 || pre<-5) {           // need exponential form\r
+    e=pre-1;                       // calculate E value\r
+    pre=1;                         // assume one digit before '.'\r
+    } // exponential form\r
+\r
+  /* modify the coefficient, adding 0s, '.', and E+nn as needed */\r
+  if (pre>0) {                     // ddd.ddd (plain), perhaps with E\r
+    char *dotat=cstart+pre;\r
+    if (dotat<c) {                      // if embedded dot needed...\r
+      // [memmove is a disaster, here]\r
+      // move by fours; there must be space for junk at the end\r
+      // because exponent is still possible\r
+      s=dotat+ROUNDDOWN4(c-dotat);      // source\r
+      t=s+1;                            // target\r
+      // open the gap [cannot use memcpy]\r
+      for (; s>=dotat; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));\r
+      *dotat='.';\r
+      c++;                              // length increased by one\r
+      } // need dot?\r
+\r
+    // finally add the E-part, if needed; it will never be 0, and has\r
+    // a maximum length of 3 or 4 digits (asserted above)\r
+    if (e!=0) {\r
+      memcpy(c, "E+", 2);               // starts with E, assume +\r
+      c++;\r
+      if (e<0) {\r
+        *c='-';                         // oops, need '-'\r
+        e=-e;                           // uInt, please\r
+        }\r
+      c++;\r
+      // Three-character exponents are easy; 4-character a little trickier\r
+      #if DECEMAXD<=3\r
+        u=&BIN2BCD8[e*4];               // -> 3 digits + length byte\r
+        // copy fixed 4 characters [is safe], starting at non-zero\r
+        // and with character mask to convert BCD to char\r
+        UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK);\r
+        c+=*(u+3);                      // bump pointer appropriately\r
+      #elif DECEMAXD==4\r
+        if (e<1000) {                   // 3 (or fewer) digits case\r
+          u=&BIN2BCD8[e*4];             // -> 3 digits + length byte\r
+          UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]\r
+          c+=*(u+3);                    // bump pointer appropriately\r
+          }\r
+         else {                         // 4-digits\r
+          Int thou=((e>>3)*1049)>>17;   // e/1000\r
+          Int rem=e-(1000*thou);        // e%1000\r
+          *c++=(char)('0'+(char)thou);  // the thousands digit\r
+          u=&BIN2BCD8[rem*4];           // -> 3 digits + length byte\r
+          UBFROMUI(c, UBTOUI(u)|CHARMASK); // copy fixed 3+1 characters [is safe]\r
+          c+=3;                         // bump pointer, always 3 digits\r
+          }\r
+      #endif\r
+      }\r
+    *c='\0';                            // add terminator\r
+    //printf("res %s\n", string);\r
+    return string;\r
+    } // pre>0\r
+\r
+  /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */\r
+  // Surprisingly, this is close to being the worst-case path, so the\r
+  // shift is done by fours; this is a little tricky because the\r
+  // rightmost character to be written must not be beyond where the\r
+  // rightmost terminator could be -- so backoff to not touch\r
+  // terminator position if need be (this can make exact alignments\r
+  // for full Doubles, but in some cases needs care not to access too\r
+  // far to the left)\r
+\r
+  pre=-pre+2;                           // gap width, including "0."\r
+  t=cstart+ROUNDDOWN4(c-cstart)+pre;    // preferred first target point\r
+  // backoff if too far to the right\r
+  if (t>string+DECSTRING-5) t=string+DECSTRING-5; // adjust to fit\r
+  // now shift the entire coefficient to the right, being careful not\r
+  // to access to the left of string [cannot use memcpy]\r
+  for (s=t-pre; s>=string; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));\r
+  // for Quads and Singles there may be a character or two left...\r
+  s+=3;                                 // where next would come from\r
+  for(; s>=cstart; s--, t--) *(t+3)=*(s);\r
+  // now have fill 0. through 0.00000; use overlaps to avoid tests\r
+  if (pre>=4) {\r
+    memcpy(cstart+pre-4, "0000", 4);\r
+    memcpy(cstart, "0.00", 4);\r
+    }\r
+   else { // 2 or 3\r
+    *(cstart+pre-1)='0';\r
+    memcpy(cstart, "0.", 2);\r
+    }\r
+  *(c+pre)='\0';                        // terminate\r
+  return string;\r
+  } // decFloatToString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatToWider -- conversion to next-wider format                 */\r
+/*                                                                    */\r
+/*  source  is the decFloat format number which gets the result of    */\r
+/*          the conversion                                            */\r
+/*  wider   is the decFloatWider format number which will be narrowed */\r
+/*  returns wider                                                     */\r
+/*                                                                    */\r
+/* Widening is always exact; no status is set (sNaNs are copied and   */\r
+/* do not signal).  The result will be canonical if the source is,    */\r
+/* and may or may not be if the source is not.                        */\r
+/* ------------------------------------------------------------------ */\r
+// widening is not possible for decQuad format numbers; simply omit\r
+#if !QUAD\r
+decFloatWider * decFloatToWider(const decFloat *source, decFloatWider *wider) {\r
+  uInt msd;\r
+\r
+  /* Construct and copy the sign word */\r
+  if (DFISSPECIAL(source)) {\r
+    // copy sign, combination, and first bit of exponent (sNaN selector)\r
+    DFWWORD(wider, 0)=DFWORD(source, 0)&0xfe000000;\r
+    msd=0;\r
+    }\r
+   else { // is finite number\r
+    uInt exp=GETEXPUN(source)+DECWBIAS; // get unbiased exponent and rebias\r
+    uInt code=(exp>>DECWECONL)<<29;     // set two bits of exp [msd=0]\r
+    code|=(exp<<(32-6-DECWECONL)) & 0x03ffffff; // add exponent continuation\r
+    code|=DFWORD(source, 0)&0x80000000; // add sign\r
+    DFWWORD(wider, 0)=code;             // .. and place top word in wider\r
+    msd=GETMSD(source);                 // get source coefficient MSD [0-9]\r
+    }\r
+  /* Copy the coefficient and clear any 'unused' words to left */\r
+  #if SINGLE\r
+    DFWWORD(wider, 1)=(DFWORD(source, 0)&0x000fffff)|(msd<<20);\r
+  #elif DOUBLE\r
+    DFWWORD(wider, 2)=(DFWORD(source, 0)&0x0003ffff)|(msd<<18);\r
+    DFWWORD(wider, 3)=DFWORD(source, 1);\r
+    DFWWORD(wider, 1)=0;\r
+  #endif\r
+  return wider;\r
+  } // decFloatToWider\r
+#endif\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatVersion -- return package version string                   */\r
+/*                                                                    */\r
+/*  returns a constant string describing this package                 */\r
+/* ------------------------------------------------------------------ */\r
+const char *decFloatVersion(void) {\r
+  return DECVERSION;\r
+  } // decFloatVersion\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFloatZero -- set to canonical (integer) zero                    */\r
+/*                                                                    */\r
+/*  df is the decFloat format number to integer +0 (q=0, c=+0)        */\r
+/*  returns df                                                        */\r
+/*                                                                    */\r
+/* No error is possible, and no status can be set.                    */\r
+/* ------------------------------------------------------------------ */\r
+decFloat * decFloatZero(decFloat *df){\r
+  DFWORD(df, 0)=ZEROWORD;     // set appropriate top word\r
+  #if DOUBLE || QUAD\r
+    DFWORD(df, 1)=0;\r
+    #if QUAD\r
+      DFWORD(df, 2)=0;\r
+      DFWORD(df, 3)=0;\r
+    #endif\r
+  #endif\r
+  // decFloatShow(df, "zero");\r
+  return df;\r
+  } // decFloatZero\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* Private generic function (not format-specific) for development use */\r
+/* ------------------------------------------------------------------ */\r
+// This is included once only, for all to use\r
+#if QUAD && (DECCHECK || DECTRACE)\r
+  /* ---------------------------------------------------------------- */\r
+  /* decShowNum -- display bcd8 number in debug form                  */\r
+  /*                                                                  */\r
+  /*   num is the bcdnum to display                                   */\r
+  /*   tag is a string to label the display                           */\r
+  /* ---------------------------------------------------------------- */\r
+  void decShowNum(const bcdnum *num, const char *tag) {\r
+    const char *csign="+";              // sign character\r
+    uByte *ub;                          // work\r
+    uInt  uiwork;                       // for macros\r
+    if (num->sign==DECFLOAT_Sign) csign="-";\r
+\r
+    printf(">%s> ", tag);\r
+    if (num->exponent==DECFLOAT_Inf) printf("%sInfinity", csign);\r
+    else if (num->exponent==DECFLOAT_qNaN) printf("%sqNaN", csign);\r
+    else if (num->exponent==DECFLOAT_sNaN) printf("%ssNaN", csign);\r
+    else {                              // finite\r
+     char qbuf[10];                     // for right-aligned q\r
+     char *c;                           // work\r
+     const uByte *u;                    // ..\r
+     Int e=num->exponent;               // .. exponent\r
+     strcpy(qbuf, "q=");\r
+     c=&qbuf[2];                        // where exponent will go\r
+     // lay out the exponent\r
+     if (e<0) {\r
+       *c++='-';                        // add '-'\r
+       e=-e;                            // uInt, please\r
+       }\r
+     #if DECEMAXD>4\r
+       #error Exponent form is too long for ShowNum to lay out\r
+     #endif\r
+     if (e==0) *c++='0';                // 0-length case\r
+      else if (e<1000) {                // 3 (or fewer) digits case\r
+       u=&BIN2BCD8[e*4];                // -> 3 digits + length byte\r
+       UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]\r
+       c+=*(u+3);                       // bump pointer appropriately\r
+       }\r
+      else {                            // 4-digits\r
+       Int thou=((e>>3)*1049)>>17;      // e/1000\r
+       Int rem=e-(1000*thou);           // e%1000\r
+       *c++=(char)('0'+(char)thou);     // the thousands digit\r
+       u=&BIN2BCD8[rem*4];              // -> 3 digits + length byte\r
+       UBFROMUI(c, UBTOUI(u)|CHARMASK); // copy fixed 3+1 characters [is safe]\r
+       c+=3;                            // bump pointer, always 3 digits\r
+       }\r
+     *c='\0';                           // add terminator\r
+     printf("%7s c=%s", qbuf, csign);\r
+     }\r
+\r
+    if (!EXPISSPECIAL(num->exponent) || num->msd!=num->lsd || *num->lsd!=0) {\r
+      for (ub=num->msd; ub<=num->lsd; ub++) { // coefficient...\r
+        printf("%1x", *ub);\r
+        if ((num->lsd-ub)%3==0 && ub!=num->lsd) printf(" "); // 4-space\r
+        }\r
+      }\r
+    printf("\n");\r
+    } // decShowNum\r
+#endif\r
diff --git a/src/decNumber/decContext.c b/src/decNumber/decContext.c
new file mode 100644 (file)
index 0000000..9f99759
--- /dev/null
@@ -0,0 +1,437 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Context module                                             */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2009.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises the routines for handling arithmetic         */\r
+/* context structures.                                                */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#include <string.h>           // for strcmp\r
+#include <stdio.h>            // for printf if DECCHECK\r
+#include "decContext.h"       // context and base types\r
+#include "decNumberLocal.h"   // decNumber local types, etc.\r
+\r
+/* compile-time endian tester [assumes sizeof(Int)>1] */\r
+static  const  Int mfcone=1;                       // constant 1\r
+static  const  Flag *mfctop=(const Flag *)&mfcone; // -> top byte\r
+#define LITEND *mfctop        // named flag; 1=little-endian\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* round-for-reround digits                                           */\r
+/* ------------------------------------------------------------------ */\r
+const uByte DECSTICKYTAB[10]={1,1,2,3,4,6,6,7,8,9}; /* used if sticky */\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* Powers of ten (powers[n]==10**n, 0<=n<=9)                          */\r
+/* ------------------------------------------------------------------ */\r
+const uInt DECPOWERS[10]={1, 10, 100, 1000, 10000, 100000, 1000000,\r
+                          10000000, 100000000, 1000000000};\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextClearStatus -- clear bits in current status              */\r
+/*                                                                    */\r
+/*  context is the context structure to be queried                    */\r
+/*  mask indicates the bits to be cleared (the status bit that        */\r
+/*    corresponds to each 1 bit in the mask is cleared)               */\r
+/*  returns context                                                   */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decContext *decContextClearStatus(decContext *context, uInt mask) {\r
+  context->status&=~mask;\r
+  return context;\r
+  } // decContextClearStatus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextDefault -- initialize a context structure                */\r
+/*                                                                    */\r
+/*  context is the structure to be initialized                        */\r
+/*  kind selects the required set of default values, one of:          */\r
+/*      DEC_INIT_BASE       -- select ANSI X3-274 defaults            */\r
+/*      DEC_INIT_DECIMAL32  -- select IEEE 754 defaults, 32-bit       */\r
+/*      DEC_INIT_DECIMAL64  -- select IEEE 754 defaults, 64-bit       */\r
+/*      DEC_INIT_DECIMAL128 -- select IEEE 754 defaults, 128-bit      */\r
+/*      For any other value a valid context is returned, but with     */\r
+/*      Invalid_operation set in the status field.                    */\r
+/*  returns a context structure with the appropriate initial values.  */\r
+/* ------------------------------------------------------------------ */\r
+decContext * decContextDefault(decContext *context, Int kind) {\r
+  // set defaults...\r
+  context->digits=9;                         // 9 digits\r
+  context->emax=DEC_MAX_EMAX;                // 9-digit exponents\r
+  context->emin=DEC_MIN_EMIN;                // .. balanced\r
+  context->round=DEC_ROUND_HALF_UP;          // 0.5 rises\r
+  context->traps=DEC_Errors;                 // all but informational\r
+  context->status=0;                         // cleared\r
+  context->clamp=0;                          // no clamping\r
+  #if DECSUBSET\r
+  context->extended=0;                       // cleared\r
+  #endif\r
+  switch (kind) {\r
+    case DEC_INIT_BASE:\r
+      // [use defaults]\r
+      break;\r
+    case DEC_INIT_DECIMAL32:\r
+      context->digits=7;                     // digits\r
+      context->emax=96;                      // Emax\r
+      context->emin=-95;                     // Emin\r
+      context->round=DEC_ROUND_HALF_EVEN;    // 0.5 to nearest even\r
+      context->traps=0;                      // no traps set\r
+      context->clamp=1;                      // clamp exponents\r
+      #if DECSUBSET\r
+      context->extended=1;                   // set\r
+      #endif\r
+      break;\r
+    case DEC_INIT_DECIMAL64:\r
+      context->digits=16;                    // digits\r
+      context->emax=384;                     // Emax\r
+      context->emin=-383;                    // Emin\r
+      context->round=DEC_ROUND_HALF_EVEN;    // 0.5 to nearest even\r
+      context->traps=0;                      // no traps set\r
+      context->clamp=1;                      // clamp exponents\r
+      #if DECSUBSET\r
+      context->extended=1;                   // set\r
+      #endif\r
+      break;\r
+    case DEC_INIT_DECIMAL128:\r
+      context->digits=34;                    // digits\r
+      context->emax=6144;                    // Emax\r
+      context->emin=-6143;                   // Emin\r
+      context->round=DEC_ROUND_HALF_EVEN;    // 0.5 to nearest even\r
+      context->traps=0;                      // no traps set\r
+      context->clamp=1;                      // clamp exponents\r
+      #if DECSUBSET\r
+      context->extended=1;                   // set\r
+      #endif\r
+      break;\r
+\r
+    default:                                 // invalid Kind\r
+      // use defaults, and ..\r
+      decContextSetStatus(context, DEC_Invalid_operation); // trap\r
+    }\r
+\r
+  return context;} // decContextDefault\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextGetRounding -- return current rounding mode              */\r
+/*                                                                    */\r
+/*  context is the context structure to be queried                    */\r
+/*  returns the rounding mode                                         */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+enum rounding decContextGetRounding(decContext *context) {\r
+  return context->round;\r
+  } // decContextGetRounding\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextGetStatus -- return current status                       */\r
+/*                                                                    */\r
+/*  context is the context structure to be queried                    */\r
+/*  returns status                                                    */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+uInt decContextGetStatus(decContext *context) {\r
+  return context->status;\r
+  } // decContextGetStatus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextRestoreStatus -- restore bits in current status          */\r
+/*                                                                    */\r
+/*  context is the context structure to be updated                    */\r
+/*  newstatus is the source for the bits to be restored               */\r
+/*  mask indicates the bits to be restored (the status bit that       */\r
+/*    corresponds to each 1 bit in the mask is set to the value of    */\r
+/*    the correspnding bit in newstatus)                              */\r
+/*  returns context                                                   */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decContext *decContextRestoreStatus(decContext *context,\r
+                                    uInt newstatus, uInt mask) {\r
+  context->status&=~mask;               // clear the selected bits\r
+  context->status|=(mask&newstatus);    // or in the new bits\r
+  return context;\r
+  } // decContextRestoreStatus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextSaveStatus -- save bits in current status                */\r
+/*                                                                    */\r
+/*  context is the context structure to be queried                    */\r
+/*  mask indicates the bits to be saved (the status bits that         */\r
+/*    correspond to each 1 bit in the mask are saved)                 */\r
+/*  returns the AND of the mask and the current status                */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+uInt decContextSaveStatus(decContext *context, uInt mask) {\r
+  return context->status&mask;\r
+  } // decContextSaveStatus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextSetRounding -- set current rounding mode                 */\r
+/*                                                                    */\r
+/*  context is the context structure to be updated                    */\r
+/*  newround is the value which will replace the current mode         */\r
+/*  returns context                                                   */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decContext *decContextSetRounding(decContext *context,\r
+                                  enum rounding newround) {\r
+  context->round=newround;\r
+  return context;\r
+  } // decContextSetRounding\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextSetStatus -- set status and raise trap if appropriate    */\r
+/*                                                                    */\r
+/*  context is the context structure to be updated                    */\r
+/*  status  is the DEC_ exception code                                */\r
+/*  returns the context structure                                     */\r
+/*                                                                    */\r
+/* Control may never return from this routine, if there is a signal   */\r
+/* handler and it takes a long jump.                                  */\r
+/* ------------------------------------------------------------------ */\r
+decContext * decContextSetStatus(decContext *context, uInt status) {\r
+  context->status|=status;\r
+  if (status & context->traps) raise(SIGFPE);\r
+  return context;} // decContextSetStatus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextSetStatusFromString -- set status from a string + trap   */\r
+/*                                                                    */\r
+/*  context is the context structure to be updated                    */\r
+/*  string is a string exactly equal to one that might be returned    */\r
+/*            by decContextStatusToString                             */\r
+/*                                                                    */\r
+/*  The status bit corresponding to the string is set, and a trap     */\r
+/*  is raised if appropriate.                                         */\r
+/*                                                                    */\r
+/*  returns the context structure, unless the string is equal to      */\r
+/*    DEC_Condition_MU or is not recognized.  In these cases NULL is  */\r
+/*    returned.                                                       */\r
+/* ------------------------------------------------------------------ */\r
+decContext * decContextSetStatusFromString(decContext *context,\r
+                                           const char *string) {\r
+  if (strcmp(string, DEC_Condition_CS)==0)\r
+    return decContextSetStatus(context, DEC_Conversion_syntax);\r
+  if (strcmp(string, DEC_Condition_DZ)==0)\r
+    return decContextSetStatus(context, DEC_Division_by_zero);\r
+  if (strcmp(string, DEC_Condition_DI)==0)\r
+    return decContextSetStatus(context, DEC_Division_impossible);\r
+  if (strcmp(string, DEC_Condition_DU)==0)\r
+    return decContextSetStatus(context, DEC_Division_undefined);\r
+  if (strcmp(string, DEC_Condition_IE)==0)\r
+    return decContextSetStatus(context, DEC_Inexact);\r
+  if (strcmp(string, DEC_Condition_IS)==0)\r
+    return decContextSetStatus(context, DEC_Insufficient_storage);\r
+  if (strcmp(string, DEC_Condition_IC)==0)\r
+    return decContextSetStatus(context, DEC_Invalid_context);\r
+  if (strcmp(string, DEC_Condition_IO)==0)\r
+    return decContextSetStatus(context, DEC_Invalid_operation);\r
+  #if DECSUBSET\r
+  if (strcmp(string, DEC_Condition_LD)==0)\r
+    return decContextSetStatus(context, DEC_Lost_digits);\r
+  #endif\r
+  if (strcmp(string, DEC_Condition_OV)==0)\r
+    return decContextSetStatus(context, DEC_Overflow);\r
+  if (strcmp(string, DEC_Condition_PA)==0)\r
+    return decContextSetStatus(context, DEC_Clamped);\r
+  if (strcmp(string, DEC_Condition_RO)==0)\r
+    return decContextSetStatus(context, DEC_Rounded);\r
+  if (strcmp(string, DEC_Condition_SU)==0)\r
+    return decContextSetStatus(context, DEC_Subnormal);\r
+  if (strcmp(string, DEC_Condition_UN)==0)\r
+    return decContextSetStatus(context, DEC_Underflow);\r
+  if (strcmp(string, DEC_Condition_ZE)==0)\r
+    return context;\r
+  return NULL;  // Multiple status, or unknown\r
+  } // decContextSetStatusFromString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextSetStatusFromStringQuiet -- set status from a string     */\r
+/*                                                                    */\r
+/*  context is the context structure to be updated                    */\r
+/*  string is a string exactly equal to one that might be returned    */\r
+/*            by decContextStatusToString                             */\r
+/*                                                                    */\r
+/*  The status bit corresponding to the string is set; no trap is     */\r
+/*  raised.                                                           */\r
+/*                                                                    */\r
+/*  returns the context structure, unless the string is equal to      */\r
+/*    DEC_Condition_MU or is not recognized.  In these cases NULL is  */\r
+/*    returned.                                                       */\r
+/* ------------------------------------------------------------------ */\r
+decContext * decContextSetStatusFromStringQuiet(decContext *context,\r
+                                                const char *string) {\r
+  if (strcmp(string, DEC_Condition_CS)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Conversion_syntax);\r
+  if (strcmp(string, DEC_Condition_DZ)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Division_by_zero);\r
+  if (strcmp(string, DEC_Condition_DI)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Division_impossible);\r
+  if (strcmp(string, DEC_Condition_DU)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Division_undefined);\r
+  if (strcmp(string, DEC_Condition_IE)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Inexact);\r
+  if (strcmp(string, DEC_Condition_IS)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Insufficient_storage);\r
+  if (strcmp(string, DEC_Condition_IC)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Invalid_context);\r
+  if (strcmp(string, DEC_Condition_IO)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Invalid_operation);\r
+  #if DECSUBSET\r
+  if (strcmp(string, DEC_Condition_LD)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Lost_digits);\r
+  #endif\r
+  if (strcmp(string, DEC_Condition_OV)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Overflow);\r
+  if (strcmp(string, DEC_Condition_PA)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Clamped);\r
+  if (strcmp(string, DEC_Condition_RO)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Rounded);\r
+  if (strcmp(string, DEC_Condition_SU)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Subnormal);\r
+  if (strcmp(string, DEC_Condition_UN)==0)\r
+    return decContextSetStatusQuiet(context, DEC_Underflow);\r
+  if (strcmp(string, DEC_Condition_ZE)==0)\r
+    return context;\r
+  return NULL;  // Multiple status, or unknown\r
+  } // decContextSetStatusFromStringQuiet\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextSetStatusQuiet -- set status without trap                */\r
+/*                                                                    */\r
+/*  context is the context structure to be updated                    */\r
+/*  status  is the DEC_ exception code                                */\r
+/*  returns the context structure                                     */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decContext * decContextSetStatusQuiet(decContext *context, uInt status) {\r
+  context->status|=status;\r
+  return context;} // decContextSetStatusQuiet\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextStatusToString -- convert status flags to a string       */\r
+/*                                                                    */\r
+/*  context is a context with valid status field                      */\r
+/*                                                                    */\r
+/*  returns a constant string describing the condition.  If multiple  */\r
+/*    (or no) flags are set, a generic constant message is returned.  */\r
+/* ------------------------------------------------------------------ */\r
+const char *decContextStatusToString(const decContext *context) {\r
+  Int status=context->status;\r
+\r
+  // test the five IEEE first, as some of the others are ambiguous when\r
+  // DECEXTFLAG=0\r
+  if (status==DEC_Invalid_operation    ) return DEC_Condition_IO;\r
+  if (status==DEC_Division_by_zero     ) return DEC_Condition_DZ;\r
+  if (status==DEC_Overflow             ) return DEC_Condition_OV;\r
+  if (status==DEC_Underflow            ) return DEC_Condition_UN;\r
+  if (status==DEC_Inexact              ) return DEC_Condition_IE;\r
+\r
+  if (status==DEC_Division_impossible  ) return DEC_Condition_DI;\r
+  if (status==DEC_Division_undefined   ) return DEC_Condition_DU;\r
+  if (status==DEC_Rounded              ) return DEC_Condition_RO;\r
+  if (status==DEC_Clamped              ) return DEC_Condition_PA;\r
+  if (status==DEC_Subnormal            ) return DEC_Condition_SU;\r
+  if (status==DEC_Conversion_syntax    ) return DEC_Condition_CS;\r
+  if (status==DEC_Insufficient_storage ) return DEC_Condition_IS;\r
+  if (status==DEC_Invalid_context      ) return DEC_Condition_IC;\r
+  #if DECSUBSET\r
+  if (status==DEC_Lost_digits          ) return DEC_Condition_LD;\r
+  #endif\r
+  if (status==0                        ) return DEC_Condition_ZE;\r
+  return DEC_Condition_MU;  // Multiple errors\r
+  } // decContextStatusToString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextTestEndian -- test whether DECLITEND is set correctly    */\r
+/*                                                                    */\r
+/*  quiet is 1 to suppress message; 0 otherwise                       */\r
+/*  returns 0 if DECLITEND is correct                                 */\r
+/*          1 if DECLITEND is incorrect and should be 1               */\r
+/*         -1 if DECLITEND is incorrect and should be 0               */\r
+/*                                                                    */\r
+/* A message is displayed if the return value is not 0 and quiet==0.  */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+Int decContextTestEndian(Flag quiet) {\r
+  Int res=0;                  // optimist\r
+  uInt dle=(uInt)DECLITEND;   // unsign\r
+  if (dle>1) dle=1;           // ensure 0 or 1\r
+\r
+  if (LITEND!=DECLITEND) {\r
+    if (!quiet) {             // always refer to this\r
+      #if DECPRINT\r
+      const char *adj;\r
+      if (LITEND) adj="little";\r
+             else adj="big";\r
+      printf("Warning: DECLITEND is set to %d, but this computer appears to be %s-endian\n",\r
+             DECLITEND, adj);\r
+      #endif\r
+      }\r
+    res=(Int)LITEND-dle;\r
+    }\r
+  return res;\r
+  } // decContextTestEndian\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextTestSavedStatus -- test bits in saved status             */\r
+/*                                                                    */\r
+/*  oldstatus is the status word to be tested                         */\r
+/*  mask indicates the bits to be tested (the oldstatus bits that     */\r
+/*    correspond to each 1 bit in the mask are tested)                */\r
+/*  returns 1 if any of the tested bits are 1, or 0 otherwise         */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+uInt decContextTestSavedStatus(uInt oldstatus, uInt mask) {\r
+  return (oldstatus&mask)!=0;\r
+  } // decContextTestSavedStatus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextTestStatus -- test bits in current status                */\r
+/*                                                                    */\r
+/*  context is the context structure to be updated                    */\r
+/*  mask indicates the bits to be tested (the status bits that        */\r
+/*    correspond to each 1 bit in the mask are tested)                */\r
+/*  returns 1 if any of the tested bits are 1, or 0 otherwise         */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+uInt decContextTestStatus(decContext *context, uInt mask) {\r
+  return (context->status&mask)!=0;\r
+  } // decContextTestStatus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decContextZeroStatus -- clear all status bits                      */\r
+/*                                                                    */\r
+/*  context is the context structure to be updated                    */\r
+/*  returns context                                                   */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decContext *decContextZeroStatus(decContext *context) {\r
+  context->status=0;\r
+  return context;\r
+  } // decContextZeroStatus\r
+\r
diff --git a/src/decNumber/decContext.h b/src/decNumber/decContext.h
new file mode 100644 (file)
index 0000000..82e4fcf
--- /dev/null
@@ -0,0 +1,254 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Context module header                                      */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2010.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/*                                                                    */\r
+/* Context variables must always have valid values:                   */\r
+/*                                                                    */\r
+/*  status   -- [any bits may be cleared, but not set, by user]       */\r
+/*  round    -- must be one of the enumerated rounding modes          */\r
+/*                                                                    */\r
+/* The following variables are implied for fixed size formats (i.e.,  */\r
+/* they are ignored) but should still be set correctly in case used   */\r
+/* with decNumber functions:                                          */\r
+/*                                                                    */\r
+/*  clamp    -- must be either 0 or 1                                 */\r
+/*  digits   -- must be in the range 1 through 999999999              */\r
+/*  emax     -- must be in the range 0 through 999999999              */\r
+/*  emin     -- must be in the range 0 through -999999999             */\r
+/*  extended -- must be either 0 or 1 [present only if DECSUBSET]     */\r
+/*  traps    -- only defined bits may be set                          */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#if !defined(DECCONTEXT)\r
+  #define DECCONTEXT\r
+  #define DECCNAME     "decContext"                     /* Short name */\r
+  #define DECCFULLNAME "Decimal Context Descriptor"   /* Verbose name */\r
+  #define DECCAUTHOR   "Mike Cowlishaw"               /* Who to blame */\r
+\r
+  #if !defined(int32_t)\r
+    #include <stdint.h>            /* C99 standard integers           */\r
+  #endif\r
+  #include <stdio.h>               /* for printf, etc.                */\r
+  #include <signal.h>              /* for traps                       */\r
+\r
+  /* Extended flags setting -- set this to 0 to use only IEEE flags   */\r
+  #if !defined(DECEXTFLAG)\r
+  #define DECEXTFLAG 1             /* 1=enable extended flags         */\r
+  #endif\r
+\r
+  /* Conditional code flag -- set this to 0 for best performance      */\r
+  #if !defined(DECSUBSET)\r
+  #define DECSUBSET  0             /* 1=enable subset arithmetic      */\r
+  #endif\r
+\r
+  /* Context for operations, with associated constants                */\r
+  enum rounding {\r
+    DEC_ROUND_CEILING,             /* round towards +infinity         */\r
+    DEC_ROUND_UP,                  /* round away from 0               */\r
+    DEC_ROUND_HALF_UP,             /* 0.5 rounds up                   */\r
+    DEC_ROUND_HALF_EVEN,           /* 0.5 rounds to nearest even      */\r
+    DEC_ROUND_HALF_DOWN,           /* 0.5 rounds down                 */\r
+    DEC_ROUND_DOWN,                /* round towards 0 (truncate)      */\r
+    DEC_ROUND_FLOOR,               /* round towards -infinity         */\r
+    DEC_ROUND_05UP,                /* round for reround               */\r
+    DEC_ROUND_MAX                  /* enum must be less than this     */\r
+    };\r
+  #define DEC_ROUND_DEFAULT DEC_ROUND_HALF_EVEN;\r
+\r
+  typedef struct {\r
+    int32_t  digits;               /* working precision               */\r
+    int32_t  emax;                 /* maximum positive exponent       */\r
+    int32_t  emin;                 /* minimum negative exponent       */\r
+    enum     rounding round;       /* rounding mode                   */\r
+    uint32_t traps;                /* trap-enabler flags              */\r
+    uint32_t status;               /* status flags                    */\r
+    uint8_t  clamp;                /* flag: apply IEEE exponent clamp */\r
+    #if DECSUBSET\r
+    uint8_t  extended;             /* flag: special-values allowed    */\r
+    #endif\r
+    } decContext;\r
+\r
+  /* Maxima and Minima for context settings                           */\r
+  #define DEC_MAX_DIGITS 999999999\r
+  #define DEC_MIN_DIGITS         1\r
+  #define DEC_MAX_EMAX   999999999\r
+  #define DEC_MIN_EMAX           0\r
+  #define DEC_MAX_EMIN           0\r
+  #define DEC_MIN_EMIN  -999999999\r
+  #define DEC_MAX_MATH      999999 /* max emax, etc., for math funcs. */\r
+\r
+  /* Classifications for decimal numbers, aligned with 754 (note that */\r
+  /* 'normal' and 'subnormal' are meaningful only with a decContext   */\r
+  /* or a fixed size format).                                         */\r
+  enum decClass {\r
+    DEC_CLASS_SNAN,\r
+    DEC_CLASS_QNAN,\r
+    DEC_CLASS_NEG_INF,\r
+    DEC_CLASS_NEG_NORMAL,\r
+    DEC_CLASS_NEG_SUBNORMAL,\r
+    DEC_CLASS_NEG_ZERO,\r
+    DEC_CLASS_POS_ZERO,\r
+    DEC_CLASS_POS_SUBNORMAL,\r
+    DEC_CLASS_POS_NORMAL,\r
+    DEC_CLASS_POS_INF\r
+    };\r
+  /* Strings for the decClasses */\r
+  #define DEC_ClassString_SN  "sNaN"\r
+  #define DEC_ClassString_QN  "NaN"\r
+  #define DEC_ClassString_NI  "-Infinity"\r
+  #define DEC_ClassString_NN  "-Normal"\r
+  #define DEC_ClassString_NS  "-Subnormal"\r
+  #define DEC_ClassString_NZ  "-Zero"\r
+  #define DEC_ClassString_PZ  "+Zero"\r
+  #define DEC_ClassString_PS  "+Subnormal"\r
+  #define DEC_ClassString_PN  "+Normal"\r
+  #define DEC_ClassString_PI  "+Infinity"\r
+  #define DEC_ClassString_UN  "Invalid"\r
+\r
+  /* Trap-enabler and Status flags (exceptional conditions), and      */\r
+  /* their names.  The top byte is reserved for internal use          */\r
+  #if DECEXTFLAG\r
+    /* Extended flags */\r
+    #define DEC_Conversion_syntax    0x00000001\r
+    #define DEC_Division_by_zero     0x00000002\r
+    #define DEC_Division_impossible  0x00000004\r
+    #define DEC_Division_undefined   0x00000008\r
+    #define DEC_Insufficient_storage 0x00000010 /* [when malloc fails]  */\r
+    #define DEC_Inexact              0x00000020\r
+    #define DEC_Invalid_context      0x00000040\r
+    #define DEC_Invalid_operation    0x00000080\r
+    #if DECSUBSET\r
+    #define DEC_Lost_digits          0x00000100\r
+    #endif\r
+    #define DEC_Overflow             0x00000200\r
+    #define DEC_Clamped              0x00000400\r
+    #define DEC_Rounded              0x00000800\r
+    #define DEC_Subnormal            0x00001000\r
+    #define DEC_Underflow            0x00002000\r
+  #else\r
+    /* IEEE flags only */\r
+    #define DEC_Conversion_syntax    0x00000010\r
+    #define DEC_Division_by_zero     0x00000002\r
+    #define DEC_Division_impossible  0x00000010\r
+    #define DEC_Division_undefined   0x00000010\r
+    #define DEC_Insufficient_storage 0x00000010 /* [when malloc fails]  */\r
+    #define DEC_Inexact              0x00000001\r
+    #define DEC_Invalid_context      0x00000010\r
+    #define DEC_Invalid_operation    0x00000010\r
+    #if DECSUBSET\r
+    #define DEC_Lost_digits          0x00000000\r
+    #endif\r
+    #define DEC_Overflow             0x00000008\r
+    #define DEC_Clamped              0x00000000\r
+    #define DEC_Rounded              0x00000000\r
+    #define DEC_Subnormal            0x00000000\r
+    #define DEC_Underflow            0x00000004\r
+  #endif\r
+\r
+  /* IEEE 754 groupings for the flags                                 */\r
+  /* [DEC_Clamped, DEC_Lost_digits, DEC_Rounded, and DEC_Subnormal    */\r
+  /* are not in IEEE 754]                                             */\r
+  #define DEC_IEEE_754_Division_by_zero  (DEC_Division_by_zero)\r
+  #if DECSUBSET\r
+  #define DEC_IEEE_754_Inexact           (DEC_Inexact | DEC_Lost_digits)\r
+  #else\r
+  #define DEC_IEEE_754_Inexact           (DEC_Inexact)\r
+  #endif\r
+  #define DEC_IEEE_754_Invalid_operation (DEC_Conversion_syntax |     \\r
+                                          DEC_Division_impossible |   \\r
+                                          DEC_Division_undefined |    \\r
+                                          DEC_Insufficient_storage |  \\r
+                                          DEC_Invalid_context |       \\r
+                                          DEC_Invalid_operation)\r
+  #define DEC_IEEE_754_Overflow          (DEC_Overflow)\r
+  #define DEC_IEEE_754_Underflow         (DEC_Underflow)\r
+\r
+  /* flags which are normally errors (result is qNaN, infinite, or 0) */\r
+  #define DEC_Errors (DEC_IEEE_754_Division_by_zero |                 \\r
+                      DEC_IEEE_754_Invalid_operation |                \\r
+                      DEC_IEEE_754_Overflow | DEC_IEEE_754_Underflow)\r
+  /* flags which cause a result to become qNaN                        */\r
+  #define DEC_NaNs    DEC_IEEE_754_Invalid_operation\r
+\r
+  /* flags which are normally for information only (finite results)   */\r
+  #if DECSUBSET\r
+  #define DEC_Information (DEC_Clamped | DEC_Rounded | DEC_Inexact    \\r
+                          | DEC_Lost_digits)\r
+  #else\r
+  #define DEC_Information (DEC_Clamped | DEC_Rounded | DEC_Inexact)\r
+  #endif\r
+\r
+  /* IEEE 854 names (for compatibility with older decNumber versions) */\r
+  #define DEC_IEEE_854_Division_by_zero  DEC_IEEE_754_Division_by_zero\r
+  #define DEC_IEEE_854_Inexact           DEC_IEEE_754_Inexact\r
+  #define DEC_IEEE_854_Invalid_operation DEC_IEEE_754_Invalid_operation\r
+  #define DEC_IEEE_854_Overflow          DEC_IEEE_754_Overflow\r
+  #define DEC_IEEE_854_Underflow         DEC_IEEE_754_Underflow\r
+\r
+  /* Name strings for the exceptional conditions                      */\r
+  #define DEC_Condition_CS "Conversion syntax"\r
+  #define DEC_Condition_DZ "Division by zero"\r
+  #define DEC_Condition_DI "Division impossible"\r
+  #define DEC_Condition_DU "Division undefined"\r
+  #define DEC_Condition_IE "Inexact"\r
+  #define DEC_Condition_IS "Insufficient storage"\r
+  #define DEC_Condition_IC "Invalid context"\r
+  #define DEC_Condition_IO "Invalid operation"\r
+  #if DECSUBSET\r
+  #define DEC_Condition_LD "Lost digits"\r
+  #endif\r
+  #define DEC_Condition_OV "Overflow"\r
+  #define DEC_Condition_PA "Clamped"\r
+  #define DEC_Condition_RO "Rounded"\r
+  #define DEC_Condition_SU "Subnormal"\r
+  #define DEC_Condition_UN "Underflow"\r
+  #define DEC_Condition_ZE "No status"\r
+  #define DEC_Condition_MU "Multiple status"\r
+  #define DEC_Condition_Length 21  /* length of the longest string,   */\r
+                                   /* including terminator            */\r
+\r
+  /* Initialization descriptors, used by decContextDefault            */\r
+  #define DEC_INIT_BASE         0\r
+  #define DEC_INIT_DECIMAL32   32\r
+  #define DEC_INIT_DECIMAL64   64\r
+  #define DEC_INIT_DECIMAL128 128\r
+  /* Synonyms */\r
+  #define DEC_INIT_DECSINGLE  DEC_INIT_DECIMAL32\r
+  #define DEC_INIT_DECDOUBLE  DEC_INIT_DECIMAL64\r
+  #define DEC_INIT_DECQUAD    DEC_INIT_DECIMAL128\r
+\r
+  /* decContext routines                                              */\r
+  extern decContext  * decContextClearStatus(decContext *, uint32_t);\r
+  extern decContext  * decContextDefault(decContext *, int32_t);\r
+  extern enum rounding decContextGetRounding(decContext *);\r
+  extern uint32_t      decContextGetStatus(decContext *);\r
+  extern decContext  * decContextRestoreStatus(decContext *, uint32_t, uint32_t);\r
+  extern uint32_t      decContextSaveStatus(decContext *, uint32_t);\r
+  extern decContext  * decContextSetRounding(decContext *, enum rounding);\r
+  extern decContext  * decContextSetStatus(decContext *, uint32_t);\r
+  extern decContext  * decContextSetStatusFromString(decContext *, const char *);\r
+  extern decContext  * decContextSetStatusFromStringQuiet(decContext *, const char *);\r
+  extern decContext  * decContextSetStatusQuiet(decContext *, uint32_t);\r
+  extern const char  * decContextStatusToString(const decContext *);\r
+  extern int32_t       decContextTestEndian(uint8_t);\r
+  extern uint32_t      decContextTestSavedStatus(uint32_t, uint32_t);\r
+  extern uint32_t      decContextTestStatus(decContext *, uint32_t);\r
+  extern decContext  * decContextZeroStatus(decContext *);\r
+\r
+#endif\r
diff --git a/src/decNumber/decDPD.h b/src/decNumber/decDPD.h
new file mode 100644 (file)
index 0000000..e6a80c0
--- /dev/null
@@ -0,0 +1,1185 @@
+/* ------------------------------------------------------------------------ */\r
+/* Binary Coded Decimal and Densely Packed Decimal conversion lookup tables */\r
+/* [Automatically generated -- do not edit.  2008.06.21]                    */\r
+/* ------------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2008. All rights reserved.          */\r
+/* ------------------------------------------------------------------------ */\r
+/* For details, see DPDecimal.html on the General Decimal Arithmetic page.  */\r
+/*                                                                          */\r
+/* This include file defines several DPD and BCD conversion tables:         */\r
+/*                                                                          */\r
+/*   uint16_t BCD2DPD[2458];     -- BCD -> DPD (0x999 => 2457)              */\r
+/*   uint16_t BIN2DPD[1000];     -- Bin -> DPD (999 => 2457)                */\r
+/*   uint8_t  BIN2CHAR[4001];    -- Bin -> CHAR (999 => '\3' '9' '9' '9')   */\r
+/*   uint8_t  BIN2BCD8[4000];    -- Bin -> bytes (999 => 9 9 9 3)           */\r
+/*   uint16_t DPD2BCD[1024];     -- DPD -> BCD (0x3FF => 0x999)             */\r
+/*   uint16_t DPD2BIN[1024];     -- DPD -> BIN (0x3FF => 999)               */\r
+/*   uint32_t DPD2BINK[1024];    -- DPD -> BIN * 1000 (0x3FF => 999000)     */\r
+/*   uint32_t DPD2BINM[1024];    -- DPD -> BIN * 1E+6 (0x3FF => 999000000)  */\r
+/*   uint8_t  DPD2BCD8[4096];    -- DPD -> bytes (x3FF => 9 9 9 3)          */\r
+/*                                                                          */\r
+/* In all cases the result (10 bits or 12 bits, or binary) is right-aligned */\r
+/* in the table entry.  BIN2CHAR entries are a single byte length (0 for    */\r
+/* value 0) followed by three digit characters; a trailing terminator is    */\r
+/* included to allow 4-char moves always.  BIN2BCD8 and DPD2BCD8 entries    */\r
+/* are similar with the three BCD8 digits followed by a one-byte length     */\r
+/* (again, length=0 for value 0).                                           */\r
+/*                                                                          */\r
+/* To use a table, its name, prefixed with DEC_, must be defined with a     */\r
+/* value of 1 before this header file is included.  For example:            */\r
+/*    #define DEC_BCD2DPD 1                                                 */\r
+/* This mechanism allows software to only include tables that are needed.   */\r
+/* ------------------------------------------------------------------------ */\r
\r
+#if defined(DEC_BCD2DPD) && DEC_BCD2DPD==1 && !defined(DECBCD2DPD)\r
+#define DECBCD2DPD\r
\r
+const uint16_t BCD2DPD[2458]={    0,    1,    2,    3,    4,    5,    6,    7, \r
+    8,    9,    0,    0,    0,    0,    0,    0,   16,   17,   18,   19,   20, \r
+   21,   22,   23,   24,   25,    0,    0,    0,    0,    0,    0,   32,   33, \r
+   34,   35,   36,   37,   38,   39,   40,   41,    0,    0,    0,    0,    0, \r
+    0,   48,   49,   50,   51,   52,   53,   54,   55,   56,   57,    0,    0, \r
+    0,    0,    0,    0,   64,   65,   66,   67,   68,   69,   70,   71,   72, \r
+   73,    0,    0,    0,    0,    0,    0,   80,   81,   82,   83,   84,   85, \r
+   86,   87,   88,   89,    0,    0,    0,    0,    0,    0,   96,   97,   98, \r
+   99,  100,  101,  102,  103,  104,  105,    0,    0,    0,    0,    0,    0, \r
+  112,  113,  114,  115,  116,  117,  118,  119,  120,  121,    0,    0,    0, \r
+    0,    0,    0,   10,   11,   42,   43,   74,   75,  106,  107,   78,   79, \r
+    0,    0,    0,    0,    0,    0,   26,   27,   58,   59,   90,   91,  122, \r
+  123,   94,   95,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,  128,  129,  130,  131,  132,  133,  134,  135,  136,  137,    0,    0, \r
+    0,    0,    0,    0,  144,  145,  146,  147,  148,  149,  150,  151,  152, \r
+  153,    0,    0,    0,    0,    0,    0,  160,  161,  162,  163,  164,  165, \r
+  166,  167,  168,  169,    0,    0,    0,    0,    0,    0,  176,  177,  178, \r
+  179,  180,  181,  182,  183,  184,  185,    0,    0,    0,    0,    0,    0, \r
+  192,  193,  194,  195,  196,  197,  198,  199,  200,  201,    0,    0,    0, \r
+    0,    0,    0,  208,  209,  210,  211,  212,  213,  214,  215,  216,  217, \r
+    0,    0,    0,    0,    0,    0,  224,  225,  226,  227,  228,  229,  230, \r
+  231,  232,  233,    0,    0,    0,    0,    0,    0,  240,  241,  242,  243, \r
+  244,  245,  246,  247,  248,  249,    0,    0,    0,    0,    0,    0,  138, \r
+  139,  170,  171,  202,  203,  234,  235,  206,  207,    0,    0,    0,    0, \r
+    0,    0,  154,  155,  186,  187,  218,  219,  250,  251,  222,  223,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,  256,  257,  258, \r
+  259,  260,  261,  262,  263,  264,  265,    0,    0,    0,    0,    0,    0, \r
+  272,  273,  274,  275,  276,  277,  278,  279,  280,  281,    0,    0,    0, \r
+    0,    0,    0,  288,  289,  290,  291,  292,  293,  294,  295,  296,  297, \r
+    0,    0,    0,    0,    0,    0,  304,  305,  306,  307,  308,  309,  310, \r
+  311,  312,  313,    0,    0,    0,    0,    0,    0,  320,  321,  322,  323, \r
+  324,  325,  326,  327,  328,  329,    0,    0,    0,    0,    0,    0,  336, \r
+  337,  338,  339,  340,  341,  342,  343,  344,  345,    0,    0,    0,    0, \r
+    0,    0,  352,  353,  354,  355,  356,  357,  358,  359,  360,  361,    0, \r
+    0,    0,    0,    0,    0,  368,  369,  370,  371,  372,  373,  374,  375, \r
+  376,  377,    0,    0,    0,    0,    0,    0,  266,  267,  298,  299,  330, \r
+  331,  362,  363,  334,  335,    0,    0,    0,    0,    0,    0,  282,  283, \r
+  314,  315,  346,  347,  378,  379,  350,  351,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,  384,  385,  386,  387,  388,  389,  390, \r
+  391,  392,  393,    0,    0,    0,    0,    0,    0,  400,  401,  402,  403, \r
+  404,  405,  406,  407,  408,  409,    0,    0,    0,    0,    0,    0,  416, \r
+  417,  418,  419,  420,  421,  422,  423,  424,  425,    0,    0,    0,    0, \r
+    0,    0,  432,  433,  434,  435,  436,  437,  438,  439,  440,  441,    0, \r
+    0,    0,    0,    0,    0,  448,  449,  450,  451,  452,  453,  454,  455, \r
+  456,  457,    0,    0,    0,    0,    0,    0,  464,  465,  466,  467,  468, \r
+  469,  470,  471,  472,  473,    0,    0,    0,    0,    0,    0,  480,  481, \r
+  482,  483,  484,  485,  486,  487,  488,  489,    0,    0,    0,    0,    0, \r
+    0,  496,  497,  498,  499,  500,  501,  502,  503,  504,  505,    0,    0, \r
+    0,    0,    0,    0,  394,  395,  426,  427,  458,  459,  490,  491,  462, \r
+  463,    0,    0,    0,    0,    0,    0,  410,  411,  442,  443,  474,  475, \r
+  506,  507,  478,  479,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,  512,  513,  514,  515,  516,  517,  518,  519,  520,  521,    0, \r
+    0,    0,    0,    0,    0,  528,  529,  530,  531,  532,  533,  534,  535, \r
+  536,  537,    0,    0,    0,    0,    0,    0,  544,  545,  546,  547,  548, \r
+  549,  550,  551,  552,  553,    0,    0,    0,    0,    0,    0,  560,  561, \r
+  562,  563,  564,  565,  566,  567,  568,  569,    0,    0,    0,    0,    0, \r
+    0,  576,  577,  578,  579,  580,  581,  582,  583,  584,  585,    0,    0, \r
+    0,    0,    0,    0,  592,  593,  594,  595,  596,  597,  598,  599,  600, \r
+  601,    0,    0,    0,    0,    0,    0,  608,  609,  610,  611,  612,  613, \r
+  614,  615,  616,  617,    0,    0,    0,    0,    0,    0,  624,  625,  626, \r
+  627,  628,  629,  630,  631,  632,  633,    0,    0,    0,    0,    0,    0, \r
+  522,  523,  554,  555,  586,  587,  618,  619,  590,  591,    0,    0,    0, \r
+    0,    0,    0,  538,  539,  570,  571,  602,  603,  634,  635,  606,  607, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,  640,  641, \r
+  642,  643,  644,  645,  646,  647,  648,  649,    0,    0,    0,    0,    0, \r
+    0,  656,  657,  658,  659,  660,  661,  662,  663,  664,  665,    0,    0, \r
+    0,    0,    0,    0,  672,  673,  674,  675,  676,  677,  678,  679,  680, \r
+  681,    0,    0,    0,    0,    0,    0,  688,  689,  690,  691,  692,  693, \r
+  694,  695,  696,  697,    0,    0,    0,    0,    0,    0,  704,  705,  706, \r
+  707,  708,  709,  710,  711,  712,  713,    0,    0,    0,    0,    0,    0, \r
+  720,  721,  722,  723,  724,  725,  726,  727,  728,  729,    0,    0,    0, \r
+    0,    0,    0,  736,  737,  738,  739,  740,  741,  742,  743,  744,  745, \r
+    0,    0,    0,    0,    0,    0,  752,  753,  754,  755,  756,  757,  758, \r
+  759,  760,  761,    0,    0,    0,    0,    0,    0,  650,  651,  682,  683, \r
+  714,  715,  746,  747,  718,  719,    0,    0,    0,    0,    0,    0,  666, \r
+  667,  698,  699,  730,  731,  762,  763,  734,  735,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,  768,  769,  770,  771,  772,  773, \r
+  774,  775,  776,  777,    0,    0,    0,    0,    0,    0,  784,  785,  786, \r
+  787,  788,  789,  790,  791,  792,  793,    0,    0,    0,    0,    0,    0, \r
+  800,  801,  802,  803,  804,  805,  806,  807,  808,  809,    0,    0,    0, \r
+    0,    0,    0,  816,  817,  818,  819,  820,  821,  822,  823,  824,  825, \r
+    0,    0,    0,    0,    0,    0,  832,  833,  834,  835,  836,  837,  838, \r
+  839,  840,  841,    0,    0,    0,    0,    0,    0,  848,  849,  850,  851, \r
+  852,  853,  854,  855,  856,  857,    0,    0,    0,    0,    0,    0,  864, \r
+  865,  866,  867,  868,  869,  870,  871,  872,  873,    0,    0,    0,    0, \r
+    0,    0,  880,  881,  882,  883,  884,  885,  886,  887,  888,  889,    0, \r
+    0,    0,    0,    0,    0,  778,  779,  810,  811,  842,  843,  874,  875, \r
+  846,  847,    0,    0,    0,    0,    0,    0,  794,  795,  826,  827,  858, \r
+  859,  890,  891,  862,  863,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,  896,  897,  898,  899,  900,  901,  902,  903,  904,  905, \r
+    0,    0,    0,    0,    0,    0,  912,  913,  914,  915,  916,  917,  918, \r
+  919,  920,  921,    0,    0,    0,    0,    0,    0,  928,  929,  930,  931, \r
+  932,  933,  934,  935,  936,  937,    0,    0,    0,    0,    0,    0,  944, \r
+  945,  946,  947,  948,  949,  950,  951,  952,  953,    0,    0,    0,    0, \r
+    0,    0,  960,  961,  962,  963,  964,  965,  966,  967,  968,  969,    0, \r
+    0,    0,    0,    0,    0,  976,  977,  978,  979,  980,  981,  982,  983, \r
+  984,  985,    0,    0,    0,    0,    0,    0,  992,  993,  994,  995,  996, \r
+  997,  998,  999, 1000, 1001,    0,    0,    0,    0,    0,    0, 1008, 1009, \r
+ 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017,    0,    0,    0,    0,    0, \r
+    0,  906,  907,  938,  939,  970,  971, 1002, 1003,  974,  975,    0,    0, \r
+    0,    0,    0,    0,  922,  923,  954,  955,  986,  987, 1018, 1019,  990, \r
+  991,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,   12, \r
+   13,  268,  269,  524,  525,  780,  781,   46,   47,    0,    0,    0,    0, \r
+    0,    0,   28,   29,  284,  285,  540,  541,  796,  797,   62,   63,    0, \r
+    0,    0,    0,    0,    0,   44,   45,  300,  301,  556,  557,  812,  813, \r
+  302,  303,    0,    0,    0,    0,    0,    0,   60,   61,  316,  317,  572, \r
+  573,  828,  829,  318,  319,    0,    0,    0,    0,    0,    0,   76,   77, \r
+  332,  333,  588,  589,  844,  845,  558,  559,    0,    0,    0,    0,    0, \r
+    0,   92,   93,  348,  349,  604,  605,  860,  861,  574,  575,    0,    0, \r
+    0,    0,    0,    0,  108,  109,  364,  365,  620,  621,  876,  877,  814, \r
+  815,    0,    0,    0,    0,    0,    0,  124,  125,  380,  381,  636,  637, \r
+  892,  893,  830,  831,    0,    0,    0,    0,    0,    0,   14,   15,  270, \r
+  271,  526,  527,  782,  783,  110,  111,    0,    0,    0,    0,    0,    0, \r
+   30,   31,  286,  287,  542,  543,  798,  799,  126,  127,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, \r
+    0,    0,    0,    0,    0,    0,    0,    0,  140,  141,  396,  397,  652, \r
+  653,  908,  909,  174,  175,    0,    0,    0,    0,    0,    0,  156,  157, \r
+  412,  413,  668,  669,  924,  925,  190,  191,    0,    0,    0,    0,    0, \r
+    0,  172,  173,  428,  429,  684,  685,  940,  941,  430,  431,    0,    0, \r
+    0,    0,    0,    0,  188,  189,  444,  445,  700,  701,  956,  957,  446, \r
+  447,    0,    0,    0,    0,    0,    0,  204,  205,  460,  461,  716,  717, \r
+  972,  973,  686,  687,    0,    0,    0,    0,    0,    0,  220,  221,  476, \r
+  477,  732,  733,  988,  989,  702,  703,    0,    0,    0,    0,    0,    0, \r
+  236,  237,  492,  493,  748,  749, 1004, 1005,  942,  943,    0,    0,    0, \r
+    0,    0,    0,  252,  253,  508,  509,  764,  765, 1020, 1021,  958,  959, \r
+    0,    0,    0,    0,    0,    0,  142,  143,  398,  399,  654,  655,  910, \r
+  911,  238,  239,    0,    0,    0,    0,    0,    0,  158,  159,  414,  415, \r
+  670,  671,  926,  927,  254,  255};\r
+#endif\r
\r
+#if defined(DEC_DPD2BCD) && DEC_DPD2BCD==1 && !defined(DECDPD2BCD)\r
+#define DECDPD2BCD\r
\r
+const uint16_t DPD2BCD[1024]={    0,    1,    2,    3,    4,    5,    6,    7, \r
+    8,    9,  128,  129, 2048, 2049, 2176, 2177,   16,   17,   18,   19,   20, \r
+   21,   22,   23,   24,   25,  144,  145, 2064, 2065, 2192, 2193,   32,   33, \r
+   34,   35,   36,   37,   38,   39,   40,   41,  130,  131, 2080, 2081, 2056, \r
+ 2057,   48,   49,   50,   51,   52,   53,   54,   55,   56,   57,  146,  147, \r
+ 2096, 2097, 2072, 2073,   64,   65,   66,   67,   68,   69,   70,   71,   72, \r
+   73,  132,  133, 2112, 2113,  136,  137,   80,   81,   82,   83,   84,   85, \r
+   86,   87,   88,   89,  148,  149, 2128, 2129,  152,  153,   96,   97,   98, \r
+   99,  100,  101,  102,  103,  104,  105,  134,  135, 2144, 2145, 2184, 2185, \r
+  112,  113,  114,  115,  116,  117,  118,  119,  120,  121,  150,  151, 2160, \r
+ 2161, 2200, 2201,  256,  257,  258,  259,  260,  261,  262,  263,  264,  265, \r
+  384,  385, 2304, 2305, 2432, 2433,  272,  273,  274,  275,  276,  277,  278, \r
+  279,  280,  281,  400,  401, 2320, 2321, 2448, 2449,  288,  289,  290,  291, \r
+  292,  293,  294,  295,  296,  297,  386,  387, 2336, 2337, 2312, 2313,  304, \r
+  305,  306,  307,  308,  309,  310,  311,  312,  313,  402,  403, 2352, 2353, \r
+ 2328, 2329,  320,  321,  322,  323,  324,  325,  326,  327,  328,  329,  388, \r
+  389, 2368, 2369,  392,  393,  336,  337,  338,  339,  340,  341,  342,  343, \r
+  344,  345,  404,  405, 2384, 2385,  408,  409,  352,  353,  354,  355,  356, \r
+  357,  358,  359,  360,  361,  390,  391, 2400, 2401, 2440, 2441,  368,  369, \r
+  370,  371,  372,  373,  374,  375,  376,  377,  406,  407, 2416, 2417, 2456, \r
+ 2457,  512,  513,  514,  515,  516,  517,  518,  519,  520,  521,  640,  641, \r
+ 2050, 2051, 2178, 2179,  528,  529,  530,  531,  532,  533,  534,  535,  536, \r
+  537,  656,  657, 2066, 2067, 2194, 2195,  544,  545,  546,  547,  548,  549, \r
+  550,  551,  552,  553,  642,  643, 2082, 2083, 2088, 2089,  560,  561,  562, \r
+  563,  564,  565,  566,  567,  568,  569,  658,  659, 2098, 2099, 2104, 2105, \r
+  576,  577,  578,  579,  580,  581,  582,  583,  584,  585,  644,  645, 2114, \r
+ 2115,  648,  649,  592,  593,  594,  595,  596,  597,  598,  599,  600,  601, \r
+  660,  661, 2130, 2131,  664,  665,  608,  609,  610,  611,  612,  613,  614, \r
+  615,  616,  617,  646,  647, 2146, 2147, 2184, 2185,  624,  625,  626,  627, \r
+  628,  629,  630,  631,  632,  633,  662,  663, 2162, 2163, 2200, 2201,  768, \r
+  769,  770,  771,  772,  773,  774,  775,  776,  777,  896,  897, 2306, 2307, \r
+ 2434, 2435,  784,  785,  786,  787,  788,  789,  790,  791,  792,  793,  912, \r
+  913, 2322, 2323, 2450, 2451,  800,  801,  802,  803,  804,  805,  806,  807, \r
+  808,  809,  898,  899, 2338, 2339, 2344, 2345,  816,  817,  818,  819,  820, \r
+  821,  822,  823,  824,  825,  914,  915, 2354, 2355, 2360, 2361,  832,  833, \r
+  834,  835,  836,  837,  838,  839,  840,  841,  900,  901, 2370, 2371,  904, \r
+  905,  848,  849,  850,  851,  852,  853,  854,  855,  856,  857,  916,  917, \r
+ 2386, 2387,  920,  921,  864,  865,  866,  867,  868,  869,  870,  871,  872, \r
+  873,  902,  903, 2402, 2403, 2440, 2441,  880,  881,  882,  883,  884,  885, \r
+  886,  887,  888,  889,  918,  919, 2418, 2419, 2456, 2457, 1024, 1025, 1026, \r
+ 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1152, 1153, 2052, 2053, 2180, 2181, \r
+ 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1168, 1169, 2068, \r
+ 2069, 2196, 2197, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, \r
+ 1154, 1155, 2084, 2085, 2120, 2121, 1072, 1073, 1074, 1075, 1076, 1077, 1078, \r
+ 1079, 1080, 1081, 1170, 1171, 2100, 2101, 2136, 2137, 1088, 1089, 1090, 1091, \r
+ 1092, 1093, 1094, 1095, 1096, 1097, 1156, 1157, 2116, 2117, 1160, 1161, 1104, \r
+ 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1172, 1173, 2132, 2133, \r
+ 1176, 1177, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1158, \r
+ 1159, 2148, 2149, 2184, 2185, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, \r
+ 1144, 1145, 1174, 1175, 2164, 2165, 2200, 2201, 1280, 1281, 1282, 1283, 1284, \r
+ 1285, 1286, 1287, 1288, 1289, 1408, 1409, 2308, 2309, 2436, 2437, 1296, 1297, \r
+ 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1424, 1425, 2324, 2325, 2452, \r
+ 2453, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1410, 1411, \r
+ 2340, 2341, 2376, 2377, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, \r
+ 1337, 1426, 1427, 2356, 2357, 2392, 2393, 1344, 1345, 1346, 1347, 1348, 1349, \r
+ 1350, 1351, 1352, 1353, 1412, 1413, 2372, 2373, 1416, 1417, 1360, 1361, 1362, \r
+ 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1428, 1429, 2388, 2389, 1432, 1433, \r
+ 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1414, 1415, 2404, \r
+ 2405, 2440, 2441, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, \r
+ 1430, 1431, 2420, 2421, 2456, 2457, 1536, 1537, 1538, 1539, 1540, 1541, 1542, \r
+ 1543, 1544, 1545, 1664, 1665, 2054, 2055, 2182, 2183, 1552, 1553, 1554, 1555, \r
+ 1556, 1557, 1558, 1559, 1560, 1561, 1680, 1681, 2070, 2071, 2198, 2199, 1568, \r
+ 1569, 1570, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1666, 1667, 2086, 2087, \r
+ 2152, 2153, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1592, 1593, 1682, \r
+ 1683, 2102, 2103, 2168, 2169, 1600, 1601, 1602, 1603, 1604, 1605, 1606, 1607, \r
+ 1608, 1609, 1668, 1669, 2118, 2119, 1672, 1673, 1616, 1617, 1618, 1619, 1620, \r
+ 1621, 1622, 1623, 1624, 1625, 1684, 1685, 2134, 2135, 1688, 1689, 1632, 1633, \r
+ 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1670, 1671, 2150, 2151, 2184, \r
+ 2185, 1648, 1649, 1650, 1651, 1652, 1653, 1654, 1655, 1656, 1657, 1686, 1687, \r
+ 2166, 2167, 2200, 2201, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, 1800, \r
+ 1801, 1920, 1921, 2310, 2311, 2438, 2439, 1808, 1809, 1810, 1811, 1812, 1813, \r
+ 1814, 1815, 1816, 1817, 1936, 1937, 2326, 2327, 2454, 2455, 1824, 1825, 1826, \r
+ 1827, 1828, 1829, 1830, 1831, 1832, 1833, 1922, 1923, 2342, 2343, 2408, 2409, \r
+ 1840, 1841, 1842, 1843, 1844, 1845, 1846, 1847, 1848, 1849, 1938, 1939, 2358, \r
+ 2359, 2424, 2425, 1856, 1857, 1858, 1859, 1860, 1861, 1862, 1863, 1864, 1865, \r
+ 1924, 1925, 2374, 2375, 1928, 1929, 1872, 1873, 1874, 1875, 1876, 1877, 1878, \r
+ 1879, 1880, 1881, 1940, 1941, 2390, 2391, 1944, 1945, 1888, 1889, 1890, 1891, \r
+ 1892, 1893, 1894, 1895, 1896, 1897, 1926, 1927, 2406, 2407, 2440, 2441, 1904, \r
+ 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1942, 1943, 2422, 2423, \r
+ 2456, 2457};\r
+#endif\r
\r
+#if defined(DEC_BIN2DPD) && DEC_BIN2DPD==1 && !defined(DECBIN2DPD)\r
+#define DECBIN2DPD\r
\r
+const uint16_t BIN2DPD[1000]={    0,    1,    2,    3,    4,    5,    6,    7, \r
+    8,    9,   16,   17,   18,   19,   20,   21,   22,   23,   24,   25,   32, \r
+   33,   34,   35,   36,   37,   38,   39,   40,   41,   48,   49,   50,   51, \r
+   52,   53,   54,   55,   56,   57,   64,   65,   66,   67,   68,   69,   70, \r
+   71,   72,   73,   80,   81,   82,   83,   84,   85,   86,   87,   88,   89, \r
+   96,   97,   98,   99,  100,  101,  102,  103,  104,  105,  112,  113,  114, \r
+  115,  116,  117,  118,  119,  120,  121,   10,   11,   42,   43,   74,   75, \r
+  106,  107,   78,   79,   26,   27,   58,   59,   90,   91,  122,  123,   94, \r
+   95,  128,  129,  130,  131,  132,  133,  134,  135,  136,  137,  144,  145, \r
+  146,  147,  148,  149,  150,  151,  152,  153,  160,  161,  162,  163,  164, \r
+  165,  166,  167,  168,  169,  176,  177,  178,  179,  180,  181,  182,  183, \r
+  184,  185,  192,  193,  194,  195,  196,  197,  198,  199,  200,  201,  208, \r
+  209,  210,  211,  212,  213,  214,  215,  216,  217,  224,  225,  226,  227, \r
+  228,  229,  230,  231,  232,  233,  240,  241,  242,  243,  244,  245,  246, \r
+  247,  248,  249,  138,  139,  170,  171,  202,  203,  234,  235,  206,  207, \r
+  154,  155,  186,  187,  218,  219,  250,  251,  222,  223,  256,  257,  258, \r
+  259,  260,  261,  262,  263,  264,  265,  272,  273,  274,  275,  276,  277, \r
+  278,  279,  280,  281,  288,  289,  290,  291,  292,  293,  294,  295,  296, \r
+  297,  304,  305,  306,  307,  308,  309,  310,  311,  312,  313,  320,  321, \r
+  322,  323,  324,  325,  326,  327,  328,  329,  336,  337,  338,  339,  340, \r
+  341,  342,  343,  344,  345,  352,  353,  354,  355,  356,  357,  358,  359, \r
+  360,  361,  368,  369,  370,  371,  372,  373,  374,  375,  376,  377,  266, \r
+  267,  298,  299,  330,  331,  362,  363,  334,  335,  282,  283,  314,  315, \r
+  346,  347,  378,  379,  350,  351,  384,  385,  386,  387,  388,  389,  390, \r
+  391,  392,  393,  400,  401,  402,  403,  404,  405,  406,  407,  408,  409, \r
+  416,  417,  418,  419,  420,  421,  422,  423,  424,  425,  432,  433,  434, \r
+  435,  436,  437,  438,  439,  440,  441,  448,  449,  450,  451,  452,  453, \r
+  454,  455,  456,  457,  464,  465,  466,  467,  468,  469,  470,  471,  472, \r
+  473,  480,  481,  482,  483,  484,  485,  486,  487,  488,  489,  496,  497, \r
+  498,  499,  500,  501,  502,  503,  504,  505,  394,  395,  426,  427,  458, \r
+  459,  490,  491,  462,  463,  410,  411,  442,  443,  474,  475,  506,  507, \r
+  478,  479,  512,  513,  514,  515,  516,  517,  518,  519,  520,  521,  528, \r
+  529,  530,  531,  532,  533,  534,  535,  536,  537,  544,  545,  546,  547, \r
+  548,  549,  550,  551,  552,  553,  560,  561,  562,  563,  564,  565,  566, \r
+  567,  568,  569,  576,  577,  578,  579,  580,  581,  582,  583,  584,  585, \r
+  592,  593,  594,  595,  596,  597,  598,  599,  600,  601,  608,  609,  610, \r
+  611,  612,  613,  614,  615,  616,  617,  624,  625,  626,  627,  628,  629, \r
+  630,  631,  632,  633,  522,  523,  554,  555,  586,  587,  618,  619,  590, \r
+  591,  538,  539,  570,  571,  602,  603,  634,  635,  606,  607,  640,  641, \r
+  642,  643,  644,  645,  646,  647,  648,  649,  656,  657,  658,  659,  660, \r
+  661,  662,  663,  664,  665,  672,  673,  674,  675,  676,  677,  678,  679, \r
+  680,  681,  688,  689,  690,  691,  692,  693,  694,  695,  696,  697,  704, \r
+  705,  706,  707,  708,  709,  710,  711,  712,  713,  720,  721,  722,  723, \r
+  724,  725,  726,  727,  728,  729,  736,  737,  738,  739,  740,  741,  742, \r
+  743,  744,  745,  752,  753,  754,  755,  756,  757,  758,  759,  760,  761, \r
+  650,  651,  682,  683,  714,  715,  746,  747,  718,  719,  666,  667,  698, \r
+  699,  730,  731,  762,  763,  734,  735,  768,  769,  770,  771,  772,  773, \r
+  774,  775,  776,  777,  784,  785,  786,  787,  788,  789,  790,  791,  792, \r
+  793,  800,  801,  802,  803,  804,  805,  806,  807,  808,  809,  816,  817, \r
+  818,  819,  820,  821,  822,  823,  824,  825,  832,  833,  834,  835,  836, \r
+  837,  838,  839,  840,  841,  848,  849,  850,  851,  852,  853,  854,  855, \r
+  856,  857,  864,  865,  866,  867,  868,  869,  870,  871,  872,  873,  880, \r
+  881,  882,  883,  884,  885,  886,  887,  888,  889,  778,  779,  810,  811, \r
+  842,  843,  874,  875,  846,  847,  794,  795,  826,  827,  858,  859,  890, \r
+  891,  862,  863,  896,  897,  898,  899,  900,  901,  902,  903,  904,  905, \r
+  912,  913,  914,  915,  916,  917,  918,  919,  920,  921,  928,  929,  930, \r
+  931,  932,  933,  934,  935,  936,  937,  944,  945,  946,  947,  948,  949, \r
+  950,  951,  952,  953,  960,  961,  962,  963,  964,  965,  966,  967,  968, \r
+  969,  976,  977,  978,  979,  980,  981,  982,  983,  984,  985,  992,  993, \r
+  994,  995,  996,  997,  998,  999, 1000, 1001, 1008, 1009, 1010, 1011, 1012, \r
+ 1013, 1014, 1015, 1016, 1017,  906,  907,  938,  939,  970,  971, 1002, 1003, \r
+  974,  975,  922,  923,  954,  955,  986,  987, 1018, 1019,  990,  991,   12, \r
+   13,  268,  269,  524,  525,  780,  781,   46,   47,   28,   29,  284,  285, \r
+  540,  541,  796,  797,   62,   63,   44,   45,  300,  301,  556,  557,  812, \r
+  813,  302,  303,   60,   61,  316,  317,  572,  573,  828,  829,  318,  319, \r
+   76,   77,  332,  333,  588,  589,  844,  845,  558,  559,   92,   93,  348, \r
+  349,  604,  605,  860,  861,  574,  575,  108,  109,  364,  365,  620,  621, \r
+  876,  877,  814,  815,  124,  125,  380,  381,  636,  637,  892,  893,  830, \r
+  831,   14,   15,  270,  271,  526,  527,  782,  783,  110,  111,   30,   31, \r
+  286,  287,  542,  543,  798,  799,  126,  127,  140,  141,  396,  397,  652, \r
+  653,  908,  909,  174,  175,  156,  157,  412,  413,  668,  669,  924,  925, \r
+  190,  191,  172,  173,  428,  429,  684,  685,  940,  941,  430,  431,  188, \r
+  189,  444,  445,  700,  701,  956,  957,  446,  447,  204,  205,  460,  461, \r
+  716,  717,  972,  973,  686,  687,  220,  221,  476,  477,  732,  733,  988, \r
+  989,  702,  703,  236,  237,  492,  493,  748,  749, 1004, 1005,  942,  943, \r
+  252,  253,  508,  509,  764,  765, 1020, 1021,  958,  959,  142,  143,  398, \r
+  399,  654,  655,  910,  911,  238,  239,  158,  159,  414,  415,  670,  671, \r
+  926,  927,  254,  255};\r
+#endif \r
\r
+#if defined(DEC_DPD2BIN) && DEC_DPD2BIN==1 && !defined(DECDPD2BIN)\r
+#define DECDPD2BIN\r
\r
+const uint16_t DPD2BIN[1024]={    0,    1,    2,    3,    4,    5,    6,    7, \r
+    8,    9,   80,   81,  800,  801,  880,  881,   10,   11,   12,   13,   14, \r
+   15,   16,   17,   18,   19,   90,   91,  810,  811,  890,  891,   20,   21, \r
+   22,   23,   24,   25,   26,   27,   28,   29,   82,   83,  820,  821,  808, \r
+  809,   30,   31,   32,   33,   34,   35,   36,   37,   38,   39,   92,   93, \r
+  830,  831,  818,  819,   40,   41,   42,   43,   44,   45,   46,   47,   48, \r
+   49,   84,   85,  840,  841,   88,   89,   50,   51,   52,   53,   54,   55, \r
+   56,   57,   58,   59,   94,   95,  850,  851,   98,   99,   60,   61,   62, \r
+   63,   64,   65,   66,   67,   68,   69,   86,   87,  860,  861,  888,  889, \r
+   70,   71,   72,   73,   74,   75,   76,   77,   78,   79,   96,   97,  870, \r
+  871,  898,  899,  100,  101,  102,  103,  104,  105,  106,  107,  108,  109, \r
+  180,  181,  900,  901,  980,  981,  110,  111,  112,  113,  114,  115,  116, \r
+  117,  118,  119,  190,  191,  910,  911,  990,  991,  120,  121,  122,  123, \r
+  124,  125,  126,  127,  128,  129,  182,  183,  920,  921,  908,  909,  130, \r
+  131,  132,  133,  134,  135,  136,  137,  138,  139,  192,  193,  930,  931, \r
+  918,  919,  140,  141,  142,  143,  144,  145,  146,  147,  148,  149,  184, \r
+  185,  940,  941,  188,  189,  150,  151,  152,  153,  154,  155,  156,  157, \r
+  158,  159,  194,  195,  950,  951,  198,  199,  160,  161,  162,  163,  164, \r
+  165,  166,  167,  168,  169,  186,  187,  960,  961,  988,  989,  170,  171, \r
+  172,  173,  174,  175,  176,  177,  178,  179,  196,  197,  970,  971,  998, \r
+  999,  200,  201,  202,  203,  204,  205,  206,  207,  208,  209,  280,  281, \r
+  802,  803,  882,  883,  210,  211,  212,  213,  214,  215,  216,  217,  218, \r
+  219,  290,  291,  812,  813,  892,  893,  220,  221,  222,  223,  224,  225, \r
+  226,  227,  228,  229,  282,  283,  822,  823,  828,  829,  230,  231,  232, \r
+  233,  234,  235,  236,  237,  238,  239,  292,  293,  832,  833,  838,  839, \r
+  240,  241,  242,  243,  244,  245,  246,  247,  248,  249,  284,  285,  842, \r
+  843,  288,  289,  250,  251,  252,  253,  254,  255,  256,  257,  258,  259, \r
+  294,  295,  852,  853,  298,  299,  260,  261,  262,  263,  264,  265,  266, \r
+  267,  268,  269,  286,  287,  862,  863,  888,  889,  270,  271,  272,  273, \r
+  274,  275,  276,  277,  278,  279,  296,  297,  872,  873,  898,  899,  300, \r
+  301,  302,  303,  304,  305,  306,  307,  308,  309,  380,  381,  902,  903, \r
+  982,  983,  310,  311,  312,  313,  314,  315,  316,  317,  318,  319,  390, \r
+  391,  912,  913,  992,  993,  320,  321,  322,  323,  324,  325,  326,  327, \r
+  328,  329,  382,  383,  922,  923,  928,  929,  330,  331,  332,  333,  334, \r
+  335,  336,  337,  338,  339,  392,  393,  932,  933,  938,  939,  340,  341, \r
+  342,  343,  344,  345,  346,  347,  348,  349,  384,  385,  942,  943,  388, \r
+  389,  350,  351,  352,  353,  354,  355,  356,  357,  358,  359,  394,  395, \r
+  952,  953,  398,  399,  360,  361,  362,  363,  364,  365,  366,  367,  368, \r
+  369,  386,  387,  962,  963,  988,  989,  370,  371,  372,  373,  374,  375, \r
+  376,  377,  378,  379,  396,  397,  972,  973,  998,  999,  400,  401,  402, \r
+  403,  404,  405,  406,  407,  408,  409,  480,  481,  804,  805,  884,  885, \r
+  410,  411,  412,  413,  414,  415,  416,  417,  418,  419,  490,  491,  814, \r
+  815,  894,  895,  420,  421,  422,  423,  424,  425,  426,  427,  428,  429, \r
+  482,  483,  824,  825,  848,  849,  430,  431,  432,  433,  434,  435,  436, \r
+  437,  438,  439,  492,  493,  834,  835,  858,  859,  440,  441,  442,  443, \r
+  444,  445,  446,  447,  448,  449,  484,  485,  844,  845,  488,  489,  450, \r
+  451,  452,  453,  454,  455,  456,  457,  458,  459,  494,  495,  854,  855, \r
+  498,  499,  460,  461,  462,  463,  464,  465,  466,  467,  468,  469,  486, \r
+  487,  864,  865,  888,  889,  470,  471,  472,  473,  474,  475,  476,  477, \r
+  478,  479,  496,  497,  874,  875,  898,  899,  500,  501,  502,  503,  504, \r
+  505,  506,  507,  508,  509,  580,  581,  904,  905,  984,  985,  510,  511, \r
+  512,  513,  514,  515,  516,  517,  518,  519,  590,  591,  914,  915,  994, \r
+  995,  520,  521,  522,  523,  524,  525,  526,  527,  528,  529,  582,  583, \r
+  924,  925,  948,  949,  530,  531,  532,  533,  534,  535,  536,  537,  538, \r
+  539,  592,  593,  934,  935,  958,  959,  540,  541,  542,  543,  544,  545, \r
+  546,  547,  548,  549,  584,  585,  944,  945,  588,  589,  550,  551,  552, \r
+  553,  554,  555,  556,  557,  558,  559,  594,  595,  954,  955,  598,  599, \r
+  560,  561,  562,  563,  564,  565,  566,  567,  568,  569,  586,  587,  964, \r
+  965,  988,  989,  570,  571,  572,  573,  574,  575,  576,  577,  578,  579, \r
+  596,  597,  974,  975,  998,  999,  600,  601,  602,  603,  604,  605,  606, \r
+  607,  608,  609,  680,  681,  806,  807,  886,  887,  610,  611,  612,  613, \r
+  614,  615,  616,  617,  618,  619,  690,  691,  816,  817,  896,  897,  620, \r
+  621,  622,  623,  624,  625,  626,  627,  628,  629,  682,  683,  826,  827, \r
+  868,  869,  630,  631,  632,  633,  634,  635,  636,  637,  638,  639,  692, \r
+  693,  836,  837,  878,  879,  640,  641,  642,  643,  644,  645,  646,  647, \r
+  648,  649,  684,  685,  846,  847,  688,  689,  650,  651,  652,  653,  654, \r
+  655,  656,  657,  658,  659,  694,  695,  856,  857,  698,  699,  660,  661, \r
+  662,  663,  664,  665,  666,  667,  668,  669,  686,  687,  866,  867,  888, \r
+  889,  670,  671,  672,  673,  674,  675,  676,  677,  678,  679,  696,  697, \r
+  876,  877,  898,  899,  700,  701,  702,  703,  704,  705,  706,  707,  708, \r
+  709,  780,  781,  906,  907,  986,  987,  710,  711,  712,  713,  714,  715, \r
+  716,  717,  718,  719,  790,  791,  916,  917,  996,  997,  720,  721,  722, \r
+  723,  724,  725,  726,  727,  728,  729,  782,  783,  926,  927,  968,  969, \r
+  730,  731,  732,  733,  734,  735,  736,  737,  738,  739,  792,  793,  936, \r
+  937,  978,  979,  740,  741,  742,  743,  744,  745,  746,  747,  748,  749, \r
+  784,  785,  946,  947,  788,  789,  750,  751,  752,  753,  754,  755,  756, \r
+  757,  758,  759,  794,  795,  956,  957,  798,  799,  760,  761,  762,  763, \r
+  764,  765,  766,  767,  768,  769,  786,  787,  966,  967,  988,  989,  770, \r
+  771,  772,  773,  774,  775,  776,  777,  778,  779,  796,  797,  976,  977, \r
+  998,  999};\r
+#endif\r
\r
+#if defined(DEC_DPD2BINK) && DEC_DPD2BINK==1 && !defined(DECDPD2BINK)\r
+#define DECDPD2BINK\r
\r
+const uint32_t DPD2BINK[1024]={       0,   1000,   2000,   3000,   4000,   5000, \r
+   6000,   7000,   8000,   9000,  80000,  81000, 800000, 801000, 880000, 881000, \r
+  10000,  11000,  12000,  13000,  14000,  15000,  16000,  17000,  18000,  19000, \r
+  90000,  91000, 810000, 811000, 890000, 891000,  20000,  21000,  22000,  23000, \r
+  24000,  25000,  26000,  27000,  28000,  29000,  82000,  83000, 820000, 821000, \r
+ 808000, 809000,  30000,  31000,  32000,  33000,  34000,  35000,  36000,  37000, \r
+  38000,  39000,  92000,  93000, 830000, 831000, 818000, 819000,  40000,  41000, \r
+  42000,  43000,  44000,  45000,  46000,  47000,  48000,  49000,  84000,  85000, \r
+ 840000, 841000,  88000,  89000,  50000,  51000,  52000,  53000,  54000,  55000, \r
+  56000,  57000,  58000,  59000,  94000,  95000, 850000, 851000,  98000,  99000, \r
+  60000,  61000,  62000,  63000,  64000,  65000,  66000,  67000,  68000,  69000, \r
+  86000,  87000, 860000, 861000, 888000, 889000,  70000,  71000,  72000,  73000, \r
+  74000,  75000,  76000,  77000,  78000,  79000,  96000,  97000, 870000, 871000, \r
+ 898000, 899000, 100000, 101000, 102000, 103000, 104000, 105000, 106000, 107000, \r
+ 108000, 109000, 180000, 181000, 900000, 901000, 980000, 981000, 110000, 111000, \r
+ 112000, 113000, 114000, 115000, 116000, 117000, 118000, 119000, 190000, 191000, \r
+ 910000, 911000, 990000, 991000, 120000, 121000, 122000, 123000, 124000, 125000, \r
+ 126000, 127000, 128000, 129000, 182000, 183000, 920000, 921000, 908000, 909000, \r
+ 130000, 131000, 132000, 133000, 134000, 135000, 136000, 137000, 138000, 139000, \r
+ 192000, 193000, 930000, 931000, 918000, 919000, 140000, 141000, 142000, 143000, \r
+ 144000, 145000, 146000, 147000, 148000, 149000, 184000, 185000, 940000, 941000, \r
+ 188000, 189000, 150000, 151000, 152000, 153000, 154000, 155000, 156000, 157000, \r
+ 158000, 159000, 194000, 195000, 950000, 951000, 198000, 199000, 160000, 161000, \r
+ 162000, 163000, 164000, 165000, 166000, 167000, 168000, 169000, 186000, 187000, \r
+ 960000, 961000, 988000, 989000, 170000, 171000, 172000, 173000, 174000, 175000, \r
+ 176000, 177000, 178000, 179000, 196000, 197000, 970000, 971000, 998000, 999000, \r
+ 200000, 201000, 202000, 203000, 204000, 205000, 206000, 207000, 208000, 209000, \r
+ 280000, 281000, 802000, 803000, 882000, 883000, 210000, 211000, 212000, 213000, \r
+ 214000, 215000, 216000, 217000, 218000, 219000, 290000, 291000, 812000, 813000, \r
+ 892000, 893000, 220000, 221000, 222000, 223000, 224000, 225000, 226000, 227000, \r
+ 228000, 229000, 282000, 283000, 822000, 823000, 828000, 829000, 230000, 231000, \r
+ 232000, 233000, 234000, 235000, 236000, 237000, 238000, 239000, 292000, 293000, \r
+ 832000, 833000, 838000, 839000, 240000, 241000, 242000, 243000, 244000, 245000, \r
+ 246000, 247000, 248000, 249000, 284000, 285000, 842000, 843000, 288000, 289000, \r
+ 250000, 251000, 252000, 253000, 254000, 255000, 256000, 257000, 258000, 259000, \r
+ 294000, 295000, 852000, 853000, 298000, 299000, 260000, 261000, 262000, 263000, \r
+ 264000, 265000, 266000, 267000, 268000, 269000, 286000, 287000, 862000, 863000, \r
+ 888000, 889000, 270000, 271000, 272000, 273000, 274000, 275000, 276000, 277000, \r
+ 278000, 279000, 296000, 297000, 872000, 873000, 898000, 899000, 300000, 301000, \r
+ 302000, 303000, 304000, 305000, 306000, 307000, 308000, 309000, 380000, 381000, \r
+ 902000, 903000, 982000, 983000, 310000, 311000, 312000, 313000, 314000, 315000, \r
+ 316000, 317000, 318000, 319000, 390000, 391000, 912000, 913000, 992000, 993000, \r
+ 320000, 321000, 322000, 323000, 324000, 325000, 326000, 327000, 328000, 329000, \r
+ 382000, 383000, 922000, 923000, 928000, 929000, 330000, 331000, 332000, 333000, \r
+ 334000, 335000, 336000, 337000, 338000, 339000, 392000, 393000, 932000, 933000, \r
+ 938000, 939000, 340000, 341000, 342000, 343000, 344000, 345000, 346000, 347000, \r
+ 348000, 349000, 384000, 385000, 942000, 943000, 388000, 389000, 350000, 351000, \r
+ 352000, 353000, 354000, 355000, 356000, 357000, 358000, 359000, 394000, 395000, \r
+ 952000, 953000, 398000, 399000, 360000, 361000, 362000, 363000, 364000, 365000, \r
+ 366000, 367000, 368000, 369000, 386000, 387000, 962000, 963000, 988000, 989000, \r
+ 370000, 371000, 372000, 373000, 374000, 375000, 376000, 377000, 378000, 379000, \r
+ 396000, 397000, 972000, 973000, 998000, 999000, 400000, 401000, 402000, 403000, \r
+ 404000, 405000, 406000, 407000, 408000, 409000, 480000, 481000, 804000, 805000, \r
+ 884000, 885000, 410000, 411000, 412000, 413000, 414000, 415000, 416000, 417000, \r
+ 418000, 419000, 490000, 491000, 814000, 815000, 894000, 895000, 420000, 421000, \r
+ 422000, 423000, 424000, 425000, 426000, 427000, 428000, 429000, 482000, 483000, \r
+ 824000, 825000, 848000, 849000, 430000, 431000, 432000, 433000, 434000, 435000, \r
+ 436000, 437000, 438000, 439000, 492000, 493000, 834000, 835000, 858000, 859000, \r
+ 440000, 441000, 442000, 443000, 444000, 445000, 446000, 447000, 448000, 449000, \r
+ 484000, 485000, 844000, 845000, 488000, 489000, 450000, 451000, 452000, 453000, \r
+ 454000, 455000, 456000, 457000, 458000, 459000, 494000, 495000, 854000, 855000, \r
+ 498000, 499000, 460000, 461000, 462000, 463000, 464000, 465000, 466000, 467000, \r
+ 468000, 469000, 486000, 487000, 864000, 865000, 888000, 889000, 470000, 471000, \r
+ 472000, 473000, 474000, 475000, 476000, 477000, 478000, 479000, 496000, 497000, \r
+ 874000, 875000, 898000, 899000, 500000, 501000, 502000, 503000, 504000, 505000, \r
+ 506000, 507000, 508000, 509000, 580000, 581000, 904000, 905000, 984000, 985000, \r
+ 510000, 511000, 512000, 513000, 514000, 515000, 516000, 517000, 518000, 519000, \r
+ 590000, 591000, 914000, 915000, 994000, 995000, 520000, 521000, 522000, 523000, \r
+ 524000, 525000, 526000, 527000, 528000, 529000, 582000, 583000, 924000, 925000, \r
+ 948000, 949000, 530000, 531000, 532000, 533000, 534000, 535000, 536000, 537000, \r
+ 538000, 539000, 592000, 593000, 934000, 935000, 958000, 959000, 540000, 541000, \r
+ 542000, 543000, 544000, 545000, 546000, 547000, 548000, 549000, 584000, 585000, \r
+ 944000, 945000, 588000, 589000, 550000, 551000, 552000, 553000, 554000, 555000, \r
+ 556000, 557000, 558000, 559000, 594000, 595000, 954000, 955000, 598000, 599000, \r
+ 560000, 561000, 562000, 563000, 564000, 565000, 566000, 567000, 568000, 569000, \r
+ 586000, 587000, 964000, 965000, 988000, 989000, 570000, 571000, 572000, 573000, \r
+ 574000, 575000, 576000, 577000, 578000, 579000, 596000, 597000, 974000, 975000, \r
+ 998000, 999000, 600000, 601000, 602000, 603000, 604000, 605000, 606000, 607000, \r
+ 608000, 609000, 680000, 681000, 806000, 807000, 886000, 887000, 610000, 611000, \r
+ 612000, 613000, 614000, 615000, 616000, 617000, 618000, 619000, 690000, 691000, \r
+ 816000, 817000, 896000, 897000, 620000, 621000, 622000, 623000, 624000, 625000, \r
+ 626000, 627000, 628000, 629000, 682000, 683000, 826000, 827000, 868000, 869000, \r
+ 630000, 631000, 632000, 633000, 634000, 635000, 636000, 637000, 638000, 639000, \r
+ 692000, 693000, 836000, 837000, 878000, 879000, 640000, 641000, 642000, 643000, \r
+ 644000, 645000, 646000, 647000, 648000, 649000, 684000, 685000, 846000, 847000, \r
+ 688000, 689000, 650000, 651000, 652000, 653000, 654000, 655000, 656000, 657000, \r
+ 658000, 659000, 694000, 695000, 856000, 857000, 698000, 699000, 660000, 661000, \r
+ 662000, 663000, 664000, 665000, 666000, 667000, 668000, 669000, 686000, 687000, \r
+ 866000, 867000, 888000, 889000, 670000, 671000, 672000, 673000, 674000, 675000, \r
+ 676000, 677000, 678000, 679000, 696000, 697000, 876000, 877000, 898000, 899000, \r
+ 700000, 701000, 702000, 703000, 704000, 705000, 706000, 707000, 708000, 709000, \r
+ 780000, 781000, 906000, 907000, 986000, 987000, 710000, 711000, 712000, 713000, \r
+ 714000, 715000, 716000, 717000, 718000, 719000, 790000, 791000, 916000, 917000, \r
+ 996000, 997000, 720000, 721000, 722000, 723000, 724000, 725000, 726000, 727000, \r
+ 728000, 729000, 782000, 783000, 926000, 927000, 968000, 969000, 730000, 731000, \r
+ 732000, 733000, 734000, 735000, 736000, 737000, 738000, 739000, 792000, 793000, \r
+ 936000, 937000, 978000, 979000, 740000, 741000, 742000, 743000, 744000, 745000, \r
+ 746000, 747000, 748000, 749000, 784000, 785000, 946000, 947000, 788000, 789000, \r
+ 750000, 751000, 752000, 753000, 754000, 755000, 756000, 757000, 758000, 759000, \r
+ 794000, 795000, 956000, 957000, 798000, 799000, 760000, 761000, 762000, 763000, \r
+ 764000, 765000, 766000, 767000, 768000, 769000, 786000, 787000, 966000, 967000, \r
+ 988000, 989000, 770000, 771000, 772000, 773000, 774000, 775000, 776000, 777000, \r
+ 778000, 779000, 796000, 797000, 976000, 977000, 998000, 999000};\r
+#endif\r
\r
+#if defined(DEC_DPD2BINM) && DEC_DPD2BINM==1 && !defined(DECDPD2BINM)\r
+#define DECDPD2BINM\r
\r
+const uint32_t DPD2BINM[1024]={0,   1000000,   2000000,   3000000,   4000000, \r
+   5000000,   6000000,   7000000,   8000000,   9000000,  80000000,  81000000, \r
+ 800000000, 801000000, 880000000, 881000000,  10000000,  11000000,  12000000, \r
+  13000000,  14000000,  15000000,  16000000,  17000000,  18000000,  19000000, \r
+  90000000,  91000000, 810000000, 811000000, 890000000, 891000000,  20000000, \r
+  21000000,  22000000,  23000000,  24000000,  25000000,  26000000,  27000000, \r
+  28000000,  29000000,  82000000,  83000000, 820000000, 821000000, 808000000, \r
+ 809000000,  30000000,  31000000,  32000000,  33000000,  34000000,  35000000, \r
+  36000000,  37000000,  38000000,  39000000,  92000000,  93000000, 830000000, \r
+ 831000000, 818000000, 819000000,  40000000,  41000000,  42000000,  43000000, \r
+  44000000,  45000000,  46000000,  47000000,  48000000,  49000000,  84000000, \r
+  85000000, 840000000, 841000000,  88000000,  89000000,  50000000,  51000000, \r
+  52000000,  53000000,  54000000,  55000000,  56000000,  57000000,  58000000, \r
+  59000000,  94000000,  95000000, 850000000, 851000000,  98000000,  99000000, \r
+  60000000,  61000000,  62000000,  63000000,  64000000,  65000000,  66000000, \r
+  67000000,  68000000,  69000000,  86000000,  87000000, 860000000, 861000000, \r
+ 888000000, 889000000,  70000000,  71000000,  72000000,  73000000,  74000000, \r
+  75000000,  76000000,  77000000,  78000000,  79000000,  96000000,  97000000, \r
+ 870000000, 871000000, 898000000, 899000000, 100000000, 101000000, 102000000, \r
+ 103000000, 104000000, 105000000, 106000000, 107000000, 108000000, 109000000, \r
+ 180000000, 181000000, 900000000, 901000000, 980000000, 981000000, 110000000, \r
+ 111000000, 112000000, 113000000, 114000000, 115000000, 116000000, 117000000, \r
+ 118000000, 119000000, 190000000, 191000000, 910000000, 911000000, 990000000, \r
+ 991000000, 120000000, 121000000, 122000000, 123000000, 124000000, 125000000, \r
+ 126000000, 127000000, 128000000, 129000000, 182000000, 183000000, 920000000, \r
+ 921000000, 908000000, 909000000, 130000000, 131000000, 132000000, 133000000, \r
+ 134000000, 135000000, 136000000, 137000000, 138000000, 139000000, 192000000, \r
+ 193000000, 930000000, 931000000, 918000000, 919000000, 140000000, 141000000, \r
+ 142000000, 143000000, 144000000, 145000000, 146000000, 147000000, 148000000, \r
+ 149000000, 184000000, 185000000, 940000000, 941000000, 188000000, 189000000, \r
+ 150000000, 151000000, 152000000, 153000000, 154000000, 155000000, 156000000, \r
+ 157000000, 158000000, 159000000, 194000000, 195000000, 950000000, 951000000, \r
+ 198000000, 199000000, 160000000, 161000000, 162000000, 163000000, 164000000, \r
+ 165000000, 166000000, 167000000, 168000000, 169000000, 186000000, 187000000, \r
+ 960000000, 961000000, 988000000, 989000000, 170000000, 171000000, 172000000, \r
+ 173000000, 174000000, 175000000, 176000000, 177000000, 178000000, 179000000, \r
+ 196000000, 197000000, 970000000, 971000000, 998000000, 999000000, 200000000, \r
+ 201000000, 202000000, 203000000, 204000000, 205000000, 206000000, 207000000, \r
+ 208000000, 209000000, 280000000, 281000000, 802000000, 803000000, 882000000, \r
+ 883000000, 210000000, 211000000, 212000000, 213000000, 214000000, 215000000, \r
+ 216000000, 217000000, 218000000, 219000000, 290000000, 291000000, 812000000, \r
+ 813000000, 892000000, 893000000, 220000000, 221000000, 222000000, 223000000, \r
+ 224000000, 225000000, 226000000, 227000000, 228000000, 229000000, 282000000, \r
+ 283000000, 822000000, 823000000, 828000000, 829000000, 230000000, 231000000, \r
+ 232000000, 233000000, 234000000, 235000000, 236000000, 237000000, 238000000, \r
+ 239000000, 292000000, 293000000, 832000000, 833000000, 838000000, 839000000, \r
+ 240000000, 241000000, 242000000, 243000000, 244000000, 245000000, 246000000, \r
+ 247000000, 248000000, 249000000, 284000000, 285000000, 842000000, 843000000, \r
+ 288000000, 289000000, 250000000, 251000000, 252000000, 253000000, 254000000, \r
+ 255000000, 256000000, 257000000, 258000000, 259000000, 294000000, 295000000, \r
+ 852000000, 853000000, 298000000, 299000000, 260000000, 261000000, 262000000, \r
+ 263000000, 264000000, 265000000, 266000000, 267000000, 268000000, 269000000, \r
+ 286000000, 287000000, 862000000, 863000000, 888000000, 889000000, 270000000, \r
+ 271000000, 272000000, 273000000, 274000000, 275000000, 276000000, 277000000, \r
+ 278000000, 279000000, 296000000, 297000000, 872000000, 873000000, 898000000, \r
+ 899000000, 300000000, 301000000, 302000000, 303000000, 304000000, 305000000, \r
+ 306000000, 307000000, 308000000, 309000000, 380000000, 381000000, 902000000, \r
+ 903000000, 982000000, 983000000, 310000000, 311000000, 312000000, 313000000, \r
+ 314000000, 315000000, 316000000, 317000000, 318000000, 319000000, 390000000, \r
+ 391000000, 912000000, 913000000, 992000000, 993000000, 320000000, 321000000, \r
+ 322000000, 323000000, 324000000, 325000000, 326000000, 327000000, 328000000, \r
+ 329000000, 382000000, 383000000, 922000000, 923000000, 928000000, 929000000, \r
+ 330000000, 331000000, 332000000, 333000000, 334000000, 335000000, 336000000, \r
+ 337000000, 338000000, 339000000, 392000000, 393000000, 932000000, 933000000, \r
+ 938000000, 939000000, 340000000, 341000000, 342000000, 343000000, 344000000, \r
+ 345000000, 346000000, 347000000, 348000000, 349000000, 384000000, 385000000, \r
+ 942000000, 943000000, 388000000, 389000000, 350000000, 351000000, 352000000, \r
+ 353000000, 354000000, 355000000, 356000000, 357000000, 358000000, 359000000, \r
+ 394000000, 395000000, 952000000, 953000000, 398000000, 399000000, 360000000, \r
+ 361000000, 362000000, 363000000, 364000000, 365000000, 366000000, 367000000, \r
+ 368000000, 369000000, 386000000, 387000000, 962000000, 963000000, 988000000, \r
+ 989000000, 370000000, 371000000, 372000000, 373000000, 374000000, 375000000, \r
+ 376000000, 377000000, 378000000, 379000000, 396000000, 397000000, 972000000, \r
+ 973000000, 998000000, 999000000, 400000000, 401000000, 402000000, 403000000, \r
+ 404000000, 405000000, 406000000, 407000000, 408000000, 409000000, 480000000, \r
+ 481000000, 804000000, 805000000, 884000000, 885000000, 410000000, 411000000, \r
+ 412000000, 413000000, 414000000, 415000000, 416000000, 417000000, 418000000, \r
+ 419000000, 490000000, 491000000, 814000000, 815000000, 894000000, 895000000, \r
+ 420000000, 421000000, 422000000, 423000000, 424000000, 425000000, 426000000, \r
+ 427000000, 428000000, 429000000, 482000000, 483000000, 824000000, 825000000, \r
+ 848000000, 849000000, 430000000, 431000000, 432000000, 433000000, 434000000, \r
+ 435000000, 436000000, 437000000, 438000000, 439000000, 492000000, 493000000, \r
+ 834000000, 835000000, 858000000, 859000000, 440000000, 441000000, 442000000, \r
+ 443000000, 444000000, 445000000, 446000000, 447000000, 448000000, 449000000, \r
+ 484000000, 485000000, 844000000, 845000000, 488000000, 489000000, 450000000, \r
+ 451000000, 452000000, 453000000, 454000000, 455000000, 456000000, 457000000, \r
+ 458000000, 459000000, 494000000, 495000000, 854000000, 855000000, 498000000, \r
+ 499000000, 460000000, 461000000, 462000000, 463000000, 464000000, 465000000, \r
+ 466000000, 467000000, 468000000, 469000000, 486000000, 487000000, 864000000, \r
+ 865000000, 888000000, 889000000, 470000000, 471000000, 472000000, 473000000, \r
+ 474000000, 475000000, 476000000, 477000000, 478000000, 479000000, 496000000, \r
+ 497000000, 874000000, 875000000, 898000000, 899000000, 500000000, 501000000, \r
+ 502000000, 503000000, 504000000, 505000000, 506000000, 507000000, 508000000, \r
+ 509000000, 580000000, 581000000, 904000000, 905000000, 984000000, 985000000, \r
+ 510000000, 511000000, 512000000, 513000000, 514000000, 515000000, 516000000, \r
+ 517000000, 518000000, 519000000, 590000000, 591000000, 914000000, 915000000, \r
+ 994000000, 995000000, 520000000, 521000000, 522000000, 523000000, 524000000, \r
+ 525000000, 526000000, 527000000, 528000000, 529000000, 582000000, 583000000, \r
+ 924000000, 925000000, 948000000, 949000000, 530000000, 531000000, 532000000, \r
+ 533000000, 534000000, 535000000, 536000000, 537000000, 538000000, 539000000, \r
+ 592000000, 593000000, 934000000, 935000000, 958000000, 959000000, 540000000, \r
+ 541000000, 542000000, 543000000, 544000000, 545000000, 546000000, 547000000, \r
+ 548000000, 549000000, 584000000, 585000000, 944000000, 945000000, 588000000, \r
+ 589000000, 550000000, 551000000, 552000000, 553000000, 554000000, 555000000, \r
+ 556000000, 557000000, 558000000, 559000000, 594000000, 595000000, 954000000, \r
+ 955000000, 598000000, 599000000, 560000000, 561000000, 562000000, 563000000, \r
+ 564000000, 565000000, 566000000, 567000000, 568000000, 569000000, 586000000, \r
+ 587000000, 964000000, 965000000, 988000000, 989000000, 570000000, 571000000, \r
+ 572000000, 573000000, 574000000, 575000000, 576000000, 577000000, 578000000, \r
+ 579000000, 596000000, 597000000, 974000000, 975000000, 998000000, 999000000, \r
+ 600000000, 601000000, 602000000, 603000000, 604000000, 605000000, 606000000, \r
+ 607000000, 608000000, 609000000, 680000000, 681000000, 806000000, 807000000, \r
+ 886000000, 887000000, 610000000, 611000000, 612000000, 613000000, 614000000, \r
+ 615000000, 616000000, 617000000, 618000000, 619000000, 690000000, 691000000, \r
+ 816000000, 817000000, 896000000, 897000000, 620000000, 621000000, 622000000, \r
+ 623000000, 624000000, 625000000, 626000000, 627000000, 628000000, 629000000, \r
+ 682000000, 683000000, 826000000, 827000000, 868000000, 869000000, 630000000, \r
+ 631000000, 632000000, 633000000, 634000000, 635000000, 636000000, 637000000, \r
+ 638000000, 639000000, 692000000, 693000000, 836000000, 837000000, 878000000, \r
+ 879000000, 640000000, 641000000, 642000000, 643000000, 644000000, 645000000, \r
+ 646000000, 647000000, 648000000, 649000000, 684000000, 685000000, 846000000, \r
+ 847000000, 688000000, 689000000, 650000000, 651000000, 652000000, 653000000, \r
+ 654000000, 655000000, 656000000, 657000000, 658000000, 659000000, 694000000, \r
+ 695000000, 856000000, 857000000, 698000000, 699000000, 660000000, 661000000, \r
+ 662000000, 663000000, 664000000, 665000000, 666000000, 667000000, 668000000, \r
+ 669000000, 686000000, 687000000, 866000000, 867000000, 888000000, 889000000, \r
+ 670000000, 671000000, 672000000, 673000000, 674000000, 675000000, 676000000, \r
+ 677000000, 678000000, 679000000, 696000000, 697000000, 876000000, 877000000, \r
+ 898000000, 899000000, 700000000, 701000000, 702000000, 703000000, 704000000, \r
+ 705000000, 706000000, 707000000, 708000000, 709000000, 780000000, 781000000, \r
+ 906000000, 907000000, 986000000, 987000000, 710000000, 711000000, 712000000, \r
+ 713000000, 714000000, 715000000, 716000000, 717000000, 718000000, 719000000, \r
+ 790000000, 791000000, 916000000, 917000000, 996000000, 997000000, 720000000, \r
+ 721000000, 722000000, 723000000, 724000000, 725000000, 726000000, 727000000, \r
+ 728000000, 729000000, 782000000, 783000000, 926000000, 927000000, 968000000, \r
+ 969000000, 730000000, 731000000, 732000000, 733000000, 734000000, 735000000, \r
+ 736000000, 737000000, 738000000, 739000000, 792000000, 793000000, 936000000, \r
+ 937000000, 978000000, 979000000, 740000000, 741000000, 742000000, 743000000, \r
+ 744000000, 745000000, 746000000, 747000000, 748000000, 749000000, 784000000, \r
+ 785000000, 946000000, 947000000, 788000000, 789000000, 750000000, 751000000, \r
+ 752000000, 753000000, 754000000, 755000000, 756000000, 757000000, 758000000, \r
+ 759000000, 794000000, 795000000, 956000000, 957000000, 798000000, 799000000, \r
+ 760000000, 761000000, 762000000, 763000000, 764000000, 765000000, 766000000, \r
+ 767000000, 768000000, 769000000, 786000000, 787000000, 966000000, 967000000, \r
+ 988000000, 989000000, 770000000, 771000000, 772000000, 773000000, 774000000, \r
+ 775000000, 776000000, 777000000, 778000000, 779000000, 796000000, 797000000, \r
+ 976000000, 977000000, 998000000, 999000000};\r
+#endif\r
\r
+#if defined(DEC_BIN2CHAR) && DEC_BIN2CHAR==1 && !defined(DECBIN2CHAR)\r
+#define DECBIN2CHAR\r
\r
+const uint8_t BIN2CHAR[4001]={\r
+ '\0','0','0','0', '\1','0','0','1', '\1','0','0','2', '\1','0','0','3', '\1','0','0','4', \r
+ '\1','0','0','5', '\1','0','0','6', '\1','0','0','7', '\1','0','0','8', '\1','0','0','9', \r
+ '\2','0','1','0', '\2','0','1','1', '\2','0','1','2', '\2','0','1','3', '\2','0','1','4', \r
+ '\2','0','1','5', '\2','0','1','6', '\2','0','1','7', '\2','0','1','8', '\2','0','1','9', \r
+ '\2','0','2','0', '\2','0','2','1', '\2','0','2','2', '\2','0','2','3', '\2','0','2','4', \r
+ '\2','0','2','5', '\2','0','2','6', '\2','0','2','7', '\2','0','2','8', '\2','0','2','9', \r
+ '\2','0','3','0', '\2','0','3','1', '\2','0','3','2', '\2','0','3','3', '\2','0','3','4', \r
+ '\2','0','3','5', '\2','0','3','6', '\2','0','3','7', '\2','0','3','8', '\2','0','3','9', \r
+ '\2','0','4','0', '\2','0','4','1', '\2','0','4','2', '\2','0','4','3', '\2','0','4','4', \r
+ '\2','0','4','5', '\2','0','4','6', '\2','0','4','7', '\2','0','4','8', '\2','0','4','9', \r
+ '\2','0','5','0', '\2','0','5','1', '\2','0','5','2', '\2','0','5','3', '\2','0','5','4', \r
+ '\2','0','5','5', '\2','0','5','6', '\2','0','5','7', '\2','0','5','8', '\2','0','5','9', \r
+ '\2','0','6','0', '\2','0','6','1', '\2','0','6','2', '\2','0','6','3', '\2','0','6','4', \r
+ '\2','0','6','5', '\2','0','6','6', '\2','0','6','7', '\2','0','6','8', '\2','0','6','9', \r
+ '\2','0','7','0', '\2','0','7','1', '\2','0','7','2', '\2','0','7','3', '\2','0','7','4', \r
+ '\2','0','7','5', '\2','0','7','6', '\2','0','7','7', '\2','0','7','8', '\2','0','7','9', \r
+ '\2','0','8','0', '\2','0','8','1', '\2','0','8','2', '\2','0','8','3', '\2','0','8','4', \r
+ '\2','0','8','5', '\2','0','8','6', '\2','0','8','7', '\2','0','8','8', '\2','0','8','9', \r
+ '\2','0','9','0', '\2','0','9','1', '\2','0','9','2', '\2','0','9','3', '\2','0','9','4', \r
+ '\2','0','9','5', '\2','0','9','6', '\2','0','9','7', '\2','0','9','8', '\2','0','9','9', \r
+ '\3','1','0','0', '\3','1','0','1', '\3','1','0','2', '\3','1','0','3', '\3','1','0','4', \r
+ '\3','1','0','5', '\3','1','0','6', '\3','1','0','7', '\3','1','0','8', '\3','1','0','9', \r
+ '\3','1','1','0', '\3','1','1','1', '\3','1','1','2', '\3','1','1','3', '\3','1','1','4', \r
+ '\3','1','1','5', '\3','1','1','6', '\3','1','1','7', '\3','1','1','8', '\3','1','1','9', \r
+ '\3','1','2','0', '\3','1','2','1', '\3','1','2','2', '\3','1','2','3', '\3','1','2','4', \r
+ '\3','1','2','5', '\3','1','2','6', '\3','1','2','7', '\3','1','2','8', '\3','1','2','9', \r
+ '\3','1','3','0', '\3','1','3','1', '\3','1','3','2', '\3','1','3','3', '\3','1','3','4', \r
+ '\3','1','3','5', '\3','1','3','6', '\3','1','3','7', '\3','1','3','8', '\3','1','3','9', \r
+ '\3','1','4','0', '\3','1','4','1', '\3','1','4','2', '\3','1','4','3', '\3','1','4','4', \r
+ '\3','1','4','5', '\3','1','4','6', '\3','1','4','7', '\3','1','4','8', '\3','1','4','9', \r
+ '\3','1','5','0', '\3','1','5','1', '\3','1','5','2', '\3','1','5','3', '\3','1','5','4', \r
+ '\3','1','5','5', '\3','1','5','6', '\3','1','5','7', '\3','1','5','8', '\3','1','5','9', \r
+ '\3','1','6','0', '\3','1','6','1', '\3','1','6','2', '\3','1','6','3', '\3','1','6','4', \r
+ '\3','1','6','5', '\3','1','6','6', '\3','1','6','7', '\3','1','6','8', '\3','1','6','9', \r
+ '\3','1','7','0', '\3','1','7','1', '\3','1','7','2', '\3','1','7','3', '\3','1','7','4', \r
+ '\3','1','7','5', '\3','1','7','6', '\3','1','7','7', '\3','1','7','8', '\3','1','7','9', \r
+ '\3','1','8','0', '\3','1','8','1', '\3','1','8','2', '\3','1','8','3', '\3','1','8','4', \r
+ '\3','1','8','5', '\3','1','8','6', '\3','1','8','7', '\3','1','8','8', '\3','1','8','9', \r
+ '\3','1','9','0', '\3','1','9','1', '\3','1','9','2', '\3','1','9','3', '\3','1','9','4', \r
+ '\3','1','9','5', '\3','1','9','6', '\3','1','9','7', '\3','1','9','8', '\3','1','9','9', \r
+ '\3','2','0','0', '\3','2','0','1', '\3','2','0','2', '\3','2','0','3', '\3','2','0','4', \r
+ '\3','2','0','5', '\3','2','0','6', '\3','2','0','7', '\3','2','0','8', '\3','2','0','9', \r
+ '\3','2','1','0', '\3','2','1','1', '\3','2','1','2', '\3','2','1','3', '\3','2','1','4', \r
+ '\3','2','1','5', '\3','2','1','6', '\3','2','1','7', '\3','2','1','8', '\3','2','1','9', \r
+ '\3','2','2','0', '\3','2','2','1', '\3','2','2','2', '\3','2','2','3', '\3','2','2','4', \r
+ '\3','2','2','5', '\3','2','2','6', '\3','2','2','7', '\3','2','2','8', '\3','2','2','9', \r
+ '\3','2','3','0', '\3','2','3','1', '\3','2','3','2', '\3','2','3','3', '\3','2','3','4', \r
+ '\3','2','3','5', '\3','2','3','6', '\3','2','3','7', '\3','2','3','8', '\3','2','3','9', \r
+ '\3','2','4','0', '\3','2','4','1', '\3','2','4','2', '\3','2','4','3', '\3','2','4','4', \r
+ '\3','2','4','5', '\3','2','4','6', '\3','2','4','7', '\3','2','4','8', '\3','2','4','9', \r
+ '\3','2','5','0', '\3','2','5','1', '\3','2','5','2', '\3','2','5','3', '\3','2','5','4', \r
+ '\3','2','5','5', '\3','2','5','6', '\3','2','5','7', '\3','2','5','8', '\3','2','5','9', \r
+ '\3','2','6','0', '\3','2','6','1', '\3','2','6','2', '\3','2','6','3', '\3','2','6','4', \r
+ '\3','2','6','5', '\3','2','6','6', '\3','2','6','7', '\3','2','6','8', '\3','2','6','9', \r
+ '\3','2','7','0', '\3','2','7','1', '\3','2','7','2', '\3','2','7','3', '\3','2','7','4', \r
+ '\3','2','7','5', '\3','2','7','6', '\3','2','7','7', '\3','2','7','8', '\3','2','7','9', \r
+ '\3','2','8','0', '\3','2','8','1', '\3','2','8','2', '\3','2','8','3', '\3','2','8','4', \r
+ '\3','2','8','5', '\3','2','8','6', '\3','2','8','7', '\3','2','8','8', '\3','2','8','9', \r
+ '\3','2','9','0', '\3','2','9','1', '\3','2','9','2', '\3','2','9','3', '\3','2','9','4', \r
+ '\3','2','9','5', '\3','2','9','6', '\3','2','9','7', '\3','2','9','8', '\3','2','9','9', \r
+ '\3','3','0','0', '\3','3','0','1', '\3','3','0','2', '\3','3','0','3', '\3','3','0','4', \r
+ '\3','3','0','5', '\3','3','0','6', '\3','3','0','7', '\3','3','0','8', '\3','3','0','9', \r
+ '\3','3','1','0', '\3','3','1','1', '\3','3','1','2', '\3','3','1','3', '\3','3','1','4', \r
+ '\3','3','1','5', '\3','3','1','6', '\3','3','1','7', '\3','3','1','8', '\3','3','1','9', \r
+ '\3','3','2','0', '\3','3','2','1', '\3','3','2','2', '\3','3','2','3', '\3','3','2','4', \r
+ '\3','3','2','5', '\3','3','2','6', '\3','3','2','7', '\3','3','2','8', '\3','3','2','9', \r
+ '\3','3','3','0', '\3','3','3','1', '\3','3','3','2', '\3','3','3','3', '\3','3','3','4', \r
+ '\3','3','3','5', '\3','3','3','6', '\3','3','3','7', '\3','3','3','8', '\3','3','3','9', \r
+ '\3','3','4','0', '\3','3','4','1', '\3','3','4','2', '\3','3','4','3', '\3','3','4','4', \r
+ '\3','3','4','5', '\3','3','4','6', '\3','3','4','7', '\3','3','4','8', '\3','3','4','9', \r
+ '\3','3','5','0', '\3','3','5','1', '\3','3','5','2', '\3','3','5','3', '\3','3','5','4', \r
+ '\3','3','5','5', '\3','3','5','6', '\3','3','5','7', '\3','3','5','8', '\3','3','5','9', \r
+ '\3','3','6','0', '\3','3','6','1', '\3','3','6','2', '\3','3','6','3', '\3','3','6','4', \r
+ '\3','3','6','5', '\3','3','6','6', '\3','3','6','7', '\3','3','6','8', '\3','3','6','9', \r
+ '\3','3','7','0', '\3','3','7','1', '\3','3','7','2', '\3','3','7','3', '\3','3','7','4', \r
+ '\3','3','7','5', '\3','3','7','6', '\3','3','7','7', '\3','3','7','8', '\3','3','7','9', \r
+ '\3','3','8','0', '\3','3','8','1', '\3','3','8','2', '\3','3','8','3', '\3','3','8','4', \r
+ '\3','3','8','5', '\3','3','8','6', '\3','3','8','7', '\3','3','8','8', '\3','3','8','9', \r
+ '\3','3','9','0', '\3','3','9','1', '\3','3','9','2', '\3','3','9','3', '\3','3','9','4', \r
+ '\3','3','9','5', '\3','3','9','6', '\3','3','9','7', '\3','3','9','8', '\3','3','9','9', \r
+ '\3','4','0','0', '\3','4','0','1', '\3','4','0','2', '\3','4','0','3', '\3','4','0','4', \r
+ '\3','4','0','5', '\3','4','0','6', '\3','4','0','7', '\3','4','0','8', '\3','4','0','9', \r
+ '\3','4','1','0', '\3','4','1','1', '\3','4','1','2', '\3','4','1','3', '\3','4','1','4', \r
+ '\3','4','1','5', '\3','4','1','6', '\3','4','1','7', '\3','4','1','8', '\3','4','1','9', \r
+ '\3','4','2','0', '\3','4','2','1', '\3','4','2','2', '\3','4','2','3', '\3','4','2','4', \r
+ '\3','4','2','5', '\3','4','2','6', '\3','4','2','7', '\3','4','2','8', '\3','4','2','9', \r
+ '\3','4','3','0', '\3','4','3','1', '\3','4','3','2', '\3','4','3','3', '\3','4','3','4', \r
+ '\3','4','3','5', '\3','4','3','6', '\3','4','3','7', '\3','4','3','8', '\3','4','3','9', \r
+ '\3','4','4','0', '\3','4','4','1', '\3','4','4','2', '\3','4','4','3', '\3','4','4','4', \r
+ '\3','4','4','5', '\3','4','4','6', '\3','4','4','7', '\3','4','4','8', '\3','4','4','9', \r
+ '\3','4','5','0', '\3','4','5','1', '\3','4','5','2', '\3','4','5','3', '\3','4','5','4', \r
+ '\3','4','5','5', '\3','4','5','6', '\3','4','5','7', '\3','4','5','8', '\3','4','5','9', \r
+ '\3','4','6','0', '\3','4','6','1', '\3','4','6','2', '\3','4','6','3', '\3','4','6','4', \r
+ '\3','4','6','5', '\3','4','6','6', '\3','4','6','7', '\3','4','6','8', '\3','4','6','9', \r
+ '\3','4','7','0', '\3','4','7','1', '\3','4','7','2', '\3','4','7','3', '\3','4','7','4', \r
+ '\3','4','7','5', '\3','4','7','6', '\3','4','7','7', '\3','4','7','8', '\3','4','7','9', \r
+ '\3','4','8','0', '\3','4','8','1', '\3','4','8','2', '\3','4','8','3', '\3','4','8','4', \r
+ '\3','4','8','5', '\3','4','8','6', '\3','4','8','7', '\3','4','8','8', '\3','4','8','9', \r
+ '\3','4','9','0', '\3','4','9','1', '\3','4','9','2', '\3','4','9','3', '\3','4','9','4', \r
+ '\3','4','9','5', '\3','4','9','6', '\3','4','9','7', '\3','4','9','8', '\3','4','9','9', \r
+ '\3','5','0','0', '\3','5','0','1', '\3','5','0','2', '\3','5','0','3', '\3','5','0','4', \r
+ '\3','5','0','5', '\3','5','0','6', '\3','5','0','7', '\3','5','0','8', '\3','5','0','9', \r
+ '\3','5','1','0', '\3','5','1','1', '\3','5','1','2', '\3','5','1','3', '\3','5','1','4', \r
+ '\3','5','1','5', '\3','5','1','6', '\3','5','1','7', '\3','5','1','8', '\3','5','1','9', \r
+ '\3','5','2','0', '\3','5','2','1', '\3','5','2','2', '\3','5','2','3', '\3','5','2','4', \r
+ '\3','5','2','5', '\3','5','2','6', '\3','5','2','7', '\3','5','2','8', '\3','5','2','9', \r
+ '\3','5','3','0', '\3','5','3','1', '\3','5','3','2', '\3','5','3','3', '\3','5','3','4', \r
+ '\3','5','3','5', '\3','5','3','6', '\3','5','3','7', '\3','5','3','8', '\3','5','3','9', \r
+ '\3','5','4','0', '\3','5','4','1', '\3','5','4','2', '\3','5','4','3', '\3','5','4','4', \r
+ '\3','5','4','5', '\3','5','4','6', '\3','5','4','7', '\3','5','4','8', '\3','5','4','9', \r
+ '\3','5','5','0', '\3','5','5','1', '\3','5','5','2', '\3','5','5','3', '\3','5','5','4', \r
+ '\3','5','5','5', '\3','5','5','6', '\3','5','5','7', '\3','5','5','8', '\3','5','5','9', \r
+ '\3','5','6','0', '\3','5','6','1', '\3','5','6','2', '\3','5','6','3', '\3','5','6','4', \r
+ '\3','5','6','5', '\3','5','6','6', '\3','5','6','7', '\3','5','6','8', '\3','5','6','9', \r
+ '\3','5','7','0', '\3','5','7','1', '\3','5','7','2', '\3','5','7','3', '\3','5','7','4', \r
+ '\3','5','7','5', '\3','5','7','6', '\3','5','7','7', '\3','5','7','8', '\3','5','7','9', \r
+ '\3','5','8','0', '\3','5','8','1', '\3','5','8','2', '\3','5','8','3', '\3','5','8','4', \r
+ '\3','5','8','5', '\3','5','8','6', '\3','5','8','7', '\3','5','8','8', '\3','5','8','9', \r
+ '\3','5','9','0', '\3','5','9','1', '\3','5','9','2', '\3','5','9','3', '\3','5','9','4', \r
+ '\3','5','9','5', '\3','5','9','6', '\3','5','9','7', '\3','5','9','8', '\3','5','9','9', \r
+ '\3','6','0','0', '\3','6','0','1', '\3','6','0','2', '\3','6','0','3', '\3','6','0','4', \r
+ '\3','6','0','5', '\3','6','0','6', '\3','6','0','7', '\3','6','0','8', '\3','6','0','9', \r
+ '\3','6','1','0', '\3','6','1','1', '\3','6','1','2', '\3','6','1','3', '\3','6','1','4', \r
+ '\3','6','1','5', '\3','6','1','6', '\3','6','1','7', '\3','6','1','8', '\3','6','1','9', \r
+ '\3','6','2','0', '\3','6','2','1', '\3','6','2','2', '\3','6','2','3', '\3','6','2','4', \r
+ '\3','6','2','5', '\3','6','2','6', '\3','6','2','7', '\3','6','2','8', '\3','6','2','9', \r
+ '\3','6','3','0', '\3','6','3','1', '\3','6','3','2', '\3','6','3','3', '\3','6','3','4', \r
+ '\3','6','3','5', '\3','6','3','6', '\3','6','3','7', '\3','6','3','8', '\3','6','3','9', \r
+ '\3','6','4','0', '\3','6','4','1', '\3','6','4','2', '\3','6','4','3', '\3','6','4','4', \r
+ '\3','6','4','5', '\3','6','4','6', '\3','6','4','7', '\3','6','4','8', '\3','6','4','9', \r
+ '\3','6','5','0', '\3','6','5','1', '\3','6','5','2', '\3','6','5','3', '\3','6','5','4', \r
+ '\3','6','5','5', '\3','6','5','6', '\3','6','5','7', '\3','6','5','8', '\3','6','5','9', \r
+ '\3','6','6','0', '\3','6','6','1', '\3','6','6','2', '\3','6','6','3', '\3','6','6','4', \r
+ '\3','6','6','5', '\3','6','6','6', '\3','6','6','7', '\3','6','6','8', '\3','6','6','9', \r
+ '\3','6','7','0', '\3','6','7','1', '\3','6','7','2', '\3','6','7','3', '\3','6','7','4', \r
+ '\3','6','7','5', '\3','6','7','6', '\3','6','7','7', '\3','6','7','8', '\3','6','7','9', \r
+ '\3','6','8','0', '\3','6','8','1', '\3','6','8','2', '\3','6','8','3', '\3','6','8','4', \r
+ '\3','6','8','5', '\3','6','8','6', '\3','6','8','7', '\3','6','8','8', '\3','6','8','9', \r
+ '\3','6','9','0', '\3','6','9','1', '\3','6','9','2', '\3','6','9','3', '\3','6','9','4', \r
+ '\3','6','9','5', '\3','6','9','6', '\3','6','9','7', '\3','6','9','8', '\3','6','9','9', \r
+ '\3','7','0','0', '\3','7','0','1', '\3','7','0','2', '\3','7','0','3', '\3','7','0','4', \r
+ '\3','7','0','5', '\3','7','0','6', '\3','7','0','7', '\3','7','0','8', '\3','7','0','9', \r
+ '\3','7','1','0', '\3','7','1','1', '\3','7','1','2', '\3','7','1','3', '\3','7','1','4', \r
+ '\3','7','1','5', '\3','7','1','6', '\3','7','1','7', '\3','7','1','8', '\3','7','1','9', \r
+ '\3','7','2','0', '\3','7','2','1', '\3','7','2','2', '\3','7','2','3', '\3','7','2','4', \r
+ '\3','7','2','5', '\3','7','2','6', '\3','7','2','7', '\3','7','2','8', '\3','7','2','9', \r
+ '\3','7','3','0', '\3','7','3','1', '\3','7','3','2', '\3','7','3','3', '\3','7','3','4', \r
+ '\3','7','3','5', '\3','7','3','6', '\3','7','3','7', '\3','7','3','8', '\3','7','3','9', \r
+ '\3','7','4','0', '\3','7','4','1', '\3','7','4','2', '\3','7','4','3', '\3','7','4','4', \r
+ '\3','7','4','5', '\3','7','4','6', '\3','7','4','7', '\3','7','4','8', '\3','7','4','9', \r
+ '\3','7','5','0', '\3','7','5','1', '\3','7','5','2', '\3','7','5','3', '\3','7','5','4', \r
+ '\3','7','5','5', '\3','7','5','6', '\3','7','5','7', '\3','7','5','8', '\3','7','5','9', \r
+ '\3','7','6','0', '\3','7','6','1', '\3','7','6','2', '\3','7','6','3', '\3','7','6','4', \r
+ '\3','7','6','5', '\3','7','6','6', '\3','7','6','7', '\3','7','6','8', '\3','7','6','9', \r
+ '\3','7','7','0', '\3','7','7','1', '\3','7','7','2', '\3','7','7','3', '\3','7','7','4', \r
+ '\3','7','7','5', '\3','7','7','6', '\3','7','7','7', '\3','7','7','8', '\3','7','7','9', \r
+ '\3','7','8','0', '\3','7','8','1', '\3','7','8','2', '\3','7','8','3', '\3','7','8','4', \r
+ '\3','7','8','5', '\3','7','8','6', '\3','7','8','7', '\3','7','8','8', '\3','7','8','9', \r
+ '\3','7','9','0', '\3','7','9','1', '\3','7','9','2', '\3','7','9','3', '\3','7','9','4', \r
+ '\3','7','9','5', '\3','7','9','6', '\3','7','9','7', '\3','7','9','8', '\3','7','9','9', \r
+ '\3','8','0','0', '\3','8','0','1', '\3','8','0','2', '\3','8','0','3', '\3','8','0','4', \r
+ '\3','8','0','5', '\3','8','0','6', '\3','8','0','7', '\3','8','0','8', '\3','8','0','9', \r
+ '\3','8','1','0', '\3','8','1','1', '\3','8','1','2', '\3','8','1','3', '\3','8','1','4', \r
+ '\3','8','1','5', '\3','8','1','6', '\3','8','1','7', '\3','8','1','8', '\3','8','1','9', \r
+ '\3','8','2','0', '\3','8','2','1', '\3','8','2','2', '\3','8','2','3', '\3','8','2','4', \r
+ '\3','8','2','5', '\3','8','2','6', '\3','8','2','7', '\3','8','2','8', '\3','8','2','9', \r
+ '\3','8','3','0', '\3','8','3','1', '\3','8','3','2', '\3','8','3','3', '\3','8','3','4', \r
+ '\3','8','3','5', '\3','8','3','6', '\3','8','3','7', '\3','8','3','8', '\3','8','3','9', \r
+ '\3','8','4','0', '\3','8','4','1', '\3','8','4','2', '\3','8','4','3', '\3','8','4','4', \r
+ '\3','8','4','5', '\3','8','4','6', '\3','8','4','7', '\3','8','4','8', '\3','8','4','9', \r
+ '\3','8','5','0', '\3','8','5','1', '\3','8','5','2', '\3','8','5','3', '\3','8','5','4', \r
+ '\3','8','5','5', '\3','8','5','6', '\3','8','5','7', '\3','8','5','8', '\3','8','5','9', \r
+ '\3','8','6','0', '\3','8','6','1', '\3','8','6','2', '\3','8','6','3', '\3','8','6','4', \r
+ '\3','8','6','5', '\3','8','6','6', '\3','8','6','7', '\3','8','6','8', '\3','8','6','9', \r
+ '\3','8','7','0', '\3','8','7','1', '\3','8','7','2', '\3','8','7','3', '\3','8','7','4', \r
+ '\3','8','7','5', '\3','8','7','6', '\3','8','7','7', '\3','8','7','8', '\3','8','7','9', \r
+ '\3','8','8','0', '\3','8','8','1', '\3','8','8','2', '\3','8','8','3', '\3','8','8','4', \r
+ '\3','8','8','5', '\3','8','8','6', '\3','8','8','7', '\3','8','8','8', '\3','8','8','9', \r
+ '\3','8','9','0', '\3','8','9','1', '\3','8','9','2', '\3','8','9','3', '\3','8','9','4', \r
+ '\3','8','9','5', '\3','8','9','6', '\3','8','9','7', '\3','8','9','8', '\3','8','9','9', \r
+ '\3','9','0','0', '\3','9','0','1', '\3','9','0','2', '\3','9','0','3', '\3','9','0','4', \r
+ '\3','9','0','5', '\3','9','0','6', '\3','9','0','7', '\3','9','0','8', '\3','9','0','9', \r
+ '\3','9','1','0', '\3','9','1','1', '\3','9','1','2', '\3','9','1','3', '\3','9','1','4', \r
+ '\3','9','1','5', '\3','9','1','6', '\3','9','1','7', '\3','9','1','8', '\3','9','1','9', \r
+ '\3','9','2','0', '\3','9','2','1', '\3','9','2','2', '\3','9','2','3', '\3','9','2','4', \r
+ '\3','9','2','5', '\3','9','2','6', '\3','9','2','7', '\3','9','2','8', '\3','9','2','9', \r
+ '\3','9','3','0', '\3','9','3','1', '\3','9','3','2', '\3','9','3','3', '\3','9','3','4', \r
+ '\3','9','3','5', '\3','9','3','6', '\3','9','3','7', '\3','9','3','8', '\3','9','3','9', \r
+ '\3','9','4','0', '\3','9','4','1', '\3','9','4','2', '\3','9','4','3', '\3','9','4','4', \r
+ '\3','9','4','5', '\3','9','4','6', '\3','9','4','7', '\3','9','4','8', '\3','9','4','9', \r
+ '\3','9','5','0', '\3','9','5','1', '\3','9','5','2', '\3','9','5','3', '\3','9','5','4', \r
+ '\3','9','5','5', '\3','9','5','6', '\3','9','5','7', '\3','9','5','8', '\3','9','5','9', \r
+ '\3','9','6','0', '\3','9','6','1', '\3','9','6','2', '\3','9','6','3', '\3','9','6','4', \r
+ '\3','9','6','5', '\3','9','6','6', '\3','9','6','7', '\3','9','6','8', '\3','9','6','9', \r
+ '\3','9','7','0', '\3','9','7','1', '\3','9','7','2', '\3','9','7','3', '\3','9','7','4', \r
+ '\3','9','7','5', '\3','9','7','6', '\3','9','7','7', '\3','9','7','8', '\3','9','7','9', \r
+ '\3','9','8','0', '\3','9','8','1', '\3','9','8','2', '\3','9','8','3', '\3','9','8','4', \r
+ '\3','9','8','5', '\3','9','8','6', '\3','9','8','7', '\3','9','8','8', '\3','9','8','9', \r
+ '\3','9','9','0', '\3','9','9','1', '\3','9','9','2', '\3','9','9','3', '\3','9','9','4', \r
+ '\3','9','9','5', '\3','9','9','6', '\3','9','9','7', '\3','9','9','8', '\3','9','9','9', '\0'};\r
+#endif\r
\r
+#if defined(DEC_DPD2BCD8) && DEC_DPD2BCD8==1 && !defined(DECDPD2BCD8)\r
+#define DECDPD2BCD8\r
\r
+const uint8_t DPD2BCD8[4096]={\r
+ 0,0,0,0, 0,0,1,1, 0,0,2,1, 0,0,3,1, 0,0,4,1, 0,0,5,1, 0,0,6,1, 0,0,7,1, 0,0,8,1, \r
+ 0,0,9,1, 0,8,0,2, 0,8,1,2, 8,0,0,3, 8,0,1,3, 8,8,0,3, 8,8,1,3, 0,1,0,2, 0,1,1,2, \r
+ 0,1,2,2, 0,1,3,2, 0,1,4,2, 0,1,5,2, 0,1,6,2, 0,1,7,2, 0,1,8,2, 0,1,9,2, 0,9,0,2, \r
+ 0,9,1,2, 8,1,0,3, 8,1,1,3, 8,9,0,3, 8,9,1,3, 0,2,0,2, 0,2,1,2, 0,2,2,2, 0,2,3,2, \r
+ 0,2,4,2, 0,2,5,2, 0,2,6,2, 0,2,7,2, 0,2,8,2, 0,2,9,2, 0,8,2,2, 0,8,3,2, 8,2,0,3, \r
+ 8,2,1,3, 8,0,8,3, 8,0,9,3, 0,3,0,2, 0,3,1,2, 0,3,2,2, 0,3,3,2, 0,3,4,2, 0,3,5,2, \r
+ 0,3,6,2, 0,3,7,2, 0,3,8,2, 0,3,9,2, 0,9,2,2, 0,9,3,2, 8,3,0,3, 8,3,1,3, 8,1,8,3, \r
+ 8,1,9,3, 0,4,0,2, 0,4,1,2, 0,4,2,2, 0,4,3,2, 0,4,4,2, 0,4,5,2, 0,4,6,2, 0,4,7,2, \r
+ 0,4,8,2, 0,4,9,2, 0,8,4,2, 0,8,5,2, 8,4,0,3, 8,4,1,3, 0,8,8,2, 0,8,9,2, 0,5,0,2, \r
+ 0,5,1,2, 0,5,2,2, 0,5,3,2, 0,5,4,2, 0,5,5,2, 0,5,6,2, 0,5,7,2, 0,5,8,2, 0,5,9,2, \r
+ 0,9,4,2, 0,9,5,2, 8,5,0,3, 8,5,1,3, 0,9,8,2, 0,9,9,2, 0,6,0,2, 0,6,1,2, 0,6,2,2, \r
+ 0,6,3,2, 0,6,4,2, 0,6,5,2, 0,6,6,2, 0,6,7,2, 0,6,8,2, 0,6,9,2, 0,8,6,2, 0,8,7,2, \r
+ 8,6,0,3, 8,6,1,3, 8,8,8,3, 8,8,9,3, 0,7,0,2, 0,7,1,2, 0,7,2,2, 0,7,3,2, 0,7,4,2, \r
+ 0,7,5,2, 0,7,6,2, 0,7,7,2, 0,7,8,2, 0,7,9,2, 0,9,6,2, 0,9,7,2, 8,7,0,3, 8,7,1,3, \r
+ 8,9,8,3, 8,9,9,3, 1,0,0,3, 1,0,1,3, 1,0,2,3, 1,0,3,3, 1,0,4,3, 1,0,5,3, 1,0,6,3, \r
+ 1,0,7,3, 1,0,8,3, 1,0,9,3, 1,8,0,3, 1,8,1,3, 9,0,0,3, 9,0,1,3, 9,8,0,3, 9,8,1,3, \r
+ 1,1,0,3, 1,1,1,3, 1,1,2,3, 1,1,3,3, 1,1,4,3, 1,1,5,3, 1,1,6,3, 1,1,7,3, 1,1,8,3, \r
+ 1,1,9,3, 1,9,0,3, 1,9,1,3, 9,1,0,3, 9,1,1,3, 9,9,0,3, 9,9,1,3, 1,2,0,3, 1,2,1,3, \r
+ 1,2,2,3, 1,2,3,3, 1,2,4,3, 1,2,5,3, 1,2,6,3, 1,2,7,3, 1,2,8,3, 1,2,9,3, 1,8,2,3, \r
+ 1,8,3,3, 9,2,0,3, 9,2,1,3, 9,0,8,3, 9,0,9,3, 1,3,0,3, 1,3,1,3, 1,3,2,3, 1,3,3,3, \r
+ 1,3,4,3, 1,3,5,3, 1,3,6,3, 1,3,7,3, 1,3,8,3, 1,3,9,3, 1,9,2,3, 1,9,3,3, 9,3,0,3, \r
+ 9,3,1,3, 9,1,8,3, 9,1,9,3, 1,4,0,3, 1,4,1,3, 1,4,2,3, 1,4,3,3, 1,4,4,3, 1,4,5,3, \r
+ 1,4,6,3, 1,4,7,3, 1,4,8,3, 1,4,9,3, 1,8,4,3, 1,8,5,3, 9,4,0,3, 9,4,1,3, 1,8,8,3, \r
+ 1,8,9,3, 1,5,0,3, 1,5,1,3, 1,5,2,3, 1,5,3,3, 1,5,4,3, 1,5,5,3, 1,5,6,3, 1,5,7,3, \r
+ 1,5,8,3, 1,5,9,3, 1,9,4,3, 1,9,5,3, 9,5,0,3, 9,5,1,3, 1,9,8,3, 1,9,9,3, 1,6,0,3, \r
+ 1,6,1,3, 1,6,2,3, 1,6,3,3, 1,6,4,3, 1,6,5,3, 1,6,6,3, 1,6,7,3, 1,6,8,3, 1,6,9,3, \r
+ 1,8,6,3, 1,8,7,3, 9,6,0,3, 9,6,1,3, 9,8,8,3, 9,8,9,3, 1,7,0,3, 1,7,1,3, 1,7,2,3, \r
+ 1,7,3,3, 1,7,4,3, 1,7,5,3, 1,7,6,3, 1,7,7,3, 1,7,8,3, 1,7,9,3, 1,9,6,3, 1,9,7,3, \r
+ 9,7,0,3, 9,7,1,3, 9,9,8,3, 9,9,9,3, 2,0,0,3, 2,0,1,3, 2,0,2,3, 2,0,3,3, 2,0,4,3, \r
+ 2,0,5,3, 2,0,6,3, 2,0,7,3, 2,0,8,3, 2,0,9,3, 2,8,0,3, 2,8,1,3, 8,0,2,3, 8,0,3,3, \r
+ 8,8,2,3, 8,8,3,3, 2,1,0,3, 2,1,1,3, 2,1,2,3, 2,1,3,3, 2,1,4,3, 2,1,5,3, 2,1,6,3, \r
+ 2,1,7,3, 2,1,8,3, 2,1,9,3, 2,9,0,3, 2,9,1,3, 8,1,2,3, 8,1,3,3, 8,9,2,3, 8,9,3,3, \r
+ 2,2,0,3, 2,2,1,3, 2,2,2,3, 2,2,3,3, 2,2,4,3, 2,2,5,3, 2,2,6,3, 2,2,7,3, 2,2,8,3, \r
+ 2,2,9,3, 2,8,2,3, 2,8,3,3, 8,2,2,3, 8,2,3,3, 8,2,8,3, 8,2,9,3, 2,3,0,3, 2,3,1,3, \r
+ 2,3,2,3, 2,3,3,3, 2,3,4,3, 2,3,5,3, 2,3,6,3, 2,3,7,3, 2,3,8,3, 2,3,9,3, 2,9,2,3, \r
+ 2,9,3,3, 8,3,2,3, 8,3,3,3, 8,3,8,3, 8,3,9,3, 2,4,0,3, 2,4,1,3, 2,4,2,3, 2,4,3,3, \r
+ 2,4,4,3, 2,4,5,3, 2,4,6,3, 2,4,7,3, 2,4,8,3, 2,4,9,3, 2,8,4,3, 2,8,5,3, 8,4,2,3, \r
+ 8,4,3,3, 2,8,8,3, 2,8,9,3, 2,5,0,3, 2,5,1,3, 2,5,2,3, 2,5,3,3, 2,5,4,3, 2,5,5,3, \r
+ 2,5,6,3, 2,5,7,3, 2,5,8,3, 2,5,9,3, 2,9,4,3, 2,9,5,3, 8,5,2,3, 8,5,3,3, 2,9,8,3, \r
+ 2,9,9,3, 2,6,0,3, 2,6,1,3, 2,6,2,3, 2,6,3,3, 2,6,4,3, 2,6,5,3, 2,6,6,3, 2,6,7,3, \r
+ 2,6,8,3, 2,6,9,3, 2,8,6,3, 2,8,7,3, 8,6,2,3, 8,6,3,3, 8,8,8,3, 8,8,9,3, 2,7,0,3, \r
+ 2,7,1,3, 2,7,2,3, 2,7,3,3, 2,7,4,3, 2,7,5,3, 2,7,6,3, 2,7,7,3, 2,7,8,3, 2,7,9,3, \r
+ 2,9,6,3, 2,9,7,3, 8,7,2,3, 8,7,3,3, 8,9,8,3, 8,9,9,3, 3,0,0,3, 3,0,1,3, 3,0,2,3, \r
+ 3,0,3,3, 3,0,4,3, 3,0,5,3, 3,0,6,3, 3,0,7,3, 3,0,8,3, 3,0,9,3, 3,8,0,3, 3,8,1,3, \r
+ 9,0,2,3, 9,0,3,3, 9,8,2,3, 9,8,3,3, 3,1,0,3, 3,1,1,3, 3,1,2,3, 3,1,3,3, 3,1,4,3, \r
+ 3,1,5,3, 3,1,6,3, 3,1,7,3, 3,1,8,3, 3,1,9,3, 3,9,0,3, 3,9,1,3, 9,1,2,3, 9,1,3,3, \r
+ 9,9,2,3, 9,9,3,3, 3,2,0,3, 3,2,1,3, 3,2,2,3, 3,2,3,3, 3,2,4,3, 3,2,5,3, 3,2,6,3, \r
+ 3,2,7,3, 3,2,8,3, 3,2,9,3, 3,8,2,3, 3,8,3,3, 9,2,2,3, 9,2,3,3, 9,2,8,3, 9,2,9,3, \r
+ 3,3,0,3, 3,3,1,3, 3,3,2,3, 3,3,3,3, 3,3,4,3, 3,3,5,3, 3,3,6,3, 3,3,7,3, 3,3,8,3, \r
+ 3,3,9,3, 3,9,2,3, 3,9,3,3, 9,3,2,3, 9,3,3,3, 9,3,8,3, 9,3,9,3, 3,4,0,3, 3,4,1,3, \r
+ 3,4,2,3, 3,4,3,3, 3,4,4,3, 3,4,5,3, 3,4,6,3, 3,4,7,3, 3,4,8,3, 3,4,9,3, 3,8,4,3, \r
+ 3,8,5,3, 9,4,2,3, 9,4,3,3, 3,8,8,3, 3,8,9,3, 3,5,0,3, 3,5,1,3, 3,5,2,3, 3,5,3,3, \r
+ 3,5,4,3, 3,5,5,3, 3,5,6,3, 3,5,7,3, 3,5,8,3, 3,5,9,3, 3,9,4,3, 3,9,5,3, 9,5,2,3, \r
+ 9,5,3,3, 3,9,8,3, 3,9,9,3, 3,6,0,3, 3,6,1,3, 3,6,2,3, 3,6,3,3, 3,6,4,3, 3,6,5,3, \r
+ 3,6,6,3, 3,6,7,3, 3,6,8,3, 3,6,9,3, 3,8,6,3, 3,8,7,3, 9,6,2,3, 9,6,3,3, 9,8,8,3, \r
+ 9,8,9,3, 3,7,0,3, 3,7,1,3, 3,7,2,3, 3,7,3,3, 3,7,4,3, 3,7,5,3, 3,7,6,3, 3,7,7,3, \r
+ 3,7,8,3, 3,7,9,3, 3,9,6,3, 3,9,7,3, 9,7,2,3, 9,7,3,3, 9,9,8,3, 9,9,9,3, 4,0,0,3, \r
+ 4,0,1,3, 4,0,2,3, 4,0,3,3, 4,0,4,3, 4,0,5,3, 4,0,6,3, 4,0,7,3, 4,0,8,3, 4,0,9,3, \r
+ 4,8,0,3, 4,8,1,3, 8,0,4,3, 8,0,5,3, 8,8,4,3, 8,8,5,3, 4,1,0,3, 4,1,1,3, 4,1,2,3, \r
+ 4,1,3,3, 4,1,4,3, 4,1,5,3, 4,1,6,3, 4,1,7,3, 4,1,8,3, 4,1,9,3, 4,9,0,3, 4,9,1,3, \r
+ 8,1,4,3, 8,1,5,3, 8,9,4,3, 8,9,5,3, 4,2,0,3, 4,2,1,3, 4,2,2,3, 4,2,3,3, 4,2,4,3, \r
+ 4,2,5,3, 4,2,6,3, 4,2,7,3, 4,2,8,3, 4,2,9,3, 4,8,2,3, 4,8,3,3, 8,2,4,3, 8,2,5,3, \r
+ 8,4,8,3, 8,4,9,3, 4,3,0,3, 4,3,1,3, 4,3,2,3, 4,3,3,3, 4,3,4,3, 4,3,5,3, 4,3,6,3, \r
+ 4,3,7,3, 4,3,8,3, 4,3,9,3, 4,9,2,3, 4,9,3,3, 8,3,4,3, 8,3,5,3, 8,5,8,3, 8,5,9,3, \r
+ 4,4,0,3, 4,4,1,3, 4,4,2,3, 4,4,3,3, 4,4,4,3, 4,4,5,3, 4,4,6,3, 4,4,7,3, 4,4,8,3, \r
+ 4,4,9,3, 4,8,4,3, 4,8,5,3, 8,4,4,3, 8,4,5,3, 4,8,8,3, 4,8,9,3, 4,5,0,3, 4,5,1,3, \r
+ 4,5,2,3, 4,5,3,3, 4,5,4,3, 4,5,5,3, 4,5,6,3, 4,5,7,3, 4,5,8,3, 4,5,9,3, 4,9,4,3, \r
+ 4,9,5,3, 8,5,4,3, 8,5,5,3, 4,9,8,3, 4,9,9,3, 4,6,0,3, 4,6,1,3, 4,6,2,3, 4,6,3,3, \r
+ 4,6,4,3, 4,6,5,3, 4,6,6,3, 4,6,7,3, 4,6,8,3, 4,6,9,3, 4,8,6,3, 4,8,7,3, 8,6,4,3, \r
+ 8,6,5,3, 8,8,8,3, 8,8,9,3, 4,7,0,3, 4,7,1,3, 4,7,2,3, 4,7,3,3, 4,7,4,3, 4,7,5,3, \r
+ 4,7,6,3, 4,7,7,3, 4,7,8,3, 4,7,9,3, 4,9,6,3, 4,9,7,3, 8,7,4,3, 8,7,5,3, 8,9,8,3, \r
+ 8,9,9,3, 5,0,0,3, 5,0,1,3, 5,0,2,3, 5,0,3,3, 5,0,4,3, 5,0,5,3, 5,0,6,3, 5,0,7,3, \r
+ 5,0,8,3, 5,0,9,3, 5,8,0,3, 5,8,1,3, 9,0,4,3, 9,0,5,3, 9,8,4,3, 9,8,5,3, 5,1,0,3, \r
+ 5,1,1,3, 5,1,2,3, 5,1,3,3, 5,1,4,3, 5,1,5,3, 5,1,6,3, 5,1,7,3, 5,1,8,3, 5,1,9,3, \r
+ 5,9,0,3, 5,9,1,3, 9,1,4,3, 9,1,5,3, 9,9,4,3, 9,9,5,3, 5,2,0,3, 5,2,1,3, 5,2,2,3, \r
+ 5,2,3,3, 5,2,4,3, 5,2,5,3, 5,2,6,3, 5,2,7,3, 5,2,8,3, 5,2,9,3, 5,8,2,3, 5,8,3,3, \r
+ 9,2,4,3, 9,2,5,3, 9,4,8,3, 9,4,9,3, 5,3,0,3, 5,3,1,3, 5,3,2,3, 5,3,3,3, 5,3,4,3, \r
+ 5,3,5,3, 5,3,6,3, 5,3,7,3, 5,3,8,3, 5,3,9,3, 5,9,2,3, 5,9,3,3, 9,3,4,3, 9,3,5,3, \r
+ 9,5,8,3, 9,5,9,3, 5,4,0,3, 5,4,1,3, 5,4,2,3, 5,4,3,3, 5,4,4,3, 5,4,5,3, 5,4,6,3, \r
+ 5,4,7,3, 5,4,8,3, 5,4,9,3, 5,8,4,3, 5,8,5,3, 9,4,4,3, 9,4,5,3, 5,8,8,3, 5,8,9,3, \r
+ 5,5,0,3, 5,5,1,3, 5,5,2,3, 5,5,3,3, 5,5,4,3, 5,5,5,3, 5,5,6,3, 5,5,7,3, 5,5,8,3, \r
+ 5,5,9,3, 5,9,4,3, 5,9,5,3, 9,5,4,3, 9,5,5,3, 5,9,8,3, 5,9,9,3, 5,6,0,3, 5,6,1,3, \r
+ 5,6,2,3, 5,6,3,3, 5,6,4,3, 5,6,5,3, 5,6,6,3, 5,6,7,3, 5,6,8,3, 5,6,9,3, 5,8,6,3, \r
+ 5,8,7,3, 9,6,4,3, 9,6,5,3, 9,8,8,3, 9,8,9,3, 5,7,0,3, 5,7,1,3, 5,7,2,3, 5,7,3,3, \r
+ 5,7,4,3, 5,7,5,3, 5,7,6,3, 5,7,7,3, 5,7,8,3, 5,7,9,3, 5,9,6,3, 5,9,7,3, 9,7,4,3, \r
+ 9,7,5,3, 9,9,8,3, 9,9,9,3, 6,0,0,3, 6,0,1,3, 6,0,2,3, 6,0,3,3, 6,0,4,3, 6,0,5,3, \r
+ 6,0,6,3, 6,0,7,3, 6,0,8,3, 6,0,9,3, 6,8,0,3, 6,8,1,3, 8,0,6,3, 8,0,7,3, 8,8,6,3, \r
+ 8,8,7,3, 6,1,0,3, 6,1,1,3, 6,1,2,3, 6,1,3,3, 6,1,4,3, 6,1,5,3, 6,1,6,3, 6,1,7,3, \r
+ 6,1,8,3, 6,1,9,3, 6,9,0,3, 6,9,1,3, 8,1,6,3, 8,1,7,3, 8,9,6,3, 8,9,7,3, 6,2,0,3, \r
+ 6,2,1,3, 6,2,2,3, 6,2,3,3, 6,2,4,3, 6,2,5,3, 6,2,6,3, 6,2,7,3, 6,2,8,3, 6,2,9,3, \r
+ 6,8,2,3, 6,8,3,3, 8,2,6,3, 8,2,7,3, 8,6,8,3, 8,6,9,3, 6,3,0,3, 6,3,1,3, 6,3,2,3, \r
+ 6,3,3,3, 6,3,4,3, 6,3,5,3, 6,3,6,3, 6,3,7,3, 6,3,8,3, 6,3,9,3, 6,9,2,3, 6,9,3,3, \r
+ 8,3,6,3, 8,3,7,3, 8,7,8,3, 8,7,9,3, 6,4,0,3, 6,4,1,3, 6,4,2,3, 6,4,3,3, 6,4,4,3, \r
+ 6,4,5,3, 6,4,6,3, 6,4,7,3, 6,4,8,3, 6,4,9,3, 6,8,4,3, 6,8,5,3, 8,4,6,3, 8,4,7,3, \r
+ 6,8,8,3, 6,8,9,3, 6,5,0,3, 6,5,1,3, 6,5,2,3, 6,5,3,3, 6,5,4,3, 6,5,5,3, 6,5,6,3, \r
+ 6,5,7,3, 6,5,8,3, 6,5,9,3, 6,9,4,3, 6,9,5,3, 8,5,6,3, 8,5,7,3, 6,9,8,3, 6,9,9,3, \r
+ 6,6,0,3, 6,6,1,3, 6,6,2,3, 6,6,3,3, 6,6,4,3, 6,6,5,3, 6,6,6,3, 6,6,7,3, 6,6,8,3, \r
+ 6,6,9,3, 6,8,6,3, 6,8,7,3, 8,6,6,3, 8,6,7,3, 8,8,8,3, 8,8,9,3, 6,7,0,3, 6,7,1,3, \r
+ 6,7,2,3, 6,7,3,3, 6,7,4,3, 6,7,5,3, 6,7,6,3, 6,7,7,3, 6,7,8,3, 6,7,9,3, 6,9,6,3, \r
+ 6,9,7,3, 8,7,6,3, 8,7,7,3, 8,9,8,3, 8,9,9,3, 7,0,0,3, 7,0,1,3, 7,0,2,3, 7,0,3,3, \r
+ 7,0,4,3, 7,0,5,3, 7,0,6,3, 7,0,7,3, 7,0,8,3, 7,0,9,3, 7,8,0,3, 7,8,1,3, 9,0,6,3, \r
+ 9,0,7,3, 9,8,6,3, 9,8,7,3, 7,1,0,3, 7,1,1,3, 7,1,2,3, 7,1,3,3, 7,1,4,3, 7,1,5,3, \r
+ 7,1,6,3, 7,1,7,3, 7,1,8,3, 7,1,9,3, 7,9,0,3, 7,9,1,3, 9,1,6,3, 9,1,7,3, 9,9,6,3, \r
+ 9,9,7,3, 7,2,0,3, 7,2,1,3, 7,2,2,3, 7,2,3,3, 7,2,4,3, 7,2,5,3, 7,2,6,3, 7,2,7,3, \r
+ 7,2,8,3, 7,2,9,3, 7,8,2,3, 7,8,3,3, 9,2,6,3, 9,2,7,3, 9,6,8,3, 9,6,9,3, 7,3,0,3, \r
+ 7,3,1,3, 7,3,2,3, 7,3,3,3, 7,3,4,3, 7,3,5,3, 7,3,6,3, 7,3,7,3, 7,3,8,3, 7,3,9,3, \r
+ 7,9,2,3, 7,9,3,3, 9,3,6,3, 9,3,7,3, 9,7,8,3, 9,7,9,3, 7,4,0,3, 7,4,1,3, 7,4,2,3, \r
+ 7,4,3,3, 7,4,4,3, 7,4,5,3, 7,4,6,3, 7,4,7,3, 7,4,8,3, 7,4,9,3, 7,8,4,3, 7,8,5,3, \r
+ 9,4,6,3, 9,4,7,3, 7,8,8,3, 7,8,9,3, 7,5,0,3, 7,5,1,3, 7,5,2,3, 7,5,3,3, 7,5,4,3, \r
+ 7,5,5,3, 7,5,6,3, 7,5,7,3, 7,5,8,3, 7,5,9,3, 7,9,4,3, 7,9,5,3, 9,5,6,3, 9,5,7,3, \r
+ 7,9,8,3, 7,9,9,3, 7,6,0,3, 7,6,1,3, 7,6,2,3, 7,6,3,3, 7,6,4,3, 7,6,5,3, 7,6,6,3, \r
+ 7,6,7,3, 7,6,8,3, 7,6,9,3, 7,8,6,3, 7,8,7,3, 9,6,6,3, 9,6,7,3, 9,8,8,3, 9,8,9,3, \r
+ 7,7,0,3, 7,7,1,3, 7,7,2,3, 7,7,3,3, 7,7,4,3, 7,7,5,3, 7,7,6,3, 7,7,7,3, 7,7,8,3, \r
+ 7,7,9,3, 7,9,6,3, 7,9,7,3, 9,7,6,3, 9,7,7,3, 9,9,8,3, 9,9,9,3};\r
+#endif\r
\r
+#if defined(DEC_BIN2BCD8) && DEC_BIN2BCD8==1 && !defined(DECBIN2BCD8)\r
+#define DECBIN2BCD8\r
\r
+const uint8_t BIN2BCD8[4000]={\r
+ 0,0,0,0, 0,0,1,1, 0,0,2,1, 0,0,3,1, 0,0,4,1, 0,0,5,1, 0,0,6,1, 0,0,7,1, 0,0,8,1, \r
+ 0,0,9,1, 0,1,0,2, 0,1,1,2, 0,1,2,2, 0,1,3,2, 0,1,4,2, 0,1,5,2, 0,1,6,2, 0,1,7,2, \r
+ 0,1,8,2, 0,1,9,2, 0,2,0,2, 0,2,1,2, 0,2,2,2, 0,2,3,2, 0,2,4,2, 0,2,5,2, 0,2,6,2, \r
+ 0,2,7,2, 0,2,8,2, 0,2,9,2, 0,3,0,2, 0,3,1,2, 0,3,2,2, 0,3,3,2, 0,3,4,2, 0,3,5,2, \r
+ 0,3,6,2, 0,3,7,2, 0,3,8,2, 0,3,9,2, 0,4,0,2, 0,4,1,2, 0,4,2,2, 0,4,3,2, 0,4,4,2, \r
+ 0,4,5,2, 0,4,6,2, 0,4,7,2, 0,4,8,2, 0,4,9,2, 0,5,0,2, 0,5,1,2, 0,5,2,2, 0,5,3,2, \r
+ 0,5,4,2, 0,5,5,2, 0,5,6,2, 0,5,7,2, 0,5,8,2, 0,5,9,2, 0,6,0,2, 0,6,1,2, 0,6,2,2, \r
+ 0,6,3,2, 0,6,4,2, 0,6,5,2, 0,6,6,2, 0,6,7,2, 0,6,8,2, 0,6,9,2, 0,7,0,2, 0,7,1,2, \r
+ 0,7,2,2, 0,7,3,2, 0,7,4,2, 0,7,5,2, 0,7,6,2, 0,7,7,2, 0,7,8,2, 0,7,9,2, 0,8,0,2, \r
+ 0,8,1,2, 0,8,2,2, 0,8,3,2, 0,8,4,2, 0,8,5,2, 0,8,6,2, 0,8,7,2, 0,8,8,2, 0,8,9,2, \r
+ 0,9,0,2, 0,9,1,2, 0,9,2,2, 0,9,3,2, 0,9,4,2, 0,9,5,2, 0,9,6,2, 0,9,7,2, 0,9,8,2, \r
+ 0,9,9,2, 1,0,0,3, 1,0,1,3, 1,0,2,3, 1,0,3,3, 1,0,4,3, 1,0,5,3, 1,0,6,3, 1,0,7,3, \r
+ 1,0,8,3, 1,0,9,3, 1,1,0,3, 1,1,1,3, 1,1,2,3, 1,1,3,3, 1,1,4,3, 1,1,5,3, 1,1,6,3, \r
+ 1,1,7,3, 1,1,8,3, 1,1,9,3, 1,2,0,3, 1,2,1,3, 1,2,2,3, 1,2,3,3, 1,2,4,3, 1,2,5,3, \r
+ 1,2,6,3, 1,2,7,3, 1,2,8,3, 1,2,9,3, 1,3,0,3, 1,3,1,3, 1,3,2,3, 1,3,3,3, 1,3,4,3, \r
+ 1,3,5,3, 1,3,6,3, 1,3,7,3, 1,3,8,3, 1,3,9,3, 1,4,0,3, 1,4,1,3, 1,4,2,3, 1,4,3,3, \r
+ 1,4,4,3, 1,4,5,3, 1,4,6,3, 1,4,7,3, 1,4,8,3, 1,4,9,3, 1,5,0,3, 1,5,1,3, 1,5,2,3, \r
+ 1,5,3,3, 1,5,4,3, 1,5,5,3, 1,5,6,3, 1,5,7,3, 1,5,8,3, 1,5,9,3, 1,6,0,3, 1,6,1,3, \r
+ 1,6,2,3, 1,6,3,3, 1,6,4,3, 1,6,5,3, 1,6,6,3, 1,6,7,3, 1,6,8,3, 1,6,9,3, 1,7,0,3, \r
+ 1,7,1,3, 1,7,2,3, 1,7,3,3, 1,7,4,3, 1,7,5,3, 1,7,6,3, 1,7,7,3, 1,7,8,3, 1,7,9,3, \r
+ 1,8,0,3, 1,8,1,3, 1,8,2,3, 1,8,3,3, 1,8,4,3, 1,8,5,3, 1,8,6,3, 1,8,7,3, 1,8,8,3, \r
+ 1,8,9,3, 1,9,0,3, 1,9,1,3, 1,9,2,3, 1,9,3,3, 1,9,4,3, 1,9,5,3, 1,9,6,3, 1,9,7,3, \r
+ 1,9,8,3, 1,9,9,3, 2,0,0,3, 2,0,1,3, 2,0,2,3, 2,0,3,3, 2,0,4,3, 2,0,5,3, 2,0,6,3, \r
+ 2,0,7,3, 2,0,8,3, 2,0,9,3, 2,1,0,3, 2,1,1,3, 2,1,2,3, 2,1,3,3, 2,1,4,3, 2,1,5,3, \r
+ 2,1,6,3, 2,1,7,3, 2,1,8,3, 2,1,9,3, 2,2,0,3, 2,2,1,3, 2,2,2,3, 2,2,3,3, 2,2,4,3, \r
+ 2,2,5,3, 2,2,6,3, 2,2,7,3, 2,2,8,3, 2,2,9,3, 2,3,0,3, 2,3,1,3, 2,3,2,3, 2,3,3,3, \r
+ 2,3,4,3, 2,3,5,3, 2,3,6,3, 2,3,7,3, 2,3,8,3, 2,3,9,3, 2,4,0,3, 2,4,1,3, 2,4,2,3, \r
+ 2,4,3,3, 2,4,4,3, 2,4,5,3, 2,4,6,3, 2,4,7,3, 2,4,8,3, 2,4,9,3, 2,5,0,3, 2,5,1,3, \r
+ 2,5,2,3, 2,5,3,3, 2,5,4,3, 2,5,5,3, 2,5,6,3, 2,5,7,3, 2,5,8,3, 2,5,9,3, 2,6,0,3, \r
+ 2,6,1,3, 2,6,2,3, 2,6,3,3, 2,6,4,3, 2,6,5,3, 2,6,6,3, 2,6,7,3, 2,6,8,3, 2,6,9,3, \r
+ 2,7,0,3, 2,7,1,3, 2,7,2,3, 2,7,3,3, 2,7,4,3, 2,7,5,3, 2,7,6,3, 2,7,7,3, 2,7,8,3, \r
+ 2,7,9,3, 2,8,0,3, 2,8,1,3, 2,8,2,3, 2,8,3,3, 2,8,4,3, 2,8,5,3, 2,8,6,3, 2,8,7,3, \r
+ 2,8,8,3, 2,8,9,3, 2,9,0,3, 2,9,1,3, 2,9,2,3, 2,9,3,3, 2,9,4,3, 2,9,5,3, 2,9,6,3, \r
+ 2,9,7,3, 2,9,8,3, 2,9,9,3, 3,0,0,3, 3,0,1,3, 3,0,2,3, 3,0,3,3, 3,0,4,3, 3,0,5,3, \r
+ 3,0,6,3, 3,0,7,3, 3,0,8,3, 3,0,9,3, 3,1,0,3, 3,1,1,3, 3,1,2,3, 3,1,3,3, 3,1,4,3, \r
+ 3,1,5,3, 3,1,6,3, 3,1,7,3, 3,1,8,3, 3,1,9,3, 3,2,0,3, 3,2,1,3, 3,2,2,3, 3,2,3,3, \r
+ 3,2,4,3, 3,2,5,3, 3,2,6,3, 3,2,7,3, 3,2,8,3, 3,2,9,3, 3,3,0,3, 3,3,1,3, 3,3,2,3, \r
+ 3,3,3,3, 3,3,4,3, 3,3,5,3, 3,3,6,3, 3,3,7,3, 3,3,8,3, 3,3,9,3, 3,4,0,3, 3,4,1,3, \r
+ 3,4,2,3, 3,4,3,3, 3,4,4,3, 3,4,5,3, 3,4,6,3, 3,4,7,3, 3,4,8,3, 3,4,9,3, 3,5,0,3, \r
+ 3,5,1,3, 3,5,2,3, 3,5,3,3, 3,5,4,3, 3,5,5,3, 3,5,6,3, 3,5,7,3, 3,5,8,3, 3,5,9,3, \r
+ 3,6,0,3, 3,6,1,3, 3,6,2,3, 3,6,3,3, 3,6,4,3, 3,6,5,3, 3,6,6,3, 3,6,7,3, 3,6,8,3, \r
+ 3,6,9,3, 3,7,0,3, 3,7,1,3, 3,7,2,3, 3,7,3,3, 3,7,4,3, 3,7,5,3, 3,7,6,3, 3,7,7,3, \r
+ 3,7,8,3, 3,7,9,3, 3,8,0,3, 3,8,1,3, 3,8,2,3, 3,8,3,3, 3,8,4,3, 3,8,5,3, 3,8,6,3, \r
+ 3,8,7,3, 3,8,8,3, 3,8,9,3, 3,9,0,3, 3,9,1,3, 3,9,2,3, 3,9,3,3, 3,9,4,3, 3,9,5,3, \r
+ 3,9,6,3, 3,9,7,3, 3,9,8,3, 3,9,9,3, 4,0,0,3, 4,0,1,3, 4,0,2,3, 4,0,3,3, 4,0,4,3, \r
+ 4,0,5,3, 4,0,6,3, 4,0,7,3, 4,0,8,3, 4,0,9,3, 4,1,0,3, 4,1,1,3, 4,1,2,3, 4,1,3,3, \r
+ 4,1,4,3, 4,1,5,3, 4,1,6,3, 4,1,7,3, 4,1,8,3, 4,1,9,3, 4,2,0,3, 4,2,1,3, 4,2,2,3, \r
+ 4,2,3,3, 4,2,4,3, 4,2,5,3, 4,2,6,3, 4,2,7,3, 4,2,8,3, 4,2,9,3, 4,3,0,3, 4,3,1,3, \r
+ 4,3,2,3, 4,3,3,3, 4,3,4,3, 4,3,5,3, 4,3,6,3, 4,3,7,3, 4,3,8,3, 4,3,9,3, 4,4,0,3, \r
+ 4,4,1,3, 4,4,2,3, 4,4,3,3, 4,4,4,3, 4,4,5,3, 4,4,6,3, 4,4,7,3, 4,4,8,3, 4,4,9,3, \r
+ 4,5,0,3, 4,5,1,3, 4,5,2,3, 4,5,3,3, 4,5,4,3, 4,5,5,3, 4,5,6,3, 4,5,7,3, 4,5,8,3, \r
+ 4,5,9,3, 4,6,0,3, 4,6,1,3, 4,6,2,3, 4,6,3,3, 4,6,4,3, 4,6,5,3, 4,6,6,3, 4,6,7,3, \r
+ 4,6,8,3, 4,6,9,3, 4,7,0,3, 4,7,1,3, 4,7,2,3, 4,7,3,3, 4,7,4,3, 4,7,5,3, 4,7,6,3, \r
+ 4,7,7,3, 4,7,8,3, 4,7,9,3, 4,8,0,3, 4,8,1,3, 4,8,2,3, 4,8,3,3, 4,8,4,3, 4,8,5,3, \r
+ 4,8,6,3, 4,8,7,3, 4,8,8,3, 4,8,9,3, 4,9,0,3, 4,9,1,3, 4,9,2,3, 4,9,3,3, 4,9,4,3, \r
+ 4,9,5,3, 4,9,6,3, 4,9,7,3, 4,9,8,3, 4,9,9,3, 5,0,0,3, 5,0,1,3, 5,0,2,3, 5,0,3,3, \r
+ 5,0,4,3, 5,0,5,3, 5,0,6,3, 5,0,7,3, 5,0,8,3, 5,0,9,3, 5,1,0,3, 5,1,1,3, 5,1,2,3, \r
+ 5,1,3,3, 5,1,4,3, 5,1,5,3, 5,1,6,3, 5,1,7,3, 5,1,8,3, 5,1,9,3, 5,2,0,3, 5,2,1,3, \r
+ 5,2,2,3, 5,2,3,3, 5,2,4,3, 5,2,5,3, 5,2,6,3, 5,2,7,3, 5,2,8,3, 5,2,9,3, 5,3,0,3, \r
+ 5,3,1,3, 5,3,2,3, 5,3,3,3, 5,3,4,3, 5,3,5,3, 5,3,6,3, 5,3,7,3, 5,3,8,3, 5,3,9,3, \r
+ 5,4,0,3, 5,4,1,3, 5,4,2,3, 5,4,3,3, 5,4,4,3, 5,4,5,3, 5,4,6,3, 5,4,7,3, 5,4,8,3, \r
+ 5,4,9,3, 5,5,0,3, 5,5,1,3, 5,5,2,3, 5,5,3,3, 5,5,4,3, 5,5,5,3, 5,5,6,3, 5,5,7,3, \r
+ 5,5,8,3, 5,5,9,3, 5,6,0,3, 5,6,1,3, 5,6,2,3, 5,6,3,3, 5,6,4,3, 5,6,5,3, 5,6,6,3, \r
+ 5,6,7,3, 5,6,8,3, 5,6,9,3, 5,7,0,3, 5,7,1,3, 5,7,2,3, 5,7,3,3, 5,7,4,3, 5,7,5,3, \r
+ 5,7,6,3, 5,7,7,3, 5,7,8,3, 5,7,9,3, 5,8,0,3, 5,8,1,3, 5,8,2,3, 5,8,3,3, 5,8,4,3, \r
+ 5,8,5,3, 5,8,6,3, 5,8,7,3, 5,8,8,3, 5,8,9,3, 5,9,0,3, 5,9,1,3, 5,9,2,3, 5,9,3,3, \r
+ 5,9,4,3, 5,9,5,3, 5,9,6,3, 5,9,7,3, 5,9,8,3, 5,9,9,3, 6,0,0,3, 6,0,1,3, 6,0,2,3, \r
+ 6,0,3,3, 6,0,4,3, 6,0,5,3, 6,0,6,3, 6,0,7,3, 6,0,8,3, 6,0,9,3, 6,1,0,3, 6,1,1,3, \r
+ 6,1,2,3, 6,1,3,3, 6,1,4,3, 6,1,5,3, 6,1,6,3, 6,1,7,3, 6,1,8,3, 6,1,9,3, 6,2,0,3, \r
+ 6,2,1,3, 6,2,2,3, 6,2,3,3, 6,2,4,3, 6,2,5,3, 6,2,6,3, 6,2,7,3, 6,2,8,3, 6,2,9,3, \r
+ 6,3,0,3, 6,3,1,3, 6,3,2,3, 6,3,3,3, 6,3,4,3, 6,3,5,3, 6,3,6,3, 6,3,7,3, 6,3,8,3, \r
+ 6,3,9,3, 6,4,0,3, 6,4,1,3, 6,4,2,3, 6,4,3,3, 6,4,4,3, 6,4,5,3, 6,4,6,3, 6,4,7,3, \r
+ 6,4,8,3, 6,4,9,3, 6,5,0,3, 6,5,1,3, 6,5,2,3, 6,5,3,3, 6,5,4,3, 6,5,5,3, 6,5,6,3, \r
+ 6,5,7,3, 6,5,8,3, 6,5,9,3, 6,6,0,3, 6,6,1,3, 6,6,2,3, 6,6,3,3, 6,6,4,3, 6,6,5,3, \r
+ 6,6,6,3, 6,6,7,3, 6,6,8,3, 6,6,9,3, 6,7,0,3, 6,7,1,3, 6,7,2,3, 6,7,3,3, 6,7,4,3, \r
+ 6,7,5,3, 6,7,6,3, 6,7,7,3, 6,7,8,3, 6,7,9,3, 6,8,0,3, 6,8,1,3, 6,8,2,3, 6,8,3,3, \r
+ 6,8,4,3, 6,8,5,3, 6,8,6,3, 6,8,7,3, 6,8,8,3, 6,8,9,3, 6,9,0,3, 6,9,1,3, 6,9,2,3, \r
+ 6,9,3,3, 6,9,4,3, 6,9,5,3, 6,9,6,3, 6,9,7,3, 6,9,8,3, 6,9,9,3, 7,0,0,3, 7,0,1,3, \r
+ 7,0,2,3, 7,0,3,3, 7,0,4,3, 7,0,5,3, 7,0,6,3, 7,0,7,3, 7,0,8,3, 7,0,9,3, 7,1,0,3, \r
+ 7,1,1,3, 7,1,2,3, 7,1,3,3, 7,1,4,3, 7,1,5,3, 7,1,6,3, 7,1,7,3, 7,1,8,3, 7,1,9,3, \r
+ 7,2,0,3, 7,2,1,3, 7,2,2,3, 7,2,3,3, 7,2,4,3, 7,2,5,3, 7,2,6,3, 7,2,7,3, 7,2,8,3, \r
+ 7,2,9,3, 7,3,0,3, 7,3,1,3, 7,3,2,3, 7,3,3,3, 7,3,4,3, 7,3,5,3, 7,3,6,3, 7,3,7,3, \r
+ 7,3,8,3, 7,3,9,3, 7,4,0,3, 7,4,1,3, 7,4,2,3, 7,4,3,3, 7,4,4,3, 7,4,5,3, 7,4,6,3, \r
+ 7,4,7,3, 7,4,8,3, 7,4,9,3, 7,5,0,3, 7,5,1,3, 7,5,2,3, 7,5,3,3, 7,5,4,3, 7,5,5,3, \r
+ 7,5,6,3, 7,5,7,3, 7,5,8,3, 7,5,9,3, 7,6,0,3, 7,6,1,3, 7,6,2,3, 7,6,3,3, 7,6,4,3, \r
+ 7,6,5,3, 7,6,6,3, 7,6,7,3, 7,6,8,3, 7,6,9,3, 7,7,0,3, 7,7,1,3, 7,7,2,3, 7,7,3,3, \r
+ 7,7,4,3, 7,7,5,3, 7,7,6,3, 7,7,7,3, 7,7,8,3, 7,7,9,3, 7,8,0,3, 7,8,1,3, 7,8,2,3, \r
+ 7,8,3,3, 7,8,4,3, 7,8,5,3, 7,8,6,3, 7,8,7,3, 7,8,8,3, 7,8,9,3, 7,9,0,3, 7,9,1,3, \r
+ 7,9,2,3, 7,9,3,3, 7,9,4,3, 7,9,5,3, 7,9,6,3, 7,9,7,3, 7,9,8,3, 7,9,9,3, 8,0,0,3, \r
+ 8,0,1,3, 8,0,2,3, 8,0,3,3, 8,0,4,3, 8,0,5,3, 8,0,6,3, 8,0,7,3, 8,0,8,3, 8,0,9,3, \r
+ 8,1,0,3, 8,1,1,3, 8,1,2,3, 8,1,3,3, 8,1,4,3, 8,1,5,3, 8,1,6,3, 8,1,7,3, 8,1,8,3, \r
+ 8,1,9,3, 8,2,0,3, 8,2,1,3, 8,2,2,3, 8,2,3,3, 8,2,4,3, 8,2,5,3, 8,2,6,3, 8,2,7,3, \r
+ 8,2,8,3, 8,2,9,3, 8,3,0,3, 8,3,1,3, 8,3,2,3, 8,3,3,3, 8,3,4,3, 8,3,5,3, 8,3,6,3, \r
+ 8,3,7,3, 8,3,8,3, 8,3,9,3, 8,4,0,3, 8,4,1,3, 8,4,2,3, 8,4,3,3, 8,4,4,3, 8,4,5,3, \r
+ 8,4,6,3, 8,4,7,3, 8,4,8,3, 8,4,9,3, 8,5,0,3, 8,5,1,3, 8,5,2,3, 8,5,3,3, 8,5,4,3, \r
+ 8,5,5,3, 8,5,6,3, 8,5,7,3, 8,5,8,3, 8,5,9,3, 8,6,0,3, 8,6,1,3, 8,6,2,3, 8,6,3,3, \r
+ 8,6,4,3, 8,6,5,3, 8,6,6,3, 8,6,7,3, 8,6,8,3, 8,6,9,3, 8,7,0,3, 8,7,1,3, 8,7,2,3, \r
+ 8,7,3,3, 8,7,4,3, 8,7,5,3, 8,7,6,3, 8,7,7,3, 8,7,8,3, 8,7,9,3, 8,8,0,3, 8,8,1,3, \r
+ 8,8,2,3, 8,8,3,3, 8,8,4,3, 8,8,5,3, 8,8,6,3, 8,8,7,3, 8,8,8,3, 8,8,9,3, 8,9,0,3, \r
+ 8,9,1,3, 8,9,2,3, 8,9,3,3, 8,9,4,3, 8,9,5,3, 8,9,6,3, 8,9,7,3, 8,9,8,3, 8,9,9,3, \r
+ 9,0,0,3, 9,0,1,3, 9,0,2,3, 9,0,3,3, 9,0,4,3, 9,0,5,3, 9,0,6,3, 9,0,7,3, 9,0,8,3, \r
+ 9,0,9,3, 9,1,0,3, 9,1,1,3, 9,1,2,3, 9,1,3,3, 9,1,4,3, 9,1,5,3, 9,1,6,3, 9,1,7,3, \r
+ 9,1,8,3, 9,1,9,3, 9,2,0,3, 9,2,1,3, 9,2,2,3, 9,2,3,3, 9,2,4,3, 9,2,5,3, 9,2,6,3, \r
+ 9,2,7,3, 9,2,8,3, 9,2,9,3, 9,3,0,3, 9,3,1,3, 9,3,2,3, 9,3,3,3, 9,3,4,3, 9,3,5,3, \r
+ 9,3,6,3, 9,3,7,3, 9,3,8,3, 9,3,9,3, 9,4,0,3, 9,4,1,3, 9,4,2,3, 9,4,3,3, 9,4,4,3, \r
+ 9,4,5,3, 9,4,6,3, 9,4,7,3, 9,4,8,3, 9,4,9,3, 9,5,0,3, 9,5,1,3, 9,5,2,3, 9,5,3,3, \r
+ 9,5,4,3, 9,5,5,3, 9,5,6,3, 9,5,7,3, 9,5,8,3, 9,5,9,3, 9,6,0,3, 9,6,1,3, 9,6,2,3, \r
+ 9,6,3,3, 9,6,4,3, 9,6,5,3, 9,6,6,3, 9,6,7,3, 9,6,8,3, 9,6,9,3, 9,7,0,3, 9,7,1,3, \r
+ 9,7,2,3, 9,7,3,3, 9,7,4,3, 9,7,5,3, 9,7,6,3, 9,7,7,3, 9,7,8,3, 9,7,9,3, 9,8,0,3, \r
+ 9,8,1,3, 9,8,2,3, 9,8,3,3, 9,8,4,3, 9,8,5,3, 9,8,6,3, 9,8,7,3, 9,8,8,3, 9,8,9,3, \r
+ 9,9,0,3, 9,9,1,3, 9,9,2,3, 9,9,3,3, 9,9,4,3, 9,9,5,3, 9,9,6,3, 9,9,7,3, 9,9,8,3, \r
+ 9,9,9,3};\r
+#endif\r
\r
diff --git a/src/decNumber/decDouble.c b/src/decNumber/decDouble.c
new file mode 100644 (file)
index 0000000..4f5df53
--- /dev/null
@@ -0,0 +1,140 @@
+/* ------------------------------------------------------------------ */\r
+/* decDouble.c -- decDouble operations module                         */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2010.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is included in the package as decNumber.pdf.  This   */\r
+/* document is also available in HTML, together with specifications,  */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises decDouble operations (including conversions) */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#include "decContext.h"       // public includes\r
+#include "decDouble.h"        // ..\r
+\r
+/* Constant mappings for shared code */\r
+#define DECPMAX     DECDOUBLE_Pmax\r
+#define DECEMIN     DECDOUBLE_Emin\r
+#define DECEMAX     DECDOUBLE_Emax\r
+#define DECEMAXD    DECDOUBLE_EmaxD\r
+#define DECBYTES    DECDOUBLE_Bytes\r
+#define DECSTRING   DECDOUBLE_String\r
+#define DECECONL    DECDOUBLE_EconL\r
+#define DECBIAS     DECDOUBLE_Bias\r
+#define DECLETS     DECDOUBLE_Declets\r
+#define DECQTINY    (-DECDOUBLE_Bias)\r
+// parameters of next-wider format\r
+#define DECWBYTES   DECQUAD_Bytes\r
+#define DECWPMAX    DECQUAD_Pmax\r
+#define DECWECONL   DECQUAD_EconL\r
+#define DECWBIAS    DECQUAD_Bias\r
+\r
+/* Type and function mappings for shared code */\r
+#define decFloat                   decDouble      // Type name\r
+#define decFloatWider              decQuad        // Type name\r
+\r
+// Utilities and conversions (binary results, extractors, etc.)\r
+#define decFloatFromBCD            decDoubleFromBCD\r
+#define decFloatFromInt32          decDoubleFromInt32\r
+#define decFloatFromPacked         decDoubleFromPacked\r
+#define decFloatFromPackedChecked  decDoubleFromPackedChecked\r
+#define decFloatFromString         decDoubleFromString\r
+#define decFloatFromUInt32         decDoubleFromUInt32\r
+#define decFloatFromWider          decDoubleFromWider\r
+#define decFloatGetCoefficient     decDoubleGetCoefficient\r
+#define decFloatGetExponent        decDoubleGetExponent\r
+#define decFloatSetCoefficient     decDoubleSetCoefficient\r
+#define decFloatSetExponent        decDoubleSetExponent\r
+#define decFloatShow               decDoubleShow\r
+#define decFloatToBCD              decDoubleToBCD\r
+#define decFloatToEngString        decDoubleToEngString\r
+#define decFloatToInt32            decDoubleToInt32\r
+#define decFloatToInt32Exact       decDoubleToInt32Exact\r
+#define decFloatToPacked           decDoubleToPacked\r
+#define decFloatToString           decDoubleToString\r
+#define decFloatToUInt32           decDoubleToUInt32\r
+#define decFloatToUInt32Exact      decDoubleToUInt32Exact\r
+#define decFloatToWider            decDoubleToWider\r
+#define decFloatZero               decDoubleZero\r
+\r
+// Computational (result is a decFloat)\r
+#define decFloatAbs                decDoubleAbs\r
+#define decFloatAdd                decDoubleAdd\r
+#define decFloatAnd                decDoubleAnd\r
+#define decFloatDivide             decDoubleDivide\r
+#define decFloatDivideInteger      decDoubleDivideInteger\r
+#define decFloatFMA                decDoubleFMA\r
+#define decFloatInvert             decDoubleInvert\r
+#define decFloatLogB               decDoubleLogB\r
+#define decFloatMax                decDoubleMax\r
+#define decFloatMaxMag             decDoubleMaxMag\r
+#define decFloatMin                decDoubleMin\r
+#define decFloatMinMag             decDoubleMinMag\r
+#define decFloatMinus              decDoubleMinus\r
+#define decFloatMultiply           decDoubleMultiply\r
+#define decFloatNextMinus          decDoubleNextMinus\r
+#define decFloatNextPlus           decDoubleNextPlus\r
+#define decFloatNextToward         decDoubleNextToward\r
+#define decFloatOr                 decDoubleOr\r
+#define decFloatPlus               decDoublePlus\r
+#define decFloatQuantize           decDoubleQuantize\r
+#define decFloatReduce             decDoubleReduce\r
+#define decFloatRemainder          decDoubleRemainder\r
+#define decFloatRemainderNear      decDoubleRemainderNear\r
+#define decFloatRotate             decDoubleRotate\r
+#define decFloatScaleB             decDoubleScaleB\r
+#define decFloatShift              decDoubleShift\r
+#define decFloatSubtract           decDoubleSubtract\r
+#define decFloatToIntegralValue    decDoubleToIntegralValue\r
+#define decFloatToIntegralExact    decDoubleToIntegralExact\r
+#define decFloatXor                decDoubleXor\r
+\r
+// Comparisons\r
+#define decFloatCompare            decDoubleCompare\r
+#define decFloatCompareSignal      decDoubleCompareSignal\r
+#define decFloatCompareTotal       decDoubleCompareTotal\r
+#define decFloatCompareTotalMag    decDoubleCompareTotalMag\r
+\r
+// Copies\r
+#define decFloatCanonical          decDoubleCanonical\r
+#define decFloatCopy               decDoubleCopy\r
+#define decFloatCopyAbs            decDoubleCopyAbs\r
+#define decFloatCopyNegate         decDoubleCopyNegate\r
+#define decFloatCopySign           decDoubleCopySign\r
+\r
+// Non-computational\r
+#define decFloatClass              decDoubleClass\r
+#define decFloatClassString        decDoubleClassString\r
+#define decFloatDigits             decDoubleDigits\r
+#define decFloatIsCanonical        decDoubleIsCanonical\r
+#define decFloatIsFinite           decDoubleIsFinite\r
+#define decFloatIsInfinite         decDoubleIsInfinite\r
+#define decFloatIsInteger          decDoubleIsInteger\r
+#define decFloatIsLogical          decDoubleIsLogical\r
+#define decFloatIsNaN              decDoubleIsNaN\r
+#define decFloatIsNegative         decDoubleIsNegative\r
+#define decFloatIsNormal           decDoubleIsNormal\r
+#define decFloatIsPositive         decDoubleIsPositive\r
+#define decFloatIsSignaling        decDoubleIsSignaling\r
+#define decFloatIsSignalling       decDoubleIsSignalling\r
+#define decFloatIsSigned           decDoubleIsSigned\r
+#define decFloatIsSubnormal        decDoubleIsSubnormal\r
+#define decFloatIsZero             decDoubleIsZero\r
+#define decFloatRadix              decDoubleRadix\r
+#define decFloatSameQuantum        decDoubleSameQuantum\r
+#define decFloatVersion            decDoubleVersion\r
+\r
+#include "decNumberLocal.h"   // local includes (need DECPMAX)\r
+#include "decCommon.c"        // non-arithmetic decFloat routines\r
+#include "decBasic.c"         // basic formats routines\r
+\r
diff --git a/src/decNumber/decDouble.h b/src/decNumber/decDouble.h
new file mode 100644 (file)
index 0000000..fe9c26d
--- /dev/null
@@ -0,0 +1,155 @@
+/* ------------------------------------------------------------------ */\r
+/* decDouble.h -- Decimal 64-bit format module header                 */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2010.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is included in the package as decNumber.pdf.  This   */\r
+/* document is also available in HTML, together with specifications,  */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#if !defined(DECDOUBLE)\r
+  #define DECDOUBLE\r
+\r
+  #define DECDOUBLENAME       "decimalDouble"         /* Short name   */\r
+  #define DECDOUBLETITLE      "Decimal 64-bit datum"  /* Verbose name */\r
+  #define DECDOUBLEAUTHOR     "Mike Cowlishaw"        /* Who to blame */\r
+\r
+  /* parameters for decDoubles */\r
+  #define DECDOUBLE_Bytes   8      /* length                          */\r
+  #define DECDOUBLE_Pmax    16     /* maximum precision (digits)      */\r
+  #define DECDOUBLE_Emin   -383    /* minimum adjusted exponent       */\r
+  #define DECDOUBLE_Emax    384    /* maximum adjusted exponent       */\r
+  #define DECDOUBLE_EmaxD   3      /* maximum exponent digits         */\r
+  #define DECDOUBLE_Bias    398    /* bias for the exponent           */\r
+  #define DECDOUBLE_String  25     /* maximum string length, +1       */\r
+  #define DECDOUBLE_EconL   8      /* exponent continuation length    */\r
+  #define DECDOUBLE_Declets 5      /* count of declets                */\r
+  /* highest biased exponent (Elimit-1) */\r
+  #define DECDOUBLE_Ehigh (DECDOUBLE_Emax + DECDOUBLE_Bias - (DECDOUBLE_Pmax-1))\r
+\r
+  /* Required includes                                                */\r
+  #include "decContext.h"\r
+  #include "decQuad.h"\r
+\r
+  /* The decDouble decimal 64-bit type, accessible by all sizes */\r
+  typedef union {\r
+    uint8_t   bytes[DECDOUBLE_Bytes];   /* fields: 1, 5, 8, 50 bits */\r
+    uint16_t shorts[DECDOUBLE_Bytes/2];\r
+    uint32_t  words[DECDOUBLE_Bytes/4];\r
+    #if DECUSE64\r
+    uint64_t  longs[DECDOUBLE_Bytes/8];\r
+    #endif\r
+    } decDouble;\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Routines -- implemented as decFloat routines in common files     */\r
+  /* ---------------------------------------------------------------- */\r
+\r
+  /* Utilities and conversions, extractors, etc.) */\r
+  extern decDouble * decDoubleFromBCD(decDouble *, int32_t, const uint8_t *, int32_t);\r
+  extern decDouble * decDoubleFromInt32(decDouble *, int32_t);\r
+  extern decDouble * decDoubleFromPacked(decDouble *, int32_t, const uint8_t *);\r
+  extern decDouble * decDoubleFromPackedChecked(decDouble *, int32_t, const uint8_t *);\r
+  extern decDouble * decDoubleFromString(decDouble *, const char *, decContext *);\r
+  extern decDouble * decDoubleFromUInt32(decDouble *, uint32_t);\r
+  extern decDouble * decDoubleFromWider(decDouble *, const decQuad *, decContext *);\r
+  extern int32_t     decDoubleGetCoefficient(const decDouble *, uint8_t *);\r
+  extern int32_t     decDoubleGetExponent(const decDouble *);\r
+  extern decDouble * decDoubleSetCoefficient(decDouble *, const uint8_t *, int32_t);\r
+  extern decDouble * decDoubleSetExponent(decDouble *, decContext *, int32_t);\r
+  extern void        decDoubleShow(const decDouble *, const char *);\r
+  extern int32_t     decDoubleToBCD(const decDouble *, int32_t *, uint8_t *);\r
+  extern char      * decDoubleToEngString(const decDouble *, char *);\r
+  extern int32_t     decDoubleToInt32(const decDouble *, decContext *, enum rounding);\r
+  extern int32_t     decDoubleToInt32Exact(const decDouble *, decContext *, enum rounding);\r
+  extern int32_t     decDoubleToPacked(const decDouble *, int32_t *, uint8_t *);\r
+  extern char      * decDoubleToString(const decDouble *, char *);\r
+  extern uint32_t    decDoubleToUInt32(const decDouble *, decContext *, enum rounding);\r
+  extern uint32_t    decDoubleToUInt32Exact(const decDouble *, decContext *, enum rounding);\r
+  extern decQuad   * decDoubleToWider(const decDouble *, decQuad *);\r
+  extern decDouble * decDoubleZero(decDouble *);\r
+\r
+  /* Computational (result is a decDouble) */\r
+  extern decDouble * decDoubleAbs(decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleAdd(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleAnd(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleDivide(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleDivideInteger(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleFMA(decDouble *, const decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleInvert(decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleLogB(decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleMax(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleMaxMag(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleMin(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleMinMag(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleMinus(decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleMultiply(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleNextMinus(decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleNextPlus(decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleNextToward(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleOr(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoublePlus(decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleQuantize(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleReduce(decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleRemainder(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleRemainderNear(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleRotate(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleScaleB(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleShift(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleSubtract(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleToIntegralValue(decDouble *, const decDouble *, decContext *, enum rounding);\r
+  extern decDouble * decDoubleToIntegralExact(decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleXor(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+\r
+  /* Comparisons */\r
+  extern decDouble * decDoubleCompare(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleCompareSignal(decDouble *, const decDouble *, const decDouble *, decContext *);\r
+  extern decDouble * decDoubleCompareTotal(decDouble *, const decDouble *, const decDouble *);\r
+  extern decDouble * decDoubleCompareTotalMag(decDouble *, const decDouble *, const decDouble *);\r
+\r
+  /* Copies */\r
+  extern decDouble * decDoubleCanonical(decDouble *, const decDouble *);\r
+  extern decDouble * decDoubleCopy(decDouble *, const decDouble *);\r
+  extern decDouble * decDoubleCopyAbs(decDouble *, const decDouble *);\r
+  extern decDouble * decDoubleCopyNegate(decDouble *, const decDouble *);\r
+  extern decDouble * decDoubleCopySign(decDouble *, const decDouble *, const decDouble *);\r
+\r
+  /* Non-computational */\r
+  extern enum decClass decDoubleClass(const decDouble *);\r
+  extern const char *  decDoubleClassString(const decDouble *);\r
+  extern uint32_t      decDoubleDigits(const decDouble *);\r
+  extern uint32_t      decDoubleIsCanonical(const decDouble *);\r
+  extern uint32_t      decDoubleIsFinite(const decDouble *);\r
+  extern uint32_t      decDoubleIsInfinite(const decDouble *);\r
+  extern uint32_t      decDoubleIsInteger(const decDouble *);\r
+  extern uint32_t      decDoubleIsLogical(const decDouble *);\r
+  extern uint32_t      decDoubleIsNaN(const decDouble *);\r
+  extern uint32_t      decDoubleIsNegative(const decDouble *);\r
+  extern uint32_t      decDoubleIsNormal(const decDouble *);\r
+  extern uint32_t      decDoubleIsPositive(const decDouble *);\r
+  extern uint32_t      decDoubleIsSignaling(const decDouble *);\r
+  extern uint32_t      decDoubleIsSignalling(const decDouble *);\r
+  extern uint32_t      decDoubleIsSigned(const decDouble *);\r
+  extern uint32_t      decDoubleIsSubnormal(const decDouble *);\r
+  extern uint32_t      decDoubleIsZero(const decDouble *);\r
+  extern uint32_t      decDoubleRadix(const decDouble *);\r
+  extern uint32_t      decDoubleSameQuantum(const decDouble *, const decDouble *);\r
+  extern const char *  decDoubleVersion(void);\r
+\r
+  /* decNumber conversions; these are implemented as macros so as not  */\r
+  /* to force a dependency on decimal64 and decNumber in decDouble.    */\r
+  /* decDoubleFromNumber returns a decimal64 * to avoid warnings.      */\r
+  #define decDoubleToNumber(dq, dn) decimal64ToNumber((decimal64 *)(dq), dn)\r
+  #define decDoubleFromNumber(dq, dn, set) decimal64FromNumber((decimal64 *)(dq), dn, set)\r
+\r
+#endif\r
diff --git a/src/decNumber/decNumber.c b/src/decNumber/decNumber.c
new file mode 100644 (file)
index 0000000..19230b8
--- /dev/null
@@ -0,0 +1,8141 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number arithmetic module                                   */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2009.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises the routines for arbitrary-precision General */\r
+/* Decimal Arithmetic as defined in the specification which may be    */\r
+/* found on the General Decimal Arithmetic pages.  It implements both */\r
+/* the full ('extended') arithmetic and the simpler ('subset')        */\r
+/* arithmetic.                                                        */\r
+/*                                                                    */\r
+/* Usage notes:                                                       */\r
+/*                                                                    */\r
+/* 1. This code is ANSI C89 except:                                   */\r
+/*                                                                    */\r
+/*    a) C99 line comments (double forward slash) are used.  (Most C  */\r
+/*       compilers accept these.  If yours does not, a simple script  */\r
+/*       can be used to convert them to ANSI C comments.)             */\r
+/*                                                                    */\r
+/*    b) Types from C99 stdint.h are used.  If you do not have this   */\r
+/*       header file, see the User's Guide section of the decNumber   */\r
+/*       documentation; this lists the necessary definitions.         */\r
+/*                                                                    */\r
+/*    c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and       */\r
+/*       uint64_t types may be used.  To avoid these, set DECUSE64=0  */\r
+/*       and DECDPUN<=4 (see documentation).                          */\r
+/*                                                                    */\r
+/*    The code also conforms to C99 restrictions; in particular,      */\r
+/*    strict aliasing rules are observed.                             */\r
+/*                                                                    */\r
+/* 2. The decNumber format which this library uses is optimized for   */\r
+/*    efficient processing of relatively short numbers; in particular */\r
+/*    it allows the use of fixed sized structures and minimizes copy  */\r
+/*    and move operations.  It does, however, support arbitrary       */\r
+/*    precision (up to 999,999,999 digits) and arbitrary exponent     */\r
+/*    range (Emax in the range 0 through 999,999,999 and Emin in the  */\r
+/*    range -999,999,999 through 0).  Mathematical functions (for     */\r
+/*    example decNumberExp) as identified below are restricted more   */\r
+/*    tightly: digits, emax, and -emin in the context must be <=      */\r
+/*    DEC_MAX_MATH (999999), and their operand(s) must be within      */\r
+/*    these bounds.                                                   */\r
+/*                                                                    */\r
+/* 3. Logical functions are further restricted; their operands must   */\r
+/*    be finite, positive, have an exponent of zero, and all digits   */\r
+/*    must be either 0 or 1.  The result will only contain digits     */\r
+/*    which are 0 or 1 (and will have exponent=0 and a sign of 0).    */\r
+/*                                                                    */\r
+/* 4. Operands to operator functions are never modified unless they   */\r
+/*    are also specified to be the result number (which is always     */\r
+/*    permitted).  Other than that case, operands must not overlap.   */\r
+/*                                                                    */\r
+/* 5. Error handling: the type of the error is ORed into the status   */\r
+/*    flags in the current context (decContext structure).  The       */\r
+/*    SIGFPE signal is then raised if the corresponding trap-enabler  */\r
+/*    flag in the decContext is set (is 1).                           */\r
+/*                                                                    */\r
+/*    It is the responsibility of the caller to clear the status      */\r
+/*    flags as required.                                              */\r
+/*                                                                    */\r
+/*    The result of any routine which returns a number will always    */\r
+/*    be a valid number (which may be a special value, such as an     */\r
+/*    Infinity or NaN).                                               */\r
+/*                                                                    */\r
+/* 6. The decNumber format is not an exchangeable concrete            */\r
+/*    representation as it comprises fields which may be machine-     */\r
+/*    dependent (packed or unpacked, or special length, for example). */\r
+/*    Canonical conversions to and from strings are provided; other   */\r
+/*    conversions are available in separate modules.                  */\r
+/*                                                                    */\r
+/* 7. Normally, input operands are assumed to be valid.  Set DECCHECK */\r
+/*    to 1 for extended operand checking (including NULL operands).   */\r
+/*    Results are undefined if a badly-formed structure (or a NULL    */\r
+/*    pointer to a structure) is provided, though with DECCHECK       */\r
+/*    enabled the operator routines are protected against exceptions. */\r
+/*    (Except if the result pointer is NULL, which is unrecoverable.) */\r
+/*                                                                    */\r
+/*    However, the routines will never cause exceptions if they are   */\r
+/*    given well-formed operands, even if the value of the operands   */\r
+/*    is inappropriate for the operation and DECCHECK is not set.     */\r
+/*    (Except for SIGFPE, as and where documented.)                   */\r
+/*                                                                    */\r
+/* 8. Subset arithmetic is available only if DECSUBSET is set to 1.   */\r
+/* ------------------------------------------------------------------ */\r
+/* Implementation notes for maintenance of this module:               */\r
+/*                                                                    */\r
+/* 1. Storage leak protection:  Routines which use malloc are not     */\r
+/*    permitted to use return for fastpath or error exits (i.e.,      */\r
+/*    they follow strict structured programming conventions).         */\r
+/*    Instead they have a do{}while(0); construct surrounding the     */\r
+/*    code which is protected -- break may be used to exit this.      */\r
+/*    Other routines can safely use the return statement inline.      */\r
+/*                                                                    */\r
+/*    Storage leak accounting can be enabled using DECALLOC.          */\r
+/*                                                                    */\r
+/* 2. All loops use the for(;;) construct.  Any do construct does     */\r
+/*    not loop; it is for allocation protection as just described.    */\r
+/*                                                                    */\r
+/* 3. Setting status in the context must always be the very last      */\r
+/*    action in a routine, as non-0 status may raise a trap and hence */\r
+/*    the call to set status may not return (if the handler uses long */\r
+/*    jump).  Therefore all cleanup must be done first.  In general,  */\r
+/*    to achieve this status is accumulated and is only applied just  */\r
+/*    before return by calling decContextSetStatus (via decStatus).   */\r
+/*                                                                    */\r
+/*    Routines which allocate storage cannot, in general, use the     */\r
+/*    'top level' routines which could cause a non-returning          */\r
+/*    transfer of control.  The decXxxxOp routines are safe (do not   */\r
+/*    call decStatus even if traps are set in the context) and should */\r
+/*    be used instead (they are also a little faster).                */\r
+/*                                                                    */\r
+/* 4. Exponent checking is minimized by allowing the exponent to      */\r
+/*    grow outside its limits during calculations, provided that      */\r
+/*    the decFinalize function is called later.  Multiplication and   */\r
+/*    division, and intermediate calculations in exponentiation,      */\r
+/*    require more careful checks because of the risk of 31-bit       */\r
+/*    overflow (the most negative valid exponent is -1999999997, for  */\r
+/*    a 999999999-digit number with adjusted exponent of -999999999). */\r
+/*                                                                    */\r
+/* 5. Rounding is deferred until finalization of results, with any    */\r
+/*    'off to the right' data being represented as a single digit     */\r
+/*    residue (in the range -1 through 9).  This avoids any double-   */\r
+/*    rounding when more than one shortening takes place (for         */\r
+/*    example, when a result is subnormal).                           */\r
+/*                                                                    */\r
+/* 6. The digits count is allowed to rise to a multiple of DECDPUN    */\r
+/*    during many operations, so whole Units are handled and exact    */\r
+/*    accounting of digits is not needed.  The correct digits value   */\r
+/*    is found by decGetDigits, which accounts for leading zeros.     */\r
+/*    This must be called before any rounding if the number of digits */\r
+/*    is not known exactly.                                           */\r
+/*                                                                    */\r
+/* 7. The multiply-by-reciprocal 'trick' is used for partitioning     */\r
+/*    numbers up to four digits, using appropriate constants.  This   */\r
+/*    is not useful for longer numbers because overflow of 32 bits    */\r
+/*    would lead to 4 multiplies, which is almost as expensive as     */\r
+/*    a divide (unless a floating-point or 64-bit multiply is         */\r
+/*    assumed to be available).                                       */\r
+/*                                                                    */\r
+/* 8. Unusual abbreviations that may be used in the commentary:       */\r
+/*      lhs -- left hand side (operand, of an operation)              */\r
+/*      lsd -- least significant digit (of coefficient)               */\r
+/*      lsu -- least significant Unit (of coefficient)                */\r
+/*      msd -- most significant digit (of coefficient)                */\r
+/*      msi -- most significant item (in an array)                    */\r
+/*      msu -- most significant Unit (of coefficient)                 */\r
+/*      rhs -- right hand side (operand, of an operation)             */\r
+/*      +ve -- positive                                               */\r
+/*      -ve -- negative                                               */\r
+/*      **  -- raise to the power                                     */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#include <stdlib.h>                // for malloc, free, etc.\r
+#include <stdio.h>                 // for printf [if needed]\r
+#include <string.h>                // for strcpy\r
+#include <ctype.h>                 // for lower\r
+#include "decNumber.h"             // base number library\r
+#include "decNumberLocal.h"        // decNumber local types, etc.\r
+\r
+/* Constants */\r
+// Public lookup table used by the D2U macro\r
+const uByte d2utable[DECMAXD2U+1]=D2UTABLE;\r
+\r
+#define DECVERB     1              // set to 1 for verbose DECCHECK\r
+#define powers      DECPOWERS      // old internal name\r
+\r
+// Local constants\r
+#define DIVIDE      0x80           // Divide operators\r
+#define REMAINDER   0x40           // ..\r
+#define DIVIDEINT   0x20           // ..\r
+#define REMNEAR     0x10           // ..\r
+#define COMPARE     0x01           // Compare operators\r
+#define COMPMAX     0x02           // ..\r
+#define COMPMIN     0x03           // ..\r
+#define COMPTOTAL   0x04           // ..\r
+#define COMPNAN     0x05           // .. [NaN processing]\r
+#define COMPSIG     0x06           // .. [signaling COMPARE]\r
+#define COMPMAXMAG  0x07           // ..\r
+#define COMPMINMAG  0x08           // ..\r
+\r
+#define DEC_sNaN     0x40000000    // local status: sNaN signal\r
+#define BADINT  (Int)0x80000000    // most-negative Int; error indicator\r
+// Next two indicate an integer >= 10**6, and its parity (bottom bit)\r
+#define BIGEVEN (Int)0x80000002\r
+#define BIGODD  (Int)0x80000003\r
+\r
+static Unit uarrone[1]={1};   // Unit array of 1, used for incrementing\r
+\r
+/* Granularity-dependent code */\r
+#if DECDPUN<=4\r
+  #define eInt  Int           // extended integer\r
+  #define ueInt uInt          // unsigned extended integer\r
+  // Constant multipliers for divide-by-power-of five using reciprocal\r
+  // multiply, after removing powers of 2 by shifting, and final shift\r
+  // of 17 [we only need up to **4]\r
+  static const uInt multies[]={131073, 26215, 5243, 1049, 210};\r
+  // QUOT10 -- macro to return the quotient of unit u divided by 10**n\r
+  #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)\r
+#else\r
+  // For DECDPUN>4 non-ANSI-89 64-bit types are needed.\r
+  #if !DECUSE64\r
+    #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4\r
+  #endif\r
+  #define eInt  Long          // extended integer\r
+  #define ueInt uLong         // unsigned extended integer\r
+#endif\r
+\r
+/* Local routines */\r
+static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,\r
+                              decContext *, uByte, uInt *);\r
+static Flag        decBiStr(const char *, const char *, const char *);\r
+static uInt        decCheckMath(const decNumber *, decContext *, uInt *);\r
+static void        decApplyRound(decNumber *, decContext *, Int, uInt *);\r
+static Int         decCompare(const decNumber *lhs, const decNumber *rhs, Flag);\r
+static decNumber * decCompareOp(decNumber *, const decNumber *,\r
+                              const decNumber *, decContext *,\r
+                              Flag, uInt *);\r
+static void        decCopyFit(decNumber *, const decNumber *, decContext *,\r
+                              Int *, uInt *);\r
+static decNumber * decDecap(decNumber *, Int);\r
+static decNumber * decDivideOp(decNumber *, const decNumber *,\r
+                              const decNumber *, decContext *, Flag, uInt *);\r
+static decNumber * decExpOp(decNumber *, const decNumber *,\r
+                              decContext *, uInt *);\r
+static void        decFinalize(decNumber *, decContext *, Int *, uInt *);\r
+static Int         decGetDigits(Unit *, Int);\r
+static Int         decGetInt(const decNumber *);\r
+static decNumber * decLnOp(decNumber *, const decNumber *,\r
+                              decContext *, uInt *);\r
+static decNumber * decMultiplyOp(decNumber *, const decNumber *,\r
+                              const decNumber *, decContext *,\r
+                              uInt *);\r
+static decNumber * decNaNs(decNumber *, const decNumber *,\r
+                              const decNumber *, decContext *, uInt *);\r
+static decNumber * decQuantizeOp(decNumber *, const decNumber *,\r
+                              const decNumber *, decContext *, Flag,\r
+                              uInt *);\r
+static void        decReverse(Unit *, Unit *);\r
+static void        decSetCoeff(decNumber *, decContext *, const Unit *,\r
+                              Int, Int *, uInt *);\r
+static void        decSetMaxValue(decNumber *, decContext *);\r
+static void        decSetOverflow(decNumber *, decContext *, uInt *);\r
+static void        decSetSubnormal(decNumber *, decContext *, Int *, uInt *);\r
+static Int         decShiftToLeast(Unit *, Int, Int);\r
+static Int         decShiftToMost(Unit *, Int, Int);\r
+static void        decStatus(decNumber *, uInt, decContext *);\r
+static void        decToString(const decNumber *, char[], Flag);\r
+static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);\r
+static Int         decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,\r
+                              Unit *, Int);\r
+static Int         decUnitCompare(const Unit *, Int, const Unit *, Int, Int);\r
+\r
+#if !DECSUBSET\r
+/* decFinish == decFinalize when no subset arithmetic needed */\r
+#define decFinish(a,b,c,d) decFinalize(a,b,c,d)\r
+#else\r
+static void        decFinish(decNumber *, decContext *, Int *, uInt *);\r
+static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);\r
+#endif\r
+\r
+/* Local macros */\r
+// masked special-values bits\r
+#define SPECIALARG  (rhs->bits & DECSPECIAL)\r
+#define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)\r
+\r
+/* Diagnostic macros, etc. */\r
+#if DECALLOC\r
+// Handle malloc/free accounting.  If enabled, our accountable routines\r
+// are used; otherwise the code just goes straight to the system malloc\r
+// and free routines.\r
+#define malloc(a) decMalloc(a)\r
+#define free(a) decFree(a)\r
+#define DECFENCE 0x5a              // corruption detector\r
+// 'Our' malloc and free:\r
+static void *decMalloc(size_t);\r
+static void  decFree(void *);\r
+uInt decAllocBytes=0;              // count of bytes allocated\r
+// Note that DECALLOC code only checks for storage buffer overflow.\r
+// To check for memory leaks, the decAllocBytes variable must be\r
+// checked to be 0 at appropriate times (e.g., after the test\r
+// harness completes a set of tests).  This checking may be unreliable\r
+// if the testing is done in a multi-thread environment.\r
+#endif\r
+\r
+#if DECCHECK\r
+// Optional checking routines.  Enabling these means that decNumber\r
+// and decContext operands to operator routines are checked for\r
+// correctness.  This roughly doubles the execution time of the\r
+// fastest routines (and adds 600+ bytes), so should not normally be\r
+// used in 'production'.\r
+// decCheckInexact is used to check that inexact results have a full\r
+// complement of digits (where appropriate -- this is not the case\r
+// for Quantize, for example)\r
+#define DECUNRESU ((decNumber *)(void *)0xffffffff)\r
+#define DECUNUSED ((const decNumber *)(void *)0xffffffff)\r
+#define DECUNCONT ((decContext *)(void *)(0xffffffff))\r
+static Flag decCheckOperands(decNumber *, const decNumber *,\r
+                             const decNumber *, decContext *);\r
+static Flag decCheckNumber(const decNumber *);\r
+static void decCheckInexact(const decNumber *, decContext *);\r
+#endif\r
+\r
+#if DECTRACE || DECCHECK\r
+// Optional trace/debugging routines (may or may not be used)\r
+void decNumberShow(const decNumber *);  // displays the components of a number\r
+static void decDumpAr(char, const Unit *, Int);\r
+#endif\r
+\r
+/* ================================================================== */\r
+/* Conversions                                                        */\r
+/* ================================================================== */\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* from-int32 -- conversion from Int or uInt                          */\r
+/*                                                                    */\r
+/*  dn is the decNumber to receive the integer                        */\r
+/*  in or uin is the integer to be converted                          */\r
+/*  returns dn                                                        */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberFromInt32(decNumber *dn, Int in) {\r
+  uInt unsig;\r
+  if (in>=0) unsig=in;\r
+   else {                               // negative (possibly BADINT)\r
+    if (in==BADINT) unsig=(uInt)1073741824*2; // special case\r
+     else unsig=-in;                    // invert\r
+    }\r
+  // in is now positive\r
+  decNumberFromUInt32(dn, unsig);\r
+  if (in<0) dn->bits=DECNEG;            // sign needed\r
+  return dn;\r
+  } // decNumberFromInt32\r
+\r
+decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {\r
+  Unit *up;                             // work pointer\r
+  decNumberZero(dn);                    // clean\r
+  if (uin==0) return dn;                // [or decGetDigits bad call]\r
+  for (up=dn->lsu; uin>0; up++) {\r
+    *up=(Unit)(uin%(DECDPUNMAX+1));\r
+    uin=uin/(DECDPUNMAX+1);\r
+    }\r
+  dn->digits=decGetDigits(dn->lsu, up-dn->lsu);\r
+  return dn;\r
+  } // decNumberFromUInt32\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* to-int32 -- conversion to Int or uInt                              */\r
+/*                                                                    */\r
+/*  dn is the decNumber to convert                                    */\r
+/*  set is the context for reporting errors                           */\r
+/*  returns the converted decNumber, or 0 if Invalid is set           */\r
+/*                                                                    */\r
+/* Invalid is set if the decNumber does not have exponent==0 or if    */\r
+/* it is a NaN, Infinite, or out-of-range.                            */\r
+/* ------------------------------------------------------------------ */\r
+Int decNumberToInt32(const decNumber *dn, decContext *set) {\r
+  #if DECCHECK\r
+  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;\r
+  #endif\r
+\r
+  // special or too many digits, or bad exponent\r
+  if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; // bad\r
+   else { // is a finite integer with 10 or fewer digits\r
+    Int d;                         // work\r
+    const Unit *up;                // ..\r
+    uInt hi=0, lo;                 // ..\r
+    up=dn->lsu;                    // -> lsu\r
+    lo=*up;                        // get 1 to 9 digits\r
+    #if DECDPUN>1                  // split to higher\r
+      hi=lo/10;\r
+      lo=lo%10;\r
+    #endif\r
+    up++;\r
+    // collect remaining Units, if any, into hi\r
+    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];\r
+    // now low has the lsd, hi the remainder\r
+    if (hi>214748364 || (hi==214748364 && lo>7)) { // out of range?\r
+      // most-negative is a reprieve\r
+      if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;\r
+      // bad -- drop through\r
+      }\r
+     else { // in-range always\r
+      Int i=X10(hi)+lo;\r
+      if (dn->bits&DECNEG) return -i;\r
+      return i;\r
+      }\r
+    } // integer\r
+  decContextSetStatus(set, DEC_Invalid_operation); // [may not return]\r
+  return 0;\r
+  } // decNumberToInt32\r
+\r
+uInt decNumberToUInt32(const decNumber *dn, decContext *set) {\r
+  #if DECCHECK\r
+  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;\r
+  #endif\r
+  // special or too many digits, or bad exponent, or negative (<0)\r
+  if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0\r
+    || (dn->bits&DECNEG && !ISZERO(dn)));                   // bad\r
+   else { // is a finite integer with 10 or fewer digits\r
+    Int d;                         // work\r
+    const Unit *up;                // ..\r
+    uInt hi=0, lo;                 // ..\r
+    up=dn->lsu;                    // -> lsu\r
+    lo=*up;                        // get 1 to 9 digits\r
+    #if DECDPUN>1                  // split to higher\r
+      hi=lo/10;\r
+      lo=lo%10;\r
+    #endif\r
+    up++;\r
+    // collect remaining Units, if any, into hi\r
+    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];\r
+\r
+    // now low has the lsd, hi the remainder\r
+    if (hi>429496729 || (hi==429496729 && lo>5)) ; // no reprieve possible\r
+     else return X10(hi)+lo;\r
+    } // integer\r
+  decContextSetStatus(set, DEC_Invalid_operation); // [may not return]\r
+  return 0;\r
+  } // decNumberToUInt32\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* to-scientific-string -- conversion to numeric string               */\r
+/* to-engineering-string -- conversion to numeric string              */\r
+/*                                                                    */\r
+/*   decNumberToString(dn, string);                                   */\r
+/*   decNumberToEngString(dn, string);                                */\r
+/*                                                                    */\r
+/*  dn is the decNumber to convert                                    */\r
+/*  string is the string where the result will be laid out            */\r
+/*                                                                    */\r
+/*  string must be at least dn->digits+14 characters long             */\r
+/*                                                                    */\r
+/*  No error is possible, and no status can be set.                   */\r
+/* ------------------------------------------------------------------ */\r
+char * decNumberToString(const decNumber *dn, char *string){\r
+  decToString(dn, string, 0);\r
+  return string;\r
+  } // DecNumberToString\r
+\r
+char * decNumberToEngString(const decNumber *dn, char *string){\r
+  decToString(dn, string, 1);\r
+  return string;\r
+  } // DecNumberToEngString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* to-number -- conversion from numeric string                        */\r
+/*                                                                    */\r
+/* decNumberFromString -- convert string to decNumber                 */\r
+/*   dn        -- the number structure to fill                        */\r
+/*   chars[]   -- the string to convert ('\0' terminated)             */\r
+/*   set       -- the context used for processing any error,          */\r
+/*                determining the maximum precision available         */\r
+/*                (set.digits), determining the maximum and minimum   */\r
+/*                exponent (set.emax and set.emin), determining if    */\r
+/*                extended values are allowed, and checking the       */\r
+/*                rounding mode if overflow occurs or rounding is     */\r
+/*                needed.                                             */\r
+/*                                                                    */\r
+/* The length of the coefficient and the size of the exponent are     */\r
+/* checked by this routine, so the correct error (Underflow or        */\r
+/* Overflow) can be reported or rounding applied, as necessary.       */\r
+/*                                                                    */\r
+/* If bad syntax is detected, the result will be a quiet NaN.         */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberFromString(decNumber *dn, const char chars[],\r
+                                decContext *set) {\r
+  Int   exponent=0;                // working exponent [assume 0]\r
+  uByte bits=0;                    // working flags [assume +ve]\r
+  Unit  *res;                      // where result will be built\r
+  Unit  resbuff[SD2U(DECBUFFER+9)];// local buffer in case need temporary\r
+                                   // [+9 allows for ln() constants]\r
+  Unit  *allocres=NULL;            // -> allocated result, iff allocated\r
+  Int   d=0;                       // count of digits found in decimal part\r
+  const char *dotchar=NULL;        // where dot was found\r
+  const char *cfirst=chars;        // -> first character of decimal part\r
+  const char *last=NULL;           // -> last digit of decimal part\r
+  const char *c;                   // work\r
+  Unit  *up;                       // ..\r
+  #if DECDPUN>1\r
+  Int   cut, out;                  // ..\r
+  #endif\r
+  Int   residue;                   // rounding residue\r
+  uInt  status=0;                  // error code\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))\r
+    return decNumberZero(dn);\r
+  #endif\r
+\r
+  do {                             // status & malloc protection\r
+    for (c=chars;; c++) {          // -> input character\r
+      if (*c>='0' && *c<='9') {    // test for Arabic digit\r
+        last=c;\r
+        d++;                       // count of real digits\r
+        continue;                  // still in decimal part\r
+        }\r
+      if (*c=='.' && dotchar==NULL) { // first '.'\r
+        dotchar=c;                 // record offset into decimal part\r
+        if (c==cfirst) cfirst++;   // first digit must follow\r
+        continue;}\r
+      if (c==chars) {              // first in string...\r
+        if (*c=='-') {             // valid - sign\r
+          cfirst++;\r
+          bits=DECNEG;\r
+          continue;}\r
+        if (*c=='+') {             // valid + sign\r
+          cfirst++;\r
+          continue;}\r
+        }\r
+      // *c is not a digit, or a valid +, -, or '.'\r
+      break;\r
+      } // c\r
+\r
+    if (last==NULL) {              // no digits yet\r
+      status=DEC_Conversion_syntax;// assume the worst\r
+      if (*c=='\0') break;         // and no more to come...\r
+      #if DECSUBSET\r
+      // if subset then infinities and NaNs are not allowed\r
+      if (!set->extended) break;   // hopeless\r
+      #endif\r
+      // Infinities and NaNs are possible, here\r
+      if (dotchar!=NULL) break;    // .. unless had a dot\r
+      decNumberZero(dn);           // be optimistic\r
+      if (decBiStr(c, "infinity", "INFINITY")\r
+       || decBiStr(c, "inf", "INF")) {\r
+        dn->bits=bits | DECINF;\r
+        status=0;                  // is OK\r
+        break; // all done\r
+        }\r
+      // a NaN expected\r
+      // 2003.09.10 NaNs are now permitted to have a sign\r
+      dn->bits=bits | DECNAN;      // assume simple NaN\r
+      if (*c=='s' || *c=='S') {    // looks like an sNaN\r
+        c++;\r
+        dn->bits=bits | DECSNAN;\r
+        }\r
+      if (*c!='n' && *c!='N') break;    // check caseless "NaN"\r
+      c++;\r
+      if (*c!='a' && *c!='A') break;    // ..\r
+      c++;\r
+      if (*c!='n' && *c!='N') break;    // ..\r
+      c++;\r
+      // now either nothing, or nnnn payload, expected\r
+      // -> start of integer and skip leading 0s [including plain 0]\r
+      for (cfirst=c; *cfirst=='0';) cfirst++;\r
+      if (*cfirst=='\0') {         // "NaN" or "sNaN", maybe with all 0s\r
+        status=0;                  // it's good\r
+        break;                     // ..\r
+        }\r
+      // something other than 0s; setup last and d as usual [no dots]\r
+      for (c=cfirst;; c++, d++) {\r
+        if (*c<'0' || *c>'9') break; // test for Arabic digit\r
+        last=c;\r
+        }\r
+      if (*c!='\0') break;         // not all digits\r
+      if (d>set->digits-1) {\r
+        // [NB: payload in a decNumber can be full length unless\r
+        // clamped, in which case can only be digits-1]\r
+        if (set->clamp) break;\r
+        if (d>set->digits) break;\r
+        } // too many digits?\r
+      // good; drop through to convert the integer to coefficient\r
+      status=0;                    // syntax is OK\r
+      bits=dn->bits;               // for copy-back\r
+      } // last==NULL\r
+\r
+     else if (*c!='\0') {          // more to process...\r
+      // had some digits; exponent is only valid sequence now\r
+      Flag nege;                   // 1=negative exponent\r
+      const char *firstexp;        // -> first significant exponent digit\r
+      status=DEC_Conversion_syntax;// assume the worst\r
+      if (*c!='e' && *c!='E') break;\r
+      /* Found 'e' or 'E' -- now process explicit exponent */\r
+      // 1998.07.11: sign no longer required\r
+      nege=0;\r
+      c++;                         // to (possible) sign\r
+      if (*c=='-') {nege=1; c++;}\r
+       else if (*c=='+') c++;\r
+      if (*c=='\0') break;\r
+\r
+      for (; *c=='0' && *(c+1)!='\0';) c++;  // strip insignificant zeros\r
+      firstexp=c;                            // save exponent digit place\r
+      for (; ;c++) {\r
+        if (*c<'0' || *c>'9') break;         // not a digit\r
+        exponent=X10(exponent)+(Int)*c-(Int)'0';\r
+        } // c\r
+      // if not now on a '\0', *c must not be a digit\r
+      if (*c!='\0') break;\r
+\r
+      // (this next test must be after the syntax checks)\r
+      // if it was too long the exponent may have wrapped, so check\r
+      // carefully and set it to a certain overflow if wrap possible\r
+      if (c>=firstexp+9+1) {\r
+        if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;\r
+        // [up to 1999999999 is OK, for example 1E-1000000998]\r
+        }\r
+      if (nege) exponent=-exponent;     // was negative\r
+      status=0;                         // is OK\r
+      } // stuff after digits\r
+\r
+    // Here when whole string has been inspected; syntax is good\r
+    // cfirst->first digit (never dot), last->last digit (ditto)\r
+\r
+    // strip leading zeros/dot [leave final 0 if all 0's]\r
+    if (*cfirst=='0') {                 // [cfirst has stepped over .]\r
+      for (c=cfirst; c<last; c++, cfirst++) {\r
+        if (*c=='.') continue;          // ignore dots\r
+        if (*c!='0') break;             // non-zero found\r
+        d--;                            // 0 stripped\r
+        } // c\r
+      #if DECSUBSET\r
+      // make a rapid exit for easy zeros if !extended\r
+      if (*cfirst=='0' && !set->extended) {\r
+        decNumberZero(dn);              // clean result\r
+        break;                          // [could be return]\r
+        }\r
+      #endif\r
+      } // at least one leading 0\r
+\r
+    // Handle decimal point...\r
+    if (dotchar!=NULL && dotchar<last)  // non-trailing '.' found?\r
+      exponent-=(last-dotchar);         // adjust exponent\r
+    // [we can now ignore the .]\r
+\r
+    // OK, the digits string is good.  Assemble in the decNumber, or in\r
+    // a temporary units array if rounding is needed\r
+    if (d<=set->digits) res=dn->lsu;    // fits into supplied decNumber\r
+     else {                             // rounding needed\r
+      Int needbytes=D2U(d)*sizeof(Unit);// bytes needed\r
+      res=resbuff;                      // assume use local buffer\r
+      if (needbytes>(Int)sizeof(resbuff)) { // too big for local\r
+        allocres=(Unit *)malloc(needbytes);\r
+        if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}\r
+        res=allocres;\r
+        }\r
+      }\r
+    // res now -> number lsu, buffer, or allocated storage for Unit array\r
+\r
+    // Place the coefficient into the selected Unit array\r
+    // [this is often 70% of the cost of this function when DECDPUN>1]\r
+    #if DECDPUN>1\r
+    out=0;                         // accumulator\r
+    up=res+D2U(d)-1;               // -> msu\r
+    cut=d-(up-res)*DECDPUN;        // digits in top unit\r
+    for (c=cfirst;; c++) {         // along the digits\r
+      if (*c=='.') continue;       // ignore '.' [don't decrement cut]\r
+      out=X10(out)+(Int)*c-(Int)'0';\r
+      if (c==last) break;          // done [never get to trailing '.']\r
+      cut--;\r
+      if (cut>0) continue;         // more for this unit\r
+      *up=(Unit)out;               // write unit\r
+      up--;                        // prepare for unit below..\r
+      cut=DECDPUN;                 // ..\r
+      out=0;                       // ..\r
+      } // c\r
+    *up=(Unit)out;                 // write lsu\r
+\r
+    #else\r
+    // DECDPUN==1\r
+    up=res;                        // -> lsu\r
+    for (c=last; c>=cfirst; c--) { // over each character, from least\r
+      if (*c=='.') continue;       // ignore . [don't step up]\r
+      *up=(Unit)((Int)*c-(Int)'0');\r
+      up++;\r
+      } // c\r
+    #endif\r
+\r
+    dn->bits=bits;\r
+    dn->exponent=exponent;\r
+    dn->digits=d;\r
+\r
+    // if not in number (too long) shorten into the number\r
+    if (d>set->digits) {\r
+      residue=0;\r
+      decSetCoeff(dn, set, res, d, &residue, &status);\r
+      // always check for overflow or subnormal and round as needed\r
+      decFinalize(dn, set, &residue, &status);\r
+      }\r
+     else { // no rounding, but may still have overflow or subnormal\r
+      // [these tests are just for performance; finalize repeats them]\r
+      if ((dn->exponent-1<set->emin-dn->digits)\r
+       || (dn->exponent-1>set->emax-set->digits)) {\r
+        residue=0;\r
+        decFinalize(dn, set, &residue, &status);\r
+        }\r
+      }\r
+    // decNumberShow(dn);\r
+    } while(0);                         // [for break]\r
+\r
+  if (allocres!=NULL) free(allocres);   // drop any storage used\r
+  if (status!=0) decStatus(dn, status, set);\r
+  return dn;\r
+  } /* decNumberFromString */\r
+\r
+/* ================================================================== */\r
+/* Operators                                                          */\r
+/* ================================================================== */\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberAbs -- absolute value operator                            */\r
+/*                                                                    */\r
+/*   This computes C = abs(A)                                         */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* See also decNumberCopyAbs for a quiet bitwise version of this.     */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+/* This has the same effect as decNumberPlus unless A is negative,    */\r
+/* in which case it has the same effect as decNumberMinus.            */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,\r
+                         decContext *set) {\r
+  decNumber dzero;                      // for 0\r
+  uInt status=0;                        // accumulator\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  decNumberZero(&dzero);                // set 0\r
+  dzero.exponent=rhs->exponent;         // [no coefficient expansion]\r
+  decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberAbs\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberAdd -- add two Numbers                                    */\r
+/*                                                                    */\r
+/*   This computes C = A + B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+/* This just calls the routine shared with Subtract                   */\r
+decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,\r
+                         const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decAddOp(res, lhs, rhs, set, 0, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberAdd\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberAnd -- AND two Numbers, digitwise                         */\r
+/*                                                                    */\r
+/*   This computes C = A & B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context (used for result length and error report)     */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Logical function restrictions apply (see above); a NaN is          */\r
+/* returned with Invalid_operation if a restriction is violated.      */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,\r
+                         const decNumber *rhs, decContext *set) {\r
+  const Unit *ua, *ub;                  // -> operands\r
+  const Unit *msua, *msub;              // -> operand msus\r
+  Unit *uc,  *msuc;                     // -> result and its msu\r
+  Int   msudigs;                        // digits in res msu\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)\r
+   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {\r
+    decStatus(res, DEC_Invalid_operation, set);\r
+    return res;\r
+    }\r
+\r
+  // operands are valid\r
+  ua=lhs->lsu;                          // bottom-up\r
+  ub=rhs->lsu;                          // ..\r
+  uc=res->lsu;                          // ..\r
+  msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs\r
+  msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs\r
+  msuc=uc+D2U(set->digits)-1;           // -> msu of result\r
+  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]\r
+  for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop\r
+    Unit a, b;                          // extract units\r
+    if (ua>msua) a=0;\r
+     else a=*ua;\r
+    if (ub>msub) b=0;\r
+     else b=*ub;\r
+    *uc=0;                              // can now write back\r
+    if (a|b) {                          // maybe 1 bits to examine\r
+      Int i, j;\r
+      *uc=0;                            // can now write back\r
+      // This loop could be unrolled and/or use BIN2BCD tables\r
+      for (i=0; i<DECDPUN; i++) {\r
+        if (a&b&1) *uc=*uc+(Unit)powers[i];  // effect AND\r
+        j=a%10;\r
+        a=a/10;\r
+        j|=b%10;\r
+        b=b/10;\r
+        if (j>1) {\r
+          decStatus(res, DEC_Invalid_operation, set);\r
+          return res;\r
+          }\r
+        if (uc==msuc && i==msudigs-1) break; // just did final digit\r
+        } // each digit\r
+      } // both OK\r
+    } // each unit\r
+  // [here uc-1 is the msu of the result]\r
+  res->digits=decGetDigits(res->lsu, uc-res->lsu);\r
+  res->exponent=0;                      // integer\r
+  res->bits=0;                          // sign=0\r
+  return res;  // [no status to set]\r
+  } // decNumberAnd\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberCompare -- compare two Numbers                            */\r
+/*                                                                    */\r
+/*   This computes C = A ? B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for one digit (or NaN).                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,\r
+                             const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decCompareOp(res, lhs, rhs, set, COMPARE, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberCompare\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberCompareSignal -- compare, signalling on all NaNs          */\r
+/*                                                                    */\r
+/*   This computes C = A ? B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for one digit (or NaN).                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,\r
+                                   const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decCompareOp(res, lhs, rhs, set, COMPSIG, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberCompareSignal\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberCompareTotal -- compare two Numbers, using total ordering */\r
+/*                                                                    */\r
+/*   This computes C = A ? B, under total ordering                    */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for one digit; the result will always be one of  */\r
+/* -1, 0, or 1.                                                       */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,\r
+                                  const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberCompareTotal\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */\r
+/*                                                                    */\r
+/*   This computes C = |A| ? |B|, under total ordering                */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for one digit; the result will always be one of  */\r
+/* -1, 0, or 1.                                                       */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,\r
+                                     const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                   // accumulator\r
+  uInt needbytes;                  // for space calculations\r
+  decNumber bufa[D2N(DECBUFFER+1)];// +1 in case DECBUFFER=0\r
+  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated\r
+  decNumber bufb[D2N(DECBUFFER+1)];\r
+  decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated\r
+  decNumber *a, *b;                // temporary pointers\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                                  // protect allocated storage\r
+    // if either is negative, take a copy and absolute\r
+    if (decNumberIsNegative(lhs)) {     // lhs<0\r
+      a=bufa;\r
+      needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);\r
+      if (needbytes>sizeof(bufa)) {     // need malloc space\r
+        allocbufa=(decNumber *)malloc(needbytes);\r
+        if (allocbufa==NULL) {          // hopeless -- abandon\r
+          status|=DEC_Insufficient_storage;\r
+          break;}\r
+        a=allocbufa;                    // use the allocated space\r
+        }\r
+      decNumberCopy(a, lhs);            // copy content\r
+      a->bits&=~DECNEG;                 // .. and clear the sign\r
+      lhs=a;                            // use copy from here on\r
+      }\r
+    if (decNumberIsNegative(rhs)) {     // rhs<0\r
+      b=bufb;\r
+      needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);\r
+      if (needbytes>sizeof(bufb)) {     // need malloc space\r
+        allocbufb=(decNumber *)malloc(needbytes);\r
+        if (allocbufb==NULL) {          // hopeless -- abandon\r
+          status|=DEC_Insufficient_storage;\r
+          break;}\r
+        b=allocbufb;                    // use the allocated space\r
+        }\r
+      decNumberCopy(b, rhs);            // copy content\r
+      b->bits&=~DECNEG;                 // .. and clear the sign\r
+      rhs=b;                            // use copy from here on\r
+      }\r
+    decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);\r
+    } while(0);                         // end protected\r
+\r
+  if (allocbufa!=NULL) free(allocbufa); // drop any storage used\r
+  if (allocbufb!=NULL) free(allocbufb); // ..\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberCompareTotalMag\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberDivide -- divide one number by another                    */\r
+/*                                                                    */\r
+/*   This computes C = A / B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,\r
+                            const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decDivideOp(res, lhs, rhs, set, DIVIDE, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberDivide\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberDivideInteger -- divide and return integer quotient       */\r
+/*                                                                    */\r
+/*   This computes C = A # B, where # is the integer divide operator  */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,\r
+                                   const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberDivideInteger\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberExp -- exponentiation                                     */\r
+/*                                                                    */\r
+/*   This computes C = exp(A)                                         */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context; note that rounding mode has no effect        */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Mathematical function restrictions apply (see above); a NaN is     */\r
+/* returned with Invalid_operation if a restriction is violated.      */\r
+/*                                                                    */\r
+/* Finite results will always be full precision and Inexact, except   */\r
+/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */\r
+/*                                                                    */\r
+/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */\r
+/* almost always be correctly rounded, but may be up to 1 ulp in      */\r
+/* error in rare cases.                                               */\r
+/* ------------------------------------------------------------------ */\r
+/* This is a wrapper for decExpOp which can handle the slightly wider */\r
+/* (double) range needed by Ln (which has to be able to calculate     */\r
+/* exp(-a) where a can be the tiniest number (Ntiny).                 */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberExp(decNumber *res, const decNumber *rhs,\r
+                         decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  #if DECSUBSET\r
+  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated\r
+  #endif\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  // Check restrictions; these restrictions ensure that if h=8 (see\r
+  // decExpOp) then the result will either overflow or underflow to 0.\r
+  // Other math functions restrict the input range, too, for inverses.\r
+  // If not violated then carry out the operation.\r
+  if (!decCheckMath(rhs, set, &status)) do { // protect allocation\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operand and set lostDigits status, as needed\r
+      if (rhs->digits>set->digits) {\r
+        allocrhs=decRoundOperand(rhs, set, &status);\r
+        if (allocrhs==NULL) break;\r
+        rhs=allocrhs;\r
+        }\r
+      }\r
+    #endif\r
+    decExpOp(res, rhs, set, &status);\r
+    } while(0);                         // end protected\r
+\r
+  #if DECSUBSET\r
+  if (allocrhs !=NULL) free(allocrhs);  // drop any storage used\r
+  #endif\r
+  // apply significant status\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberExp\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberFMA -- fused multiply add                                 */\r
+/*                                                                    */\r
+/*   This computes D = (A * B) + C with only one rounding             */\r
+/*                                                                    */\r
+/*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   fhs is C [far hand side]                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* Mathematical function restrictions apply (see above); a NaN is     */\r
+/* returned with Invalid_operation if a restriction is violated.      */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,\r
+                         const decNumber *rhs, const decNumber *fhs,\r
+                         decContext *set) {\r
+  uInt status=0;                   // accumulator\r
+  decContext dcmul;                // context for the multiplication\r
+  uInt needbytes;                  // for space calculations\r
+  decNumber bufa[D2N(DECBUFFER*2+1)];\r
+  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated\r
+  decNumber *acc;                  // accumulator pointer\r
+  decNumber dzero;                 // work\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;\r
+  #endif\r
+\r
+  do {                                  // protect allocated storage\r
+    #if DECSUBSET\r
+    if (!set->extended) {               // [undefined if subset]\r
+      status|=DEC_Invalid_operation;\r
+      break;}\r
+    #endif\r
+    // Check math restrictions [these ensure no overflow or underflow]\r
+    if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))\r
+     || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))\r
+     || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;\r
+    // set up context for multiply\r
+    dcmul=*set;\r
+    dcmul.digits=lhs->digits+rhs->digits; // just enough\r
+    // [The above may be an over-estimate for subset arithmetic, but that's OK]\r
+    dcmul.emax=DEC_MAX_EMAX;            // effectively unbounded ..\r
+    dcmul.emin=DEC_MIN_EMIN;            // [thanks to Math restrictions]\r
+    // set up decNumber space to receive the result of the multiply\r
+    acc=bufa;                           // may fit\r
+    needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);\r
+    if (needbytes>sizeof(bufa)) {       // need malloc space\r
+      allocbufa=(decNumber *)malloc(needbytes);\r
+      if (allocbufa==NULL) {            // hopeless -- abandon\r
+        status|=DEC_Insufficient_storage;\r
+        break;}\r
+      acc=allocbufa;                    // use the allocated space\r
+      }\r
+    // multiply with extended range and necessary precision\r
+    //printf("emin=%ld\n", dcmul.emin);\r
+    decMultiplyOp(acc, lhs, rhs, &dcmul, &status);\r
+    // Only Invalid operation (from sNaN or Inf * 0) is possible in\r
+    // status; if either is seen than ignore fhs (in case it is\r
+    // another sNaN) and set acc to NaN unless we had an sNaN\r
+    // [decMultiplyOp leaves that to caller]\r
+    // Note sNaN has to go through addOp to shorten payload if\r
+    // necessary\r
+    if ((status&DEC_Invalid_operation)!=0) {\r
+      if (!(status&DEC_sNaN)) {         // but be true invalid\r
+        decNumberZero(res);             // acc not yet set\r
+        res->bits=DECNAN;\r
+        break;\r
+        }\r
+      decNumberZero(&dzero);            // make 0 (any non-NaN would do)\r
+      fhs=&dzero;                       // use that\r
+      }\r
+    #if DECCHECK\r
+     else { // multiply was OK\r
+      if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);\r
+      }\r
+    #endif\r
+    // add the third operand and result -> res, and all is done\r
+    decAddOp(res, acc, fhs, set, 0, &status);\r
+    } while(0);                         // end protected\r
+\r
+  if (allocbufa!=NULL) free(allocbufa); // drop any storage used\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberFMA\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberInvert -- invert a Number, digitwise                      */\r
+/*                                                                    */\r
+/*   This computes C = ~A                                             */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A (e.g., X=~X)                   */\r
+/*   rhs is A                                                         */\r
+/*   set is the context (used for result length and error report)     */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Logical function restrictions apply (see above); a NaN is          */\r
+/* returned with Invalid_operation if a restriction is violated.      */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,\r
+                            decContext *set) {\r
+  const Unit *ua, *msua;                // -> operand and its msu\r
+  Unit  *uc, *msuc;                     // -> result and its msu\r
+  Int   msudigs;                        // digits in res msu\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {\r
+    decStatus(res, DEC_Invalid_operation, set);\r
+    return res;\r
+    }\r
+  // operand is valid\r
+  ua=rhs->lsu;                          // bottom-up\r
+  uc=res->lsu;                          // ..\r
+  msua=ua+D2U(rhs->digits)-1;           // -> msu of rhs\r
+  msuc=uc+D2U(set->digits)-1;           // -> msu of result\r
+  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]\r
+  for (; uc<=msuc; ua++, uc++) {        // Unit loop\r
+    Unit a;                             // extract unit\r
+    Int  i, j;                          // work\r
+    if (ua>msua) a=0;\r
+     else a=*ua;\r
+    *uc=0;                              // can now write back\r
+    // always need to examine all bits in rhs\r
+    // This loop could be unrolled and/or use BIN2BCD tables\r
+    for (i=0; i<DECDPUN; i++) {\r
+      if ((~a)&1) *uc=*uc+(Unit)powers[i];   // effect INVERT\r
+      j=a%10;\r
+      a=a/10;\r
+      if (j>1) {\r
+        decStatus(res, DEC_Invalid_operation, set);\r
+        return res;\r
+        }\r
+      if (uc==msuc && i==msudigs-1) break;   // just did final digit\r
+      } // each digit\r
+    } // each unit\r
+  // [here uc-1 is the msu of the result]\r
+  res->digits=decGetDigits(res->lsu, uc-res->lsu);\r
+  res->exponent=0;                      // integer\r
+  res->bits=0;                          // sign=0\r
+  return res;  // [no status to set]\r
+  } // decNumberInvert\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberLn -- natural logarithm                                   */\r
+/*                                                                    */\r
+/*   This computes C = ln(A)                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context; note that rounding mode has no effect        */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Notable cases:                                                     */\r
+/*   A<0 -> Invalid                                                   */\r
+/*   A=0 -> -Infinity (Exact)                                         */\r
+/*   A=+Infinity -> +Infinity (Exact)                                 */\r
+/*   A=1 exactly -> 0 (Exact)                                         */\r
+/*                                                                    */\r
+/* Mathematical function restrictions apply (see above); a NaN is     */\r
+/* returned with Invalid_operation if a restriction is violated.      */\r
+/*                                                                    */\r
+/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */\r
+/* almost always be correctly rounded, but may be up to 1 ulp in      */\r
+/* error in rare cases.                                               */\r
+/* ------------------------------------------------------------------ */\r
+/* This is a wrapper for decLnOp which can handle the slightly wider  */\r
+/* (+11) range needed by Ln, Log10, etc. (which may have to be able   */\r
+/* to calculate at p+e+2).                                            */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberLn(decNumber *res, const decNumber *rhs,\r
+                        decContext *set) {\r
+  uInt status=0;                   // accumulator\r
+  #if DECSUBSET\r
+  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated\r
+  #endif\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  // Check restrictions; this is a math function; if not violated\r
+  // then carry out the operation.\r
+  if (!decCheckMath(rhs, set, &status)) do { // protect allocation\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operand and set lostDigits status, as needed\r
+      if (rhs->digits>set->digits) {\r
+        allocrhs=decRoundOperand(rhs, set, &status);\r
+        if (allocrhs==NULL) break;\r
+        rhs=allocrhs;\r
+        }\r
+      // special check in subset for rhs=0\r
+      if (ISZERO(rhs)) {                // +/- zeros -> error\r
+        status|=DEC_Invalid_operation;\r
+        break;}\r
+      } // extended=0\r
+    #endif\r
+    decLnOp(res, rhs, set, &status);\r
+    } while(0);                         // end protected\r
+\r
+  #if DECSUBSET\r
+  if (allocrhs !=NULL) free(allocrhs);  // drop any storage used\r
+  #endif\r
+  // apply significant status\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberLn\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberLogB - get adjusted exponent, by 754 rules                */\r
+/*                                                                    */\r
+/*   This computes C = adjustedexponent(A)                            */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context, used only for digits and status              */\r
+/*                                                                    */\r
+/* For an unrounded result, digits may need to be 10 (A might have    */\r
+/* 10**9 digits and an exponent of +999999999, or one digit and an    */\r
+/* exponent of -1999999999).                                          */\r
+/*                                                                    */\r
+/* This returns the adjusted exponent of A after (in theory) padding  */\r
+/* with zeros on the right to set->digits digits while keeping the    */\r
+/* same value.  The exponent is not limited by emin/emax.             */\r
+/*                                                                    */\r
+/* Notable cases:                                                     */\r
+/*   A<0 -> Use |A|                                                   */\r
+/*   A=0 -> -Infinity (Division by zero)                              */\r
+/*   A=Infinite -> +Infinity (Exact)                                  */\r
+/*   A=1 exactly -> 0 (Exact)                                         */\r
+/*   NaNs are propagated as usual                                     */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,\r
+                          decContext *set) {\r
+  uInt status=0;                   // accumulator\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  // NaNs as usual; Infinities return +Infinity; 0->oops\r
+  if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);\r
+   else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);\r
+   else if (decNumberIsZero(rhs)) {\r
+    decNumberZero(res);                 // prepare for Infinity\r
+    res->bits=DECNEG|DECINF;            // -Infinity\r
+    status|=DEC_Division_by_zero;       // as per 754\r
+    }\r
+   else { // finite non-zero\r
+    Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent\r
+    if (set->digits>=10) decNumberFromInt32(res, ae);  // lay it out\r
+     else {\r
+      decNumber buft[D2N(10)];          // temporary number\r
+      decNumber *t=buft;                // ..\r
+      decNumberFromInt32(t, ae);        // lay it out\r
+      decNumberPlus(res, t, set);       // round as necessary\r
+      }\r
+    }\r
+\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberLogB\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberLog10 -- logarithm in base 10                             */\r
+/*                                                                    */\r
+/*   This computes C = log10(A)                                       */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context; note that rounding mode has no effect        */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Notable cases:                                                     */\r
+/*   A<0 -> Invalid                                                   */\r
+/*   A=0 -> -Infinity (Exact)                                         */\r
+/*   A=+Infinity -> +Infinity (Exact)                                 */\r
+/*   A=10**n (if n is an integer) -> n (Exact)                        */\r
+/*                                                                    */\r
+/* Mathematical function restrictions apply (see above); a NaN is     */\r
+/* returned with Invalid_operation if a restriction is violated.      */\r
+/*                                                                    */\r
+/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */\r
+/* almost always be correctly rounded, but may be up to 1 ulp in      */\r
+/* error in rare cases.                                               */\r
+/* ------------------------------------------------------------------ */\r
+/* This calculates ln(A)/ln(10) using appropriate precision.  For     */\r
+/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */\r
+/* requested digits and t is the number of digits in the exponent     */\r
+/* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */\r
+/* fastpath in decLnOp.  The final division is done to the requested  */\r
+/* precision.                                                         */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,\r
+                          decContext *set) {\r
+  uInt status=0, ignore=0;         // status accumulators\r
+  uInt needbytes;                  // for space calculations\r
+  Int p;                           // working precision\r
+  Int t;                           // digits in exponent of A\r
+\r
+  // buffers for a and b working decimals\r
+  // (adjustment calculator, same size)\r
+  decNumber bufa[D2N(DECBUFFER+2)];\r
+  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated\r
+  decNumber *a=bufa;               // temporary a\r
+  decNumber bufb[D2N(DECBUFFER+2)];\r
+  decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated\r
+  decNumber *b=bufb;               // temporary b\r
+  decNumber bufw[D2N(10)];         // working 2-10 digit number\r
+  decNumber *w=bufw;               // ..\r
+  #if DECSUBSET\r
+  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated\r
+  #endif\r
+\r
+  decContext aset;                 // working context\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  // Check restrictions; this is a math function; if not violated\r
+  // then carry out the operation.\r
+  if (!decCheckMath(rhs, set, &status)) do { // protect malloc\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operand and set lostDigits status, as needed\r
+      if (rhs->digits>set->digits) {\r
+        allocrhs=decRoundOperand(rhs, set, &status);\r
+        if (allocrhs==NULL) break;\r
+        rhs=allocrhs;\r
+        }\r
+      // special check in subset for rhs=0\r
+      if (ISZERO(rhs)) {                // +/- zeros -> error\r
+        status|=DEC_Invalid_operation;\r
+        break;}\r
+      } // extended=0\r
+    #endif\r
+\r
+    decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context\r
+\r
+    // handle exact powers of 10; only check if +ve finite\r
+    if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {\r
+      Int residue=0;               // (no residue)\r
+      uInt copystat=0;             // clean status\r
+\r
+      // round to a single digit...\r
+      aset.digits=1;\r
+      decCopyFit(w, rhs, &aset, &residue, &copystat); // copy & shorten\r
+      // if exact and the digit is 1, rhs is a power of 10\r
+      if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {\r
+        // the exponent, conveniently, is the power of 10; making\r
+        // this the result needs a little care as it might not fit,\r
+        // so first convert it into the working number, and then move\r
+        // to res\r
+        decNumberFromInt32(w, w->exponent);\r
+        residue=0;\r
+        decCopyFit(res, w, set, &residue, &status); // copy & round\r
+        decFinish(res, set, &residue, &status);     // cleanup/set flags\r
+        break;\r
+        } // not a power of 10\r
+      } // not a candidate for exact\r
+\r
+    // simplify the information-content calculation to use 'total\r
+    // number of digits in a, including exponent' as compared to the\r
+    // requested digits, as increasing this will only rarely cost an\r
+    // iteration in ln(a) anyway\r
+    t=6;                                // it can never be >6\r
+\r
+    // allocate space when needed...\r
+    p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;\r
+    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);\r
+    if (needbytes>sizeof(bufa)) {       // need malloc space\r
+      allocbufa=(decNumber *)malloc(needbytes);\r
+      if (allocbufa==NULL) {            // hopeless -- abandon\r
+        status|=DEC_Insufficient_storage;\r
+        break;}\r
+      a=allocbufa;                      // use the allocated space\r
+      }\r
+    aset.digits=p;                      // as calculated\r
+    aset.emax=DEC_MAX_MATH;             // usual bounds\r
+    aset.emin=-DEC_MAX_MATH;            // ..\r
+    aset.clamp=0;                       // and no concrete format\r
+    decLnOp(a, rhs, &aset, &status);    // a=ln(rhs)\r
+\r
+    // skip the division if the result so far is infinite, NaN, or\r
+    // zero, or there was an error; note NaN from sNaN needs copy\r
+    if (status&DEC_NaNs && !(status&DEC_sNaN)) break;\r
+    if (a->bits&DECSPECIAL || ISZERO(a)) {\r
+      decNumberCopy(res, a);            // [will fit]\r
+      break;}\r
+\r
+    // for ln(10) an extra 3 digits of precision are needed\r
+    p=set->digits+3;\r
+    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);\r
+    if (needbytes>sizeof(bufb)) {       // need malloc space\r
+      allocbufb=(decNumber *)malloc(needbytes);\r
+      if (allocbufb==NULL) {            // hopeless -- abandon\r
+        status|=DEC_Insufficient_storage;\r
+        break;}\r
+      b=allocbufb;                      // use the allocated space\r
+      }\r
+    decNumberZero(w);                   // set up 10...\r
+    #if DECDPUN==1\r
+    w->lsu[1]=1; w->lsu[0]=0;           // ..\r
+    #else\r
+    w->lsu[0]=10;                       // ..\r
+    #endif\r
+    w->digits=2;                        // ..\r
+\r
+    aset.digits=p;\r
+    decLnOp(b, w, &aset, &ignore);      // b=ln(10)\r
+\r
+    aset.digits=set->digits;            // for final divide\r
+    decDivideOp(res, a, b, &aset, DIVIDE, &status); // into result\r
+    } while(0);                         // [for break]\r
+\r
+  if (allocbufa!=NULL) free(allocbufa); // drop any storage used\r
+  if (allocbufb!=NULL) free(allocbufb); // ..\r
+  #if DECSUBSET\r
+  if (allocrhs !=NULL) free(allocrhs);  // ..\r
+  #endif\r
+  // apply significant status\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberLog10\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberMax -- compare two Numbers and return the maximum         */\r
+/*                                                                    */\r
+/*   This computes C = A ? B, returning the maximum by 754 rules      */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberMax(decNumber *res, const decNumber *lhs,\r
+                         const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decCompareOp(res, lhs, rhs, set, COMPMAX, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberMax\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberMaxMag -- compare and return the maximum by magnitude     */\r
+/*                                                                    */\r
+/*   This computes C = A ? B, returning the maximum by 754 rules      */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,\r
+                         const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberMaxMag\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberMin -- compare two Numbers and return the minimum         */\r
+/*                                                                    */\r
+/*   This computes C = A ? B, returning the minimum by 754 rules      */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberMin(decNumber *res, const decNumber *lhs,\r
+                         const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decCompareOp(res, lhs, rhs, set, COMPMIN, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberMin\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberMinMag -- compare and return the minimum by magnitude     */\r
+/*                                                                    */\r
+/*   This computes C = A ? B, returning the minimum by 754 rules      */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,\r
+                         const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberMinMag\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberMinus -- prefix minus operator                            */\r
+/*                                                                    */\r
+/*   This computes C = 0 - A                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* See also decNumberCopyNegate for a quiet bitwise version of this.  */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+/* Simply use AddOp for the subtract, which will do the necessary.    */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,\r
+                           decContext *set) {\r
+  decNumber dzero;\r
+  uInt status=0;                        // accumulator\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  decNumberZero(&dzero);                // make 0\r
+  dzero.exponent=rhs->exponent;         // [no coefficient expansion]\r
+  decAddOp(res, &dzero, rhs, set, DECNEG, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberMinus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberNextMinus -- next towards -Infinity                       */\r
+/*                                                                    */\r
+/*   This computes C = A - infinitesimal, rounded towards -Infinity   */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* This is a generalization of 754 NextDown.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,\r
+                               decContext *set) {\r
+  decNumber dtiny;                           // constant\r
+  decContext workset=*set;                   // work\r
+  uInt status=0;                             // accumulator\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  // +Infinity is the special case\r
+  if ((rhs->bits&(DECINF|DECNEG))==DECINF) {\r
+    decSetMaxValue(res, set);                // is +ve\r
+    // there is no status to set\r
+    return res;\r
+    }\r
+  decNumberZero(&dtiny);                     // start with 0\r
+  dtiny.lsu[0]=1;                            // make number that is ..\r
+  dtiny.exponent=DEC_MIN_EMIN-1;             // .. smaller than tiniest\r
+  workset.round=DEC_ROUND_FLOOR;\r
+  decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);\r
+  status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberNextMinus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberNextPlus -- next towards +Infinity                        */\r
+/*                                                                    */\r
+/*   This computes C = A + infinitesimal, rounded towards +Infinity   */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* This is a generalization of 754 NextUp.                            */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,\r
+                              decContext *set) {\r
+  decNumber dtiny;                           // constant\r
+  decContext workset=*set;                   // work\r
+  uInt status=0;                             // accumulator\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  // -Infinity is the special case\r
+  if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {\r
+    decSetMaxValue(res, set);\r
+    res->bits=DECNEG;                        // negative\r
+    // there is no status to set\r
+    return res;\r
+    }\r
+  decNumberZero(&dtiny);                     // start with 0\r
+  dtiny.lsu[0]=1;                            // make number that is ..\r
+  dtiny.exponent=DEC_MIN_EMIN-1;             // .. smaller than tiniest\r
+  workset.round=DEC_ROUND_CEILING;\r
+  decAddOp(res, rhs, &dtiny, &workset, 0, &status);\r
+  status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberNextPlus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberNextToward -- next towards rhs                            */\r
+/*                                                                    */\r
+/*   This computes C = A +/- infinitesimal, rounded towards           */\r
+/*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */\r
+/*   modified during revision but dropped from 754-2008.              */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A or B.                          */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* This is a generalization of 754-1985 NextAfter.                    */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,\r
+                                const decNumber *rhs, decContext *set) {\r
+  decNumber dtiny;                           // constant\r
+  decContext workset=*set;                   // work\r
+  Int result;                                // ..\r
+  uInt status=0;                             // accumulator\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {\r
+    decNaNs(res, lhs, rhs, set, &status);\r
+    }\r
+   else { // Is numeric, so no chance of sNaN Invalid, etc.\r
+    result=decCompare(lhs, rhs, 0);     // sign matters\r
+    if (result==BADINT) status|=DEC_Insufficient_storage; // rare\r
+     else { // valid compare\r
+      if (result==0) decNumberCopySign(res, lhs, rhs); // easy\r
+       else { // differ: need NextPlus or NextMinus\r
+        uByte sub;                      // add or subtract\r
+        if (result<0) {                 // lhs<rhs, do nextplus\r
+          // -Infinity is the special case\r
+          if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {\r
+            decSetMaxValue(res, set);\r
+            res->bits=DECNEG;           // negative\r
+            return res;                 // there is no status to set\r
+            }\r
+          workset.round=DEC_ROUND_CEILING;\r
+          sub=0;                        // add, please\r
+          } // plus\r
+         else {                         // lhs>rhs, do nextminus\r
+          // +Infinity is the special case\r
+          if ((lhs->bits&(DECINF|DECNEG))==DECINF) {\r
+            decSetMaxValue(res, set);\r
+            return res;                 // there is no status to set\r
+            }\r
+          workset.round=DEC_ROUND_FLOOR;\r
+          sub=DECNEG;                   // subtract, please\r
+          } // minus\r
+        decNumberZero(&dtiny);          // start with 0\r
+        dtiny.lsu[0]=1;                 // make number that is ..\r
+        dtiny.exponent=DEC_MIN_EMIN-1;  // .. smaller than tiniest\r
+        decAddOp(res, lhs, &dtiny, &workset, sub, &status); // + or -\r
+        // turn off exceptions if the result is a normal number\r
+        // (including Nmin), otherwise let all status through\r
+        if (decNumberIsNormal(res, set)) status=0;\r
+        } // unequal\r
+      } // compare OK\r
+    } // numeric\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberNextToward\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberOr -- OR two Numbers, digitwise                           */\r
+/*                                                                    */\r
+/*   This computes C = A | B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context (used for result length and error report)     */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Logical function restrictions apply (see above); a NaN is          */\r
+/* returned with Invalid_operation if a restriction is violated.      */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberOr(decNumber *res, const decNumber *lhs,\r
+                        const decNumber *rhs, decContext *set) {\r
+  const Unit *ua, *ub;                  // -> operands\r
+  const Unit *msua, *msub;              // -> operand msus\r
+  Unit  *uc, *msuc;                     // -> result and its msu\r
+  Int   msudigs;                        // digits in res msu\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)\r
+   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {\r
+    decStatus(res, DEC_Invalid_operation, set);\r
+    return res;\r
+    }\r
+  // operands are valid\r
+  ua=lhs->lsu;                          // bottom-up\r
+  ub=rhs->lsu;                          // ..\r
+  uc=res->lsu;                          // ..\r
+  msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs\r
+  msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs\r
+  msuc=uc+D2U(set->digits)-1;           // -> msu of result\r
+  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]\r
+  for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop\r
+    Unit a, b;                          // extract units\r
+    if (ua>msua) a=0;\r
+     else a=*ua;\r
+    if (ub>msub) b=0;\r
+     else b=*ub;\r
+    *uc=0;                              // can now write back\r
+    if (a|b) {                          // maybe 1 bits to examine\r
+      Int i, j;\r
+      // This loop could be unrolled and/or use BIN2BCD tables\r
+      for (i=0; i<DECDPUN; i++) {\r
+        if ((a|b)&1) *uc=*uc+(Unit)powers[i];     // effect OR\r
+        j=a%10;\r
+        a=a/10;\r
+        j|=b%10;\r
+        b=b/10;\r
+        if (j>1) {\r
+          decStatus(res, DEC_Invalid_operation, set);\r
+          return res;\r
+          }\r
+        if (uc==msuc && i==msudigs-1) break;      // just did final digit\r
+        } // each digit\r
+      } // non-zero\r
+    } // each unit\r
+  // [here uc-1 is the msu of the result]\r
+  res->digits=decGetDigits(res->lsu, uc-res->lsu);\r
+  res->exponent=0;                      // integer\r
+  res->bits=0;                          // sign=0\r
+  return res;  // [no status to set]\r
+  } // decNumberOr\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberPlus -- prefix plus operator                              */\r
+/*                                                                    */\r
+/*   This computes C = 0 + A                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* See also decNumberCopy for a quiet bitwise version of this.        */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+/* This simply uses AddOp; Add will take fast path after preparing A. */\r
+/* Performance is a concern here, as this routine is often used to    */\r
+/* check operands and apply rounding and overflow/underflow testing.  */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,\r
+                          decContext *set) {\r
+  decNumber dzero;\r
+  uInt status=0;                        // accumulator\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  decNumberZero(&dzero);                // make 0\r
+  dzero.exponent=rhs->exponent;         // [no coefficient expansion]\r
+  decAddOp(res, &dzero, rhs, set, 0, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberPlus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberMultiply -- multiply two Numbers                          */\r
+/*                                                                    */\r
+/*   This computes C = A x B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,\r
+                              const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                   // accumulator\r
+  decMultiplyOp(res, lhs, rhs, set, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberMultiply\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberPower -- raise a number to a power                        */\r
+/*                                                                    */\r
+/*   This computes C = A ** B                                         */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Mathematical function restrictions apply (see above); a NaN is     */\r
+/* returned with Invalid_operation if a restriction is violated.      */\r
+/*                                                                    */\r
+/* However, if 1999999997<=B<=999999999 and B is an integer then the  */\r
+/* restrictions on A and the context are relaxed to the usual bounds, */\r
+/* for compatibility with the earlier (integer power only) version    */\r
+/* of this function.                                                  */\r
+/*                                                                    */\r
+/* When B is an integer, the result may be exact, even if rounded.    */\r
+/*                                                                    */\r
+/* The final result is rounded according to the context; it will      */\r
+/* almost always be correctly rounded, but may be up to 1 ulp in      */\r
+/* error in rare cases.                                               */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberPower(decNumber *res, const decNumber *lhs,\r
+                           const decNumber *rhs, decContext *set) {\r
+  #if DECSUBSET\r
+  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated\r
+  decNumber *allocrhs=NULL;        // .., rhs\r
+  #endif\r
+  decNumber *allocdac=NULL;        // -> allocated acc buffer, iff used\r
+  decNumber *allocinv=NULL;        // -> allocated 1/x buffer, iff used\r
+  Int   reqdigits=set->digits;     // requested DIGITS\r
+  Int   n;                         // rhs in binary\r
+  Flag  rhsint=0;                  // 1 if rhs is an integer\r
+  Flag  useint=0;                  // 1 if can use integer calculation\r
+  Flag  isoddint=0;                // 1 if rhs is an integer and odd\r
+  Int   i;                         // work\r
+  #if DECSUBSET\r
+  Int   dropped;                   // ..\r
+  #endif\r
+  uInt  needbytes;                 // buffer size needed\r
+  Flag  seenbit;                   // seen a bit while powering\r
+  Int   residue=0;                 // rounding residue\r
+  uInt  status=0;                  // accumulators\r
+  uByte bits=0;                    // result sign if errors\r
+  decContext aset;                 // working context\r
+  decNumber dnOne;                 // work value 1...\r
+  // local accumulator buffer [a decNumber, with digits+elength+1 digits]\r
+  decNumber dacbuff[D2N(DECBUFFER+9)];\r
+  decNumber *dac=dacbuff;          // -> result accumulator\r
+  // same again for possible 1/lhs calculation\r
+  decNumber invbuff[D2N(DECBUFFER+9)];\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                             // protect allocated storage\r
+    #if DECSUBSET\r
+    if (!set->extended) { // reduce operands and set status, as needed\r
+      if (lhs->digits>reqdigits) {\r
+        alloclhs=decRoundOperand(lhs, set, &status);\r
+        if (alloclhs==NULL) break;\r
+        lhs=alloclhs;\r
+        }\r
+      if (rhs->digits>reqdigits) {\r
+        allocrhs=decRoundOperand(rhs, set, &status);\r
+        if (allocrhs==NULL) break;\r
+        rhs=allocrhs;\r
+        }\r
+      }\r
+    #endif\r
+    // [following code does not require input rounding]\r
+\r
+    // handle NaNs and rhs Infinity (lhs infinity is harder)\r
+    if (SPECIALARGS) {\r
+      if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { // NaNs\r
+        decNaNs(res, lhs, rhs, set, &status);\r
+        break;}\r
+      if (decNumberIsInfinite(rhs)) {   // rhs Infinity\r
+        Flag rhsneg=rhs->bits&DECNEG;   // save rhs sign\r
+        if (decNumberIsNegative(lhs)    // lhs<0\r
+         && !decNumberIsZero(lhs))      // ..\r
+          status|=DEC_Invalid_operation;\r
+         else {                         // lhs >=0\r
+          decNumberZero(&dnOne);        // set up 1\r
+          dnOne.lsu[0]=1;\r
+          decNumberCompare(dac, lhs, &dnOne, set); // lhs ? 1\r
+          decNumberZero(res);           // prepare for 0/1/Infinity\r
+          if (decNumberIsNegative(dac)) {    // lhs<1\r
+            if (rhsneg) res->bits|=DECINF;   // +Infinity [else is +0]\r
+            }\r
+           else if (dac->lsu[0]==0) {        // lhs=1\r
+            // 1**Infinity is inexact, so return fully-padded 1.0000\r
+            Int shift=set->digits-1;\r
+            *res->lsu=1;                     // was 0, make int 1\r
+            res->digits=decShiftToMost(res->lsu, 1, shift);\r
+            res->exponent=-shift;            // make 1.0000...\r
+            status|=DEC_Inexact|DEC_Rounded; // deemed inexact\r
+            }\r
+           else {                            // lhs>1\r
+            if (!rhsneg) res->bits|=DECINF;  // +Infinity [else is +0]\r
+            }\r
+          } // lhs>=0\r
+        break;}\r
+      // [lhs infinity drops through]\r
+      } // specials\r
+\r
+    // Original rhs may be an integer that fits and is in range\r
+    n=decGetInt(rhs);\r
+    if (n!=BADINT) {                    // it is an integer\r
+      rhsint=1;                         // record the fact for 1**n\r
+      isoddint=(Flag)n&1;               // [works even if big]\r
+      if (n!=BIGEVEN && n!=BIGODD)      // can use integer path?\r
+        useint=1;                       // looks good\r
+      }\r
+\r
+    if (decNumberIsNegative(lhs)        // -x ..\r
+      && isoddint) bits=DECNEG;         // .. to an odd power\r
+\r
+    // handle LHS infinity\r
+    if (decNumberIsInfinite(lhs)) {     // [NaNs already handled]\r
+      uByte rbits=rhs->bits;            // save\r
+      decNumberZero(res);               // prepare\r
+      if (n==0) *res->lsu=1;            // [-]Inf**0 => 1\r
+       else {\r
+        // -Inf**nonint -> error\r
+        if (!rhsint && decNumberIsNegative(lhs)) {\r
+          status|=DEC_Invalid_operation;     // -Inf**nonint is error\r
+          break;}\r
+        if (!(rbits & DECNEG)) bits|=DECINF; // was not a **-n\r
+        // [otherwise will be 0 or -0]\r
+        res->bits=bits;\r
+        }\r
+      break;}\r
+\r
+    // similarly handle LHS zero\r
+    if (decNumberIsZero(lhs)) {\r
+      if (n==0) {                            // 0**0 => Error\r
+        #if DECSUBSET\r
+        if (!set->extended) {                // [unless subset]\r
+          decNumberZero(res);\r
+          *res->lsu=1;                       // return 1\r
+          break;}\r
+        #endif\r
+        status|=DEC_Invalid_operation;\r
+        }\r
+       else {                                // 0**x\r
+        uByte rbits=rhs->bits;               // save\r
+        if (rbits & DECNEG) {                // was a 0**(-n)\r
+          #if DECSUBSET\r
+          if (!set->extended) {              // [bad if subset]\r
+            status|=DEC_Invalid_operation;\r
+            break;}\r
+          #endif\r
+          bits|=DECINF;\r
+          }\r
+        decNumberZero(res);                  // prepare\r
+        // [otherwise will be 0 or -0]\r
+        res->bits=bits;\r
+        }\r
+      break;}\r
+\r
+    // here both lhs and rhs are finite; rhs==0 is handled in the\r
+    // integer path.  Next handle the non-integer cases\r
+    if (!useint) {                      // non-integral rhs\r
+      // any -ve lhs is bad, as is either operand or context out of\r
+      // bounds\r
+      if (decNumberIsNegative(lhs)) {\r
+        status|=DEC_Invalid_operation;\r
+        break;}\r
+      if (decCheckMath(lhs, set, &status)\r
+       || decCheckMath(rhs, set, &status)) break; // variable status\r
+\r
+      decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context\r
+      aset.emax=DEC_MAX_MATH;           // usual bounds\r
+      aset.emin=-DEC_MAX_MATH;          // ..\r
+      aset.clamp=0;                     // and no concrete format\r
+\r
+      // calculate the result using exp(ln(lhs)*rhs), which can\r
+      // all be done into the accumulator, dac.  The precision needed\r
+      // is enough to contain the full information in the lhs (which\r
+      // is the total digits, including exponent), or the requested\r
+      // precision, if larger, + 4; 6 is used for the exponent\r
+      // maximum length, and this is also used when it is shorter\r
+      // than the requested digits as it greatly reduces the >0.5 ulp\r
+      // cases at little cost (because Ln doubles digits each\r
+      // iteration so a few extra digits rarely causes an extra\r
+      // iteration)\r
+      aset.digits=MAXI(lhs->digits, set->digits)+6+4;\r
+      } // non-integer rhs\r
+\r
+     else { // rhs is in-range integer\r
+      if (n==0) {                       // x**0 = 1\r
+        // (0**0 was handled above)\r
+        decNumberZero(res);             // result=1\r
+        *res->lsu=1;                    // ..\r
+        break;}\r
+      // rhs is a non-zero integer\r
+      if (n<0) n=-n;                    // use abs(n)\r
+\r
+      aset=*set;                        // clone the context\r
+      aset.round=DEC_ROUND_HALF_EVEN;   // internally use balanced\r
+      // calculate the working DIGITS\r
+      aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;\r
+      #if DECSUBSET\r
+      if (!set->extended) aset.digits--;     // use classic precision\r
+      #endif\r
+      // it's an error if this is more than can be handled\r
+      if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}\r
+      } // integer path\r
+\r
+    // aset.digits is the count of digits for the accumulator needed\r
+    // if accumulator is too long for local storage, then allocate\r
+    needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);\r
+    // [needbytes also used below if 1/lhs needed]\r
+    if (needbytes>sizeof(dacbuff)) {\r
+      allocdac=(decNumber *)malloc(needbytes);\r
+      if (allocdac==NULL) {   // hopeless -- abandon\r
+        status|=DEC_Insufficient_storage;\r
+        break;}\r
+      dac=allocdac;           // use the allocated space\r
+      }\r
+    // here, aset is set up and accumulator is ready for use\r
+\r
+    if (!useint) {                           // non-integral rhs\r
+      // x ** y; special-case x=1 here as it will otherwise always\r
+      // reduce to integer 1; decLnOp has a fastpath which detects\r
+      // the case of x=1\r
+      decLnOp(dac, lhs, &aset, &status);     // dac=ln(lhs)\r
+      // [no error possible, as lhs 0 already handled]\r
+      if (ISZERO(dac)) {                     // x==1, 1.0, etc.\r
+        // need to return fully-padded 1.0000 etc., but rhsint->1\r
+        *dac->lsu=1;                         // was 0, make int 1\r
+        if (!rhsint) {                       // add padding\r
+          Int shift=set->digits-1;\r
+          dac->digits=decShiftToMost(dac->lsu, 1, shift);\r
+          dac->exponent=-shift;              // make 1.0000...\r
+          status|=DEC_Inexact|DEC_Rounded;   // deemed inexact\r
+          }\r
+        }\r
+       else {\r
+        decMultiplyOp(dac, dac, rhs, &aset, &status);  // dac=dac*rhs\r
+        decExpOp(dac, dac, &aset, &status);            // dac=exp(dac)\r
+        }\r
+      // and drop through for final rounding\r
+      } // non-integer rhs\r
+\r
+     else {                             // carry on with integer\r
+      decNumberZero(dac);               // acc=1\r
+      *dac->lsu=1;                      // ..\r
+\r
+      // if a negative power the constant 1 is needed, and if not subset\r
+      // invert the lhs now rather than inverting the result later\r
+      if (decNumberIsNegative(rhs)) {   // was a **-n [hence digits>0]\r
+        decNumber *inv=invbuff;         // asssume use fixed buffer\r
+        decNumberCopy(&dnOne, dac);     // dnOne=1;  [needed now or later]\r
+        #if DECSUBSET\r
+        if (set->extended) {            // need to calculate 1/lhs\r
+        #endif\r
+          // divide lhs into 1, putting result in dac [dac=1/dac]\r
+          decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);\r
+          // now locate or allocate space for the inverted lhs\r
+          if (needbytes>sizeof(invbuff)) {\r
+            allocinv=(decNumber *)malloc(needbytes);\r
+            if (allocinv==NULL) {       // hopeless -- abandon\r
+              status|=DEC_Insufficient_storage;\r
+              break;}\r
+            inv=allocinv;               // use the allocated space\r
+            }\r
+          // [inv now points to big-enough buffer or allocated storage]\r
+          decNumberCopy(inv, dac);      // copy the 1/lhs\r
+          decNumberCopy(dac, &dnOne);   // restore acc=1\r
+          lhs=inv;                      // .. and go forward with new lhs\r
+        #if DECSUBSET\r
+          }\r
+        #endif\r
+        }\r
+\r
+      // Raise-to-the-power loop...\r
+      seenbit=0;                   // set once a 1-bit is encountered\r
+      for (i=1;;i++){              // for each bit [top bit ignored]\r
+        // abandon if had overflow or terminal underflow\r
+        if (status & (DEC_Overflow|DEC_Underflow)) { // interesting?\r
+          if (status&DEC_Overflow || ISZERO(dac)) break;\r
+          }\r
+        // [the following two lines revealed an optimizer bug in a C++\r
+        // compiler, with symptom: 5**3 -> 25, when n=n+n was used]\r
+        n=n<<1;                    // move next bit to testable position\r
+        if (n<0) {                 // top bit is set\r
+          seenbit=1;               // OK, significant bit seen\r
+          decMultiplyOp(dac, dac, lhs, &aset, &status); // dac=dac*x\r
+          }\r
+        if (i==31) break;          // that was the last bit\r
+        if (!seenbit) continue;    // no need to square 1\r
+        decMultiplyOp(dac, dac, dac, &aset, &status); // dac=dac*dac [square]\r
+        } /*i*/ // 32 bits\r
+\r
+      // complete internal overflow or underflow processing\r
+      if (status & (DEC_Overflow|DEC_Underflow)) {\r
+        #if DECSUBSET\r
+        // If subset, and power was negative, reverse the kind of -erflow\r
+        // [1/x not yet done]\r
+        if (!set->extended && decNumberIsNegative(rhs)) {\r
+          if (status & DEC_Overflow)\r
+            status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;\r
+           else { // trickier -- Underflow may or may not be set\r
+            status&=~(DEC_Underflow | DEC_Subnormal); // [one or both]\r
+            status|=DEC_Overflow;\r
+            }\r
+          }\r
+        #endif\r
+        dac->bits=(dac->bits & ~DECNEG) | bits; // force correct sign\r
+        // round subnormals [to set.digits rather than aset.digits]\r
+        // or set overflow result similarly as required\r
+        decFinalize(dac, set, &residue, &status);\r
+        decNumberCopy(res, dac);   // copy to result (is now OK length)\r
+        break;\r
+        }\r
+\r
+      #if DECSUBSET\r
+      if (!set->extended &&                  // subset math\r
+          decNumberIsNegative(rhs)) {        // was a **-n [hence digits>0]\r
+        // so divide result into 1 [dac=1/dac]\r
+        decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);\r
+        }\r
+      #endif\r
+      } // rhs integer path\r
+\r
+    // reduce result to the requested length and copy to result\r
+    decCopyFit(res, dac, set, &residue, &status);\r
+    decFinish(res, set, &residue, &status);  // final cleanup\r
+    #if DECSUBSET\r
+    if (!set->extended) decTrim(res, set, 0, 1, &dropped); // trailing zeros\r
+    #endif\r
+    } while(0);                         // end protected\r
+\r
+  if (allocdac!=NULL) free(allocdac);   // drop any storage used\r
+  if (allocinv!=NULL) free(allocinv);   // ..\r
+  #if DECSUBSET\r
+  if (alloclhs!=NULL) free(alloclhs);   // ..\r
+  if (allocrhs!=NULL) free(allocrhs);   // ..\r
+  #endif\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberPower\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberQuantize -- force exponent to requested value             */\r
+/*                                                                    */\r
+/*   This computes C = op(A, B), where op adjusts the coefficient     */\r
+/*   of C (by rounding or shifting) such that the exponent (-scale)   */\r
+/*   of C has exponent of B.  The numerical value of C will equal A,  */\r
+/*   except for the effects of any rounding that occurred.            */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A or B                           */\r
+/*   lhs is A, the number to adjust                                   */\r
+/*   rhs is B, the number with exponent to match                      */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Unless there is an error or the result is infinite, the exponent   */\r
+/* after the operation is guaranteed to be equal to that of B.        */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,\r
+                              const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decQuantizeOp(res, lhs, rhs, set, 1, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberQuantize\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberReduce -- remove trailing zeros                           */\r
+/*                                                                    */\r
+/*   This computes C = 0 + A, and normalizes the result               */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+// Previously known as Normalize\r
+decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,\r
+                               decContext *set) {\r
+  return decNumberReduce(res, rhs, set);\r
+  } // decNumberNormalize\r
+\r
+decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,\r
+                            decContext *set) {\r
+  #if DECSUBSET\r
+  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated\r
+  #endif\r
+  uInt status=0;                   // as usual\r
+  Int  residue=0;                  // as usual\r
+  Int  dropped;                    // work\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                             // protect allocated storage\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operand and set lostDigits status, as needed\r
+      if (rhs->digits>set->digits) {\r
+        allocrhs=decRoundOperand(rhs, set, &status);\r
+        if (allocrhs==NULL) break;\r
+        rhs=allocrhs;\r
+        }\r
+      }\r
+    #endif\r
+    // [following code does not require input rounding]\r
+\r
+    // Infinities copy through; NaNs need usual treatment\r
+    if (decNumberIsNaN(rhs)) {\r
+      decNaNs(res, rhs, NULL, set, &status);\r
+      break;\r
+      }\r
+\r
+    // reduce result to the requested length and copy to result\r
+    decCopyFit(res, rhs, set, &residue, &status); // copy & round\r
+    decFinish(res, set, &residue, &status);       // cleanup/set flags\r
+    decTrim(res, set, 1, 0, &dropped);            // normalize in place\r
+                                                  // [may clamp]\r
+    } while(0);                              // end protected\r
+\r
+  #if DECSUBSET\r
+  if (allocrhs !=NULL) free(allocrhs);       // ..\r
+  #endif\r
+  if (status!=0) decStatus(res, status, set);// then report status\r
+  return res;\r
+  } // decNumberReduce\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberRescale -- force exponent to requested value              */\r
+/*                                                                    */\r
+/*   This computes C = op(A, B), where op adjusts the coefficient     */\r
+/*   of C (by rounding or shifting) such that the exponent (-scale)   */\r
+/*   of C has the value B.  The numerical value of C will equal A,    */\r
+/*   except for the effects of any rounding that occurred.            */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A or B                           */\r
+/*   lhs is A, the number to adjust                                   */\r
+/*   rhs is B, the requested exponent                                 */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Unless there is an error or the result is infinite, the exponent   */\r
+/* after the operation is guaranteed to be equal to B.                */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,\r
+                             const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decQuantizeOp(res, lhs, rhs, set, 0, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberRescale\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberRemainder -- divide and return remainder                  */\r
+/*                                                                    */\r
+/*   This computes C = A % B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,\r
+                               const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decDivideOp(res, lhs, rhs, set, REMAINDER, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberRemainder\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberRemainderNear -- divide and return remainder from nearest */\r
+/*                                                                    */\r
+/*   This computes C = A % B, where % is the IEEE remainder operator  */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,\r
+                                   const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+  decDivideOp(res, lhs, rhs, set, REMNEAR, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberRemainderNear\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberRotate -- rotate the coefficient of a Number left/right   */\r
+/*                                                                    */\r
+/*   This computes C = A rot B  (in base ten and rotating set->digits */\r
+/*   digits).                                                         */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B, the number of digits to rotate (-ve to right)          */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* The digits of the coefficient of A are rotated to the left (if B   */\r
+/* is positive) or to the right (if B is negative) without adjusting  */\r
+/* the exponent or the sign of A.  If lhs->digits is less than        */\r
+/* set->digits the coefficient is padded with zeros on the left       */\r
+/* before the rotate.  Any leading zeros in the result are removed    */\r
+/* as usual.                                                          */\r
+/*                                                                    */\r
+/* B must be an integer (q=0) and in the range -set->digits through   */\r
+/* +set->digits.                                                      */\r
+/* C must have space for set->digits digits.                          */\r
+/* NaNs are propagated as usual.  Infinities are unaffected (but      */\r
+/* B must be valid).  No status is set unless B is invalid or an      */\r
+/* operand is an sNaN.                                                */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,\r
+                           const decNumber *rhs, decContext *set) {\r
+  uInt status=0;              // accumulator\r
+  Int  rotate;                // rhs as an Int\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  // NaNs propagate as normal\r
+  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))\r
+    decNaNs(res, lhs, rhs, set, &status);\r
+   // rhs must be an integer\r
+   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)\r
+    status=DEC_Invalid_operation;\r
+   else { // both numeric, rhs is an integer\r
+    rotate=decGetInt(rhs);                   // [cannot fail]\r
+    if (rotate==BADINT                       // something bad ..\r
+     || rotate==BIGODD || rotate==BIGEVEN    // .. very big ..\r
+     || abs(rotate)>set->digits)             // .. or out of range\r
+      status=DEC_Invalid_operation;\r
+     else {                                  // rhs is OK\r
+      decNumberCopy(res, lhs);\r
+      // convert -ve rotate to equivalent positive rotation\r
+      if (rotate<0) rotate=set->digits+rotate;\r
+      if (rotate!=0 && rotate!=set->digits   // zero or full rotation\r
+       && !decNumberIsInfinite(res)) {       // lhs was infinite\r
+        // left-rotate to do; 0 < rotate < set->digits\r
+        uInt units, shift;                   // work\r
+        uInt msudigits;                      // digits in result msu\r
+        Unit *msu=res->lsu+D2U(res->digits)-1;    // current msu\r
+        Unit *msumax=res->lsu+D2U(set->digits)-1; // rotation msu\r
+        for (msu++; msu<=msumax; msu++) *msu=0;   // ensure high units=0\r
+        res->digits=set->digits;                  // now full-length\r
+        msudigits=MSUDIGITS(res->digits);         // actual digits in msu\r
+\r
+        // rotation here is done in-place, in three steps\r
+        // 1. shift all to least up to one unit to unit-align final\r
+        //    lsd [any digits shifted out are rotated to the left,\r
+        //    abutted to the original msd (which may require split)]\r
+        //\r
+        //    [if there are no whole units left to rotate, the\r
+        //    rotation is now complete]\r
+        //\r
+        // 2. shift to least, from below the split point only, so that\r
+        //    the final msd is in the right place in its Unit [any\r
+        //    digits shifted out will fit exactly in the current msu,\r
+        //    left aligned, no split required]\r
+        //\r
+        // 3. rotate all the units by reversing left part, right\r
+        //    part, and then whole\r
+        //\r
+        // example: rotate right 8 digits (2 units + 2), DECDPUN=3.\r
+        //\r
+        //   start: 00a bcd efg hij klm npq\r
+        //\r
+        //      1a  000 0ab cde fgh|ijk lmn [pq saved]\r
+        //      1b  00p qab cde fgh|ijk lmn\r
+        //\r
+        //      2a  00p qab cde fgh|00i jkl [mn saved]\r
+        //      2b  mnp qab cde fgh|00i jkl\r
+        //\r
+        //      3a  fgh cde qab mnp|00i jkl\r
+        //      3b  fgh cde qab mnp|jkl 00i\r
+        //      3c  00i jkl mnp qab cde fgh\r
+\r
+        // Step 1: amount to shift is the partial right-rotate count\r
+        rotate=set->digits-rotate;      // make it right-rotate\r
+        units=rotate/DECDPUN;           // whole units to rotate\r
+        shift=rotate%DECDPUN;           // left-over digits count\r
+        if (shift>0) {                  // not an exact number of units\r
+          uInt save=res->lsu[0]%powers[shift];    // save low digit(s)\r
+          decShiftToLeast(res->lsu, D2U(res->digits), shift);\r
+          if (shift>msudigits) {        // msumax-1 needs >0 digits\r
+            uInt rem=save%powers[shift-msudigits];// split save\r
+            *msumax=(Unit)(save/powers[shift-msudigits]); // and insert\r
+            *(msumax-1)=*(msumax-1)\r
+                       +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); // ..\r
+            }\r
+           else { // all fits in msumax\r
+            *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); // [maybe *1]\r
+            }\r
+          } // digits shift needed\r
+\r
+        // If whole units to rotate...\r
+        if (units>0) {                  // some to do\r
+          // Step 2: the units to touch are the whole ones in rotate,\r
+          //   if any, and the shift is DECDPUN-msudigits (which may be\r
+          //   0, again)\r
+          shift=DECDPUN-msudigits;\r
+          if (shift>0) {                // not an exact number of units\r
+            uInt save=res->lsu[0]%powers[shift];  // save low digit(s)\r
+            decShiftToLeast(res->lsu, units, shift);\r
+            *msumax=*msumax+(Unit)(save*powers[msudigits]);\r
+            } // partial shift needed\r
+\r
+          // Step 3: rotate the units array using triple reverse\r
+          // (reversing is easy and fast)\r
+          decReverse(res->lsu+units, msumax);     // left part\r
+          decReverse(res->lsu, res->lsu+units-1); // right part\r
+          decReverse(res->lsu, msumax);           // whole\r
+          } // whole units to rotate\r
+        // the rotation may have left an undetermined number of zeros\r
+        // on the left, so true length needs to be calculated\r
+        res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);\r
+        } // rotate needed\r
+      } // rhs OK\r
+    } // numerics\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberRotate\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberSameQuantum -- test for equal exponents                   */\r
+/*                                                                    */\r
+/*   res is the result number, which will contain either 0 or 1       */\r
+/*   lhs is a number to test                                          */\r
+/*   rhs is the second (usually a pattern)                            */\r
+/*                                                                    */\r
+/* No errors are possible and no context is needed.                   */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,\r
+                                 const decNumber *rhs) {\r
+  Unit ret=0;                      // return value\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;\r
+  #endif\r
+\r
+  if (SPECIALARGS) {\r
+    if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;\r
+     else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;\r
+     // [anything else with a special gives 0]\r
+    }\r
+   else if (lhs->exponent==rhs->exponent) ret=1;\r
+\r
+  decNumberZero(res);              // OK to overwrite an operand now\r
+  *res->lsu=ret;\r
+  return res;\r
+  } // decNumberSameQuantum\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberScaleB -- multiply by a power of 10                       */\r
+/*                                                                    */\r
+/* This computes C = A x 10**B where B is an integer (q=0) with       */\r
+/* maximum magnitude 2*(emax+digits)                                  */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A or B                           */\r
+/*   lhs is A, the number to adjust                                   */\r
+/*   rhs is B, the requested power of ten to use                      */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* The result may underflow or overflow.                              */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,\r
+                            const decNumber *rhs, decContext *set) {\r
+  Int  reqexp;                // requested exponent change [B]\r
+  uInt status=0;              // accumulator\r
+  Int  residue;               // work\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  // Handle special values except lhs infinite\r
+  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))\r
+    decNaNs(res, lhs, rhs, set, &status);\r
+    // rhs must be an integer\r
+   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)\r
+    status=DEC_Invalid_operation;\r
+   else {\r
+    // lhs is a number; rhs is a finite with q==0\r
+    reqexp=decGetInt(rhs);                   // [cannot fail]\r
+    // maximum range is larger than getInt can handle, so this is\r
+    // more restrictive than the specification\r
+    if (reqexp==BADINT                       // something bad ..\r
+     || reqexp==BIGODD || reqexp==BIGEVEN    // it was huge\r
+     || (abs(reqexp)+1)/2>(set->digits+set->emax)) // .. or out of range\r
+      status=DEC_Invalid_operation;\r
+     else {                                  // rhs is OK\r
+      decNumberCopy(res, lhs);               // all done if infinite lhs\r
+      if (!decNumberIsInfinite(res)) {       // prepare to scale\r
+        Int exp=res->exponent;               // save for overflow test\r
+        res->exponent+=reqexp;               // adjust the exponent\r
+        if (((exp^reqexp)>=0)                // same sign ...\r
+         && ((exp^res->exponent)<0)) {       // .. but result had different\r
+          // the calculation overflowed, so force right treatment\r
+          if (exp<0) res->exponent=DEC_MIN_EMIN-DEC_MAX_DIGITS;\r
+           else      res->exponent=DEC_MAX_EMAX+1;\r
+          }\r
+        residue=0;\r
+        decFinalize(res, set, &residue, &status); // final check\r
+        } // finite LHS\r
+      } // rhs OK\r
+    } // rhs finite\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberScaleB\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberShift -- shift the coefficient of a Number left or right  */\r
+/*                                                                    */\r
+/*   This computes C = A << B or C = A >> -B  (in base ten).          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B, the number of digits to shift (-ve to right)           */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* The digits of the coefficient of A are shifted to the left (if B   */\r
+/* is positive) or to the right (if B is negative) without adjusting  */\r
+/* the exponent or the sign of A.                                     */\r
+/*                                                                    */\r
+/* B must be an integer (q=0) and in the range -set->digits through   */\r
+/* +set->digits.                                                      */\r
+/* C must have space for set->digits digits.                          */\r
+/* NaNs are propagated as usual.  Infinities are unaffected (but      */\r
+/* B must be valid).  No status is set unless B is invalid or an      */\r
+/* operand is an sNaN.                                                */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberShift(decNumber *res, const decNumber *lhs,\r
+                           const decNumber *rhs, decContext *set) {\r
+  uInt status=0;              // accumulator\r
+  Int  shift;                 // rhs as an Int\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  // NaNs propagate as normal\r
+  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))\r
+    decNaNs(res, lhs, rhs, set, &status);\r
+   // rhs must be an integer\r
+   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)\r
+    status=DEC_Invalid_operation;\r
+   else { // both numeric, rhs is an integer\r
+    shift=decGetInt(rhs);                    // [cannot fail]\r
+    if (shift==BADINT                        // something bad ..\r
+     || shift==BIGODD || shift==BIGEVEN      // .. very big ..\r
+     || abs(shift)>set->digits)              // .. or out of range\r
+      status=DEC_Invalid_operation;\r
+     else {                                  // rhs is OK\r
+      decNumberCopy(res, lhs);\r
+      if (shift!=0 && !decNumberIsInfinite(res)) { // something to do\r
+        if (shift>0) {                       // to left\r
+          if (shift==set->digits) {          // removing all\r
+            *res->lsu=0;                     // so place 0\r
+            res->digits=1;                   // ..\r
+            }\r
+           else {                            //\r
+            // first remove leading digits if necessary\r
+            if (res->digits+shift>set->digits) {\r
+              decDecap(res, res->digits+shift-set->digits);\r
+              // that updated res->digits; may have gone to 1 (for a\r
+              // single digit or for zero\r
+              }\r
+            if (res->digits>1 || *res->lsu)  // if non-zero..\r
+              res->digits=decShiftToMost(res->lsu, res->digits, shift);\r
+            } // partial left\r
+          } // left\r
+         else { // to right\r
+          if (-shift>=res->digits) {         // discarding all\r
+            *res->lsu=0;                     // so place 0\r
+            res->digits=1;                   // ..\r
+            }\r
+           else {\r
+            decShiftToLeast(res->lsu, D2U(res->digits), -shift);\r
+            res->digits-=(-shift);\r
+            }\r
+          } // to right\r
+        } // non-0 non-Inf shift\r
+      } // rhs OK\r
+    } // numerics\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberShift\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberSquareRoot -- square root operator                        */\r
+/*                                                                    */\r
+/*   This computes C = squareroot(A)                                  */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context; note that rounding mode has no effect        */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+/* This uses the following varying-precision algorithm in:            */\r
+/*                                                                    */\r
+/*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */\r
+/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */\r
+/*   pp229-237, ACM, September 1985.                                  */\r
+/*                                                                    */\r
+/* The square-root is calculated using Newton's method, after which   */\r
+/* a check is made to ensure the result is correctly rounded.         */\r
+/*                                                                    */\r
+/* % [Reformatted original Numerical Turing source code follows.]     */\r
+/* function sqrt(x : real) : real                                     */\r
+/* % sqrt(x) returns the properly rounded approximation to the square */\r
+/* % root of x, in the precision of the calling environment, or it    */\r
+/* % fails if x < 0.                                                  */\r
+/* % t e hull and a abrham, august, 1984                              */\r
+/* if x <= 0 then                                                     */\r
+/*   if x < 0 then                                                    */\r
+/*     assert false                                                   */\r
+/*   else                                                             */\r
+/*     result 0                                                       */\r
+/*   end if                                                           */\r
+/* end if                                                             */\r
+/* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */\r
+/* var e := getexp(x)     % exponent part of x                        */\r
+/* var approx : real                                                  */\r
+/* if e mod 2 = 0  then                                               */\r
+/*   approx := .259 + .819 * f   % approx to root of f                */\r
+/* else                                                               */\r
+/*   f := f/l0                   % adjustments                        */\r
+/*   e := e + 1                  %   for odd                          */\r
+/*   approx := .0819 + 2.59 * f  %   exponent                         */\r
+/* end if                                                             */\r
+/*                                                                    */\r
+/* var p:= 3                                                          */\r
+/* const maxp := currentprecision + 2                                 */\r
+/* loop                                                               */\r
+/*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */\r
+/*   precision p                                                      */\r
+/*   approx := .5 * (approx + f/approx)                               */\r
+/*   exit when p = maxp                                               */\r
+/* end loop                                                           */\r
+/*                                                                    */\r
+/* % approx is now within 1 ulp of the properly rounded square root   */\r
+/* % of f; to ensure proper rounding, compare squares of (approx -    */\r
+/* % l/2 ulp) and (approx + l/2 ulp) with f.                          */\r
+/* p := currentprecision                                              */\r
+/* begin                                                              */\r
+/*   precision p + 2                                                  */\r
+/*   const approxsubhalf := approx - setexp(.5, -p)                   */\r
+/*   if mulru(approxsubhalf, approxsubhalf) > f then                  */\r
+/*     approx := approx - setexp(.l, -p + 1)                          */\r
+/*   else                                                             */\r
+/*     const approxaddhalf := approx + setexp(.5, -p)                 */\r
+/*     if mulrd(approxaddhalf, approxaddhalf) < f then                */\r
+/*       approx := approx + setexp(.l, -p + 1)                        */\r
+/*     end if                                                         */\r
+/*   end if                                                           */\r
+/* end                                                                */\r
+/* result setexp(approx, e div 2)  % fix exponent                     */\r
+/* end sqrt                                                           */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,\r
+                                decContext *set) {\r
+  decContext workset, approxset;   // work contexts\r
+  decNumber dzero;                 // used for constant zero\r
+  Int  maxp;                       // largest working precision\r
+  Int  workp;                      // working precision\r
+  Int  residue=0;                  // rounding residue\r
+  uInt status=0, ignore=0;         // status accumulators\r
+  uInt rstatus;                    // ..\r
+  Int  exp;                        // working exponent\r
+  Int  ideal;                      // ideal (preferred) exponent\r
+  Int  needbytes;                  // work\r
+  Int  dropped;                    // ..\r
+\r
+  #if DECSUBSET\r
+  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated\r
+  #endif\r
+  // buffer for f [needs +1 in case DECBUFFER 0]\r
+  decNumber buff[D2N(DECBUFFER+1)];\r
+  // buffer for a [needs +2 to match likely maxp]\r
+  decNumber bufa[D2N(DECBUFFER+2)];\r
+  // buffer for temporary, b [must be same size as a]\r
+  decNumber bufb[D2N(DECBUFFER+2)];\r
+  decNumber *allocbuff=NULL;       // -> allocated buff, iff allocated\r
+  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated\r
+  decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated\r
+  decNumber *f=buff;               // reduced fraction\r
+  decNumber *a=bufa;               // approximation to result\r
+  decNumber *b=bufb;               // intermediate result\r
+  // buffer for temporary variable, up to 3 digits\r
+  decNumber buft[D2N(3)];\r
+  decNumber *t=buft;               // up-to-3-digit constant or work\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                             // protect allocated storage\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operand and set lostDigits status, as needed\r
+      if (rhs->digits>set->digits) {\r
+        allocrhs=decRoundOperand(rhs, set, &status);\r
+        if (allocrhs==NULL) break;\r
+        // [Note: 'f' allocation below could reuse this buffer if\r
+        // used, but as this is rare they are kept separate for clarity.]\r
+        rhs=allocrhs;\r
+        }\r
+      }\r
+    #endif\r
+    // [following code does not require input rounding]\r
+\r
+    // handle infinities and NaNs\r
+    if (SPECIALARG) {\r
+      if (decNumberIsInfinite(rhs)) {         // an infinity\r
+        if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;\r
+         else decNumberCopy(res, rhs);        // +Infinity\r
+        }\r
+       else decNaNs(res, rhs, NULL, set, &status); // a NaN\r
+      break;\r
+      }\r
+\r
+    // calculate the ideal (preferred) exponent [floor(exp/2)]\r
+    // [It would be nicer to write: ideal=rhs->exponent>>1, but this\r
+    // generates a compiler warning.  Generated code is the same.]\r
+    ideal=(rhs->exponent&~1)/2;         // target\r
+\r
+    // handle zeros\r
+    if (ISZERO(rhs)) {\r
+      decNumberCopy(res, rhs);          // could be 0 or -0\r
+      res->exponent=ideal;              // use the ideal [safe]\r
+      // use decFinish to clamp any out-of-range exponent, etc.\r
+      decFinish(res, set, &residue, &status);\r
+      break;\r
+      }\r
+\r
+    // any other -x is an oops\r
+    if (decNumberIsNegative(rhs)) {\r
+      status|=DEC_Invalid_operation;\r
+      break;\r
+      }\r
+\r
+    // space is needed for three working variables\r
+    //   f -- the same precision as the RHS, reduced to 0.01->0.99...\r
+    //   a -- Hull's approximation -- precision, when assigned, is\r
+    //        currentprecision+1 or the input argument precision,\r
+    //        whichever is larger (+2 for use as temporary)\r
+    //   b -- intermediate temporary result (same size as a)\r
+    // if any is too long for local storage, then allocate\r
+    workp=MAXI(set->digits+1, rhs->digits);  // actual rounding precision\r
+    workp=MAXI(workp, 7);                    // at least 7 for low cases\r
+    maxp=workp+2;                            // largest working precision\r
+\r
+    needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);\r
+    if (needbytes>(Int)sizeof(buff)) {\r
+      allocbuff=(decNumber *)malloc(needbytes);\r
+      if (allocbuff==NULL) {  // hopeless -- abandon\r
+        status|=DEC_Insufficient_storage;\r
+        break;}\r
+      f=allocbuff;            // use the allocated space\r
+      }\r
+    // a and b both need to be able to hold a maxp-length number\r
+    needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);\r
+    if (needbytes>(Int)sizeof(bufa)) {            // [same applies to b]\r
+      allocbufa=(decNumber *)malloc(needbytes);\r
+      allocbufb=(decNumber *)malloc(needbytes);\r
+      if (allocbufa==NULL || allocbufb==NULL) {   // hopeless\r
+        status|=DEC_Insufficient_storage;\r
+        break;}\r
+      a=allocbufa;            // use the allocated spaces\r
+      b=allocbufb;            // ..\r
+      }\r
+\r
+    // copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1\r
+    decNumberCopy(f, rhs);\r
+    exp=f->exponent+f->digits;               // adjusted to Hull rules\r
+    f->exponent=-(f->digits);                // to range\r
+\r
+    // set up working context\r
+    decContextDefault(&workset, DEC_INIT_DECIMAL64);\r
+    workset.emax=DEC_MAX_EMAX;\r
+    workset.emin=DEC_MIN_EMIN;\r
+\r
+    // [Until further notice, no error is possible and status bits\r
+    // (Rounded, etc.) should be ignored, not accumulated.]\r
+\r
+    // Calculate initial approximation, and allow for odd exponent\r
+    workset.digits=workp;                    // p for initial calculation\r
+    t->bits=0; t->digits=3;\r
+    a->bits=0; a->digits=3;\r
+    if ((exp & 1)==0) {                      // even exponent\r
+      // Set t=0.259, a=0.819\r
+      t->exponent=-3;\r
+      a->exponent=-3;\r
+      #if DECDPUN>=3\r
+        t->lsu[0]=259;\r
+        a->lsu[0]=819;\r
+      #elif DECDPUN==2\r
+        t->lsu[0]=59; t->lsu[1]=2;\r
+        a->lsu[0]=19; a->lsu[1]=8;\r
+      #else\r
+        t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;\r
+        a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;\r
+      #endif\r
+      }\r
+     else {                                  // odd exponent\r
+      // Set t=0.0819, a=2.59\r
+      f->exponent--;                         // f=f/10\r
+      exp++;                                 // e=e+1\r
+      t->exponent=-4;\r
+      a->exponent=-2;\r
+      #if DECDPUN>=3\r
+        t->lsu[0]=819;\r
+        a->lsu[0]=259;\r
+      #elif DECDPUN==2\r
+        t->lsu[0]=19; t->lsu[1]=8;\r
+        a->lsu[0]=59; a->lsu[1]=2;\r
+      #else\r
+        t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;\r
+        a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;\r
+      #endif\r
+      }\r
+\r
+    decMultiplyOp(a, a, f, &workset, &ignore);    // a=a*f\r
+    decAddOp(a, a, t, &workset, 0, &ignore);      // ..+t\r
+    // [a is now the initial approximation for sqrt(f), calculated with\r
+    // currentprecision, which is also a's precision.]\r
+\r
+    // the main calculation loop\r
+    decNumberZero(&dzero);                   // make 0\r
+    decNumberZero(t);                        // set t = 0.5\r
+    t->lsu[0]=5;                             // ..\r
+    t->exponent=-1;                          // ..\r
+    workset.digits=3;                        // initial p\r
+    for (; workset.digits<maxp;) {\r
+      // set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp]\r
+      workset.digits=MINI(workset.digits*2-2, maxp);\r
+      // a = 0.5 * (a + f/a)\r
+      // [calculated at p then rounded to currentprecision]\r
+      decDivideOp(b, f, a, &workset, DIVIDE, &ignore); // b=f/a\r
+      decAddOp(b, b, a, &workset, 0, &ignore);         // b=b+a\r
+      decMultiplyOp(a, b, t, &workset, &ignore);       // a=b*0.5\r
+      } // loop\r
+\r
+    // Here, 0.1 <= a < 1 [Hull], and a has maxp digits\r
+    // now reduce to length, etc.; this needs to be done with a\r
+    // having the correct exponent so as to handle subnormals\r
+    // correctly\r
+    approxset=*set;                          // get emin, emax, etc.\r
+    approxset.round=DEC_ROUND_HALF_EVEN;\r
+    a->exponent+=exp/2;                      // set correct exponent\r
+    rstatus=0;                               // clear status\r
+    residue=0;                               // .. and accumulator\r
+    decCopyFit(a, a, &approxset, &residue, &rstatus);  // reduce (if needed)\r
+    decFinish(a, &approxset, &residue, &rstatus);      // clean and finalize\r
+\r
+    // Overflow was possible if the input exponent was out-of-range,\r
+    // in which case quit\r
+    if (rstatus&DEC_Overflow) {\r
+      status=rstatus;                        // use the status as-is\r
+      decNumberCopy(res, a);                 // copy to result\r
+      break;\r
+      }\r
+\r
+    // Preserve status except Inexact/Rounded\r
+    status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));\r
+\r
+    // Carry out the Hull correction\r
+    a->exponent-=exp/2;                      // back to 0.1->1\r
+\r
+    // a is now at final precision and within 1 ulp of the properly\r
+    // rounded square root of f; to ensure proper rounding, compare\r
+    // squares of (a - l/2 ulp) and (a + l/2 ulp) with f.\r
+    // Here workset.digits=maxp and t=0.5, and a->digits determines\r
+    // the ulp\r
+    workset.digits--;                             // maxp-1 is OK now\r
+    t->exponent=-a->digits-1;                     // make 0.5 ulp\r
+    decAddOp(b, a, t, &workset, DECNEG, &ignore); // b = a - 0.5 ulp\r
+    workset.round=DEC_ROUND_UP;\r
+    decMultiplyOp(b, b, b, &workset, &ignore);    // b = mulru(b, b)\r
+    decCompareOp(b, f, b, &workset, COMPARE, &ignore); // b ? f, reversed\r
+    if (decNumberIsNegative(b)) {                 // f < b [i.e., b > f]\r
+      // this is the more common adjustment, though both are rare\r
+      t->exponent++;                              // make 1.0 ulp\r
+      t->lsu[0]=1;                                // ..\r
+      decAddOp(a, a, t, &workset, DECNEG, &ignore); // a = a - 1 ulp\r
+      // assign to approx [round to length]\r
+      approxset.emin-=exp/2;                      // adjust to match a\r
+      approxset.emax-=exp/2;\r
+      decAddOp(a, &dzero, a, &approxset, 0, &ignore);\r
+      }\r
+     else {\r
+      decAddOp(b, a, t, &workset, 0, &ignore);    // b = a + 0.5 ulp\r
+      workset.round=DEC_ROUND_DOWN;\r
+      decMultiplyOp(b, b, b, &workset, &ignore);  // b = mulrd(b, b)\r
+      decCompareOp(b, b, f, &workset, COMPARE, &ignore);   // b ? f\r
+      if (decNumberIsNegative(b)) {               // b < f\r
+        t->exponent++;                            // make 1.0 ulp\r
+        t->lsu[0]=1;                              // ..\r
+        decAddOp(a, a, t, &workset, 0, &ignore);  // a = a + 1 ulp\r
+        // assign to approx [round to length]\r
+        approxset.emin-=exp/2;                    // adjust to match a\r
+        approxset.emax-=exp/2;\r
+        decAddOp(a, &dzero, a, &approxset, 0, &ignore);\r
+        }\r
+      }\r
+    // [no errors are possible in the above, and rounding/inexact during\r
+    // estimation are irrelevant, so status was not accumulated]\r
+\r
+    // Here, 0.1 <= a < 1  (still), so adjust back\r
+    a->exponent+=exp/2;                      // set correct exponent\r
+\r
+    // count droppable zeros [after any subnormal rounding] by\r
+    // trimming a copy\r
+    decNumberCopy(b, a);\r
+    decTrim(b, set, 1, 1, &dropped);         // [drops trailing zeros]\r
+\r
+    // Set Inexact and Rounded.  The answer can only be exact if\r
+    // it is short enough so that squaring it could fit in workp\r
+    // digits, so this is the only (relatively rare) condition that\r
+    // a careful check is needed\r
+    if (b->digits*2-1 > workp) {             // cannot fit\r
+      status|=DEC_Inexact|DEC_Rounded;\r
+      }\r
+     else {                                  // could be exact/unrounded\r
+      uInt mstatus=0;                        // local status\r
+      decMultiplyOp(b, b, b, &workset, &mstatus); // try the multiply\r
+      if (mstatus&DEC_Overflow) {            // result just won't fit\r
+        status|=DEC_Inexact|DEC_Rounded;\r
+        }\r
+       else {                                // plausible\r
+        decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); // b ? rhs\r
+        if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; // not equal\r
+         else {                              // is Exact\r
+          // here, dropped is the count of trailing zeros in 'a'\r
+          // use closest exponent to ideal...\r
+          Int todrop=ideal-a->exponent;      // most that can be dropped\r
+          if (todrop<0) status|=DEC_Rounded; // ideally would add 0s\r
+           else {                            // unrounded\r
+            // there are some to drop, but emax may not allow all\r
+            Int maxexp=set->emax-set->digits+1;\r
+            Int maxdrop=maxexp-a->exponent;\r
+            if (todrop>maxdrop && set->clamp) { // apply clamping\r
+              todrop=maxdrop;\r
+              status|=DEC_Clamped;\r
+              }\r
+            if (dropped<todrop) {            // clamp to those available\r
+              todrop=dropped;\r
+              status|=DEC_Clamped;\r
+              }\r
+            if (todrop>0) {                  // have some to drop\r
+              decShiftToLeast(a->lsu, D2U(a->digits), todrop);\r
+              a->exponent+=todrop;           // maintain numerical value\r
+              a->digits-=todrop;             // new length\r
+              }\r
+            }\r
+          }\r
+        }\r
+      }\r
+\r
+    // double-check Underflow, as perhaps the result could not have\r
+    // been subnormal (initial argument too big), or it is now Exact\r
+    if (status&DEC_Underflow) {\r
+      Int ae=rhs->exponent+rhs->digits-1;    // adjusted exponent\r
+      // check if truly subnormal\r
+      #if DECEXTFLAG                         // DEC_Subnormal too\r
+        if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);\r
+      #else\r
+        if (ae>=set->emin*2) status&=~DEC_Underflow;\r
+      #endif\r
+      // check if truly inexact\r
+      if (!(status&DEC_Inexact)) status&=~DEC_Underflow;\r
+      }\r
+\r
+    decNumberCopy(res, a);                   // a is now the result\r
+    } while(0);                              // end protected\r
+\r
+  if (allocbuff!=NULL) free(allocbuff);      // drop any storage used\r
+  if (allocbufa!=NULL) free(allocbufa);      // ..\r
+  if (allocbufb!=NULL) free(allocbufb);      // ..\r
+  #if DECSUBSET\r
+  if (allocrhs !=NULL) free(allocrhs);       // ..\r
+  #endif\r
+  if (status!=0) decStatus(res, status, set);// then report status\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberSquareRoot\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberSubtract -- subtract two Numbers                          */\r
+/*                                                                    */\r
+/*   This computes C = A - B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,\r
+                              const decNumber *rhs, decContext *set) {\r
+  uInt status=0;                        // accumulator\r
+\r
+  decAddOp(res, lhs, rhs, set, DECNEG, &status);\r
+  if (status!=0) decStatus(res, status, set);\r
+  #if DECCHECK\r
+  decCheckInexact(res, set);\r
+  #endif\r
+  return res;\r
+  } // decNumberSubtract\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberToIntegralExact -- round-to-integral-value with InExact   */\r
+/* decNumberToIntegralValue -- round-to-integral-value                */\r
+/*                                                                    */\r
+/*   res is the result                                                */\r
+/*   rhs is input number                                              */\r
+/*   set is the context                                               */\r
+/*                                                                    */\r
+/* res must have space for any value of rhs.                          */\r
+/*                                                                    */\r
+/* This implements the IEEE special operators and therefore treats    */\r
+/* special values as valid.  For finite numbers it returns            */\r
+/* rescale(rhs, 0) if rhs->exponent is <0.                            */\r
+/* Otherwise the result is rhs (so no error is possible, except for   */\r
+/* sNaN).                                                             */\r
+/*                                                                    */\r
+/* The context is used for rounding mode and status after sNaN, but   */\r
+/* the digits setting is ignored.  The Exact version will signal      */\r
+/* Inexact if the result differs numerically from rhs; the other      */\r
+/* never signals Inexact.                                             */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,\r
+                                     decContext *set) {\r
+  decNumber dn;\r
+  decContext workset;              // working context\r
+  uInt status=0;                   // accumulator\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  // handle infinities and NaNs\r
+  if (SPECIALARG) {\r
+    if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); // an Infinity\r
+     else decNaNs(res, rhs, NULL, set, &status); // a NaN\r
+    }\r
+   else { // finite\r
+    // have a finite number; no error possible (res must be big enough)\r
+    if (rhs->exponent>=0) return decNumberCopy(res, rhs);\r
+    // that was easy, but if negative exponent there is work to do...\r
+    workset=*set;                  // clone rounding, etc.\r
+    workset.digits=rhs->digits;    // no length rounding\r
+    workset.traps=0;               // no traps\r
+    decNumberZero(&dn);            // make a number with exponent 0\r
+    decNumberQuantize(res, rhs, &dn, &workset);\r
+    status|=workset.status;\r
+    }\r
+  if (status!=0) decStatus(res, status, set);\r
+  return res;\r
+  } // decNumberToIntegralExact\r
+\r
+decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,\r
+                                     decContext *set) {\r
+  decContext workset=*set;         // working context\r
+  workset.traps=0;                 // no traps\r
+  decNumberToIntegralExact(res, rhs, &workset);\r
+  // this never affects set, except for sNaNs; NaN will have been set\r
+  // or propagated already, so no need to call decStatus\r
+  set->status|=workset.status&DEC_Invalid_operation;\r
+  return res;\r
+  } // decNumberToIntegralValue\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberXor -- XOR two Numbers, digitwise                         */\r
+/*                                                                    */\r
+/*   This computes C = A ^ B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context (used for result length and error report)     */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Logical function restrictions apply (see above); a NaN is          */\r
+/* returned with Invalid_operation if a restriction is violated.      */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberXor(decNumber *res, const decNumber *lhs,\r
+                         const decNumber *rhs, decContext *set) {\r
+  const Unit *ua, *ub;                  // -> operands\r
+  const Unit *msua, *msub;              // -> operand msus\r
+  Unit  *uc, *msuc;                     // -> result and its msu\r
+  Int   msudigs;                        // digits in res msu\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)\r
+   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {\r
+    decStatus(res, DEC_Invalid_operation, set);\r
+    return res;\r
+    }\r
+  // operands are valid\r
+  ua=lhs->lsu;                          // bottom-up\r
+  ub=rhs->lsu;                          // ..\r
+  uc=res->lsu;                          // ..\r
+  msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs\r
+  msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs\r
+  msuc=uc+D2U(set->digits)-1;           // -> msu of result\r
+  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]\r
+  for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop\r
+    Unit a, b;                          // extract units\r
+    if (ua>msua) a=0;\r
+     else a=*ua;\r
+    if (ub>msub) b=0;\r
+     else b=*ub;\r
+    *uc=0;                              // can now write back\r
+    if (a|b) {                          // maybe 1 bits to examine\r
+      Int i, j;\r
+      // This loop could be unrolled and/or use BIN2BCD tables\r
+      for (i=0; i<DECDPUN; i++) {\r
+        if ((a^b)&1) *uc=*uc+(Unit)powers[i];     // effect XOR\r
+        j=a%10;\r
+        a=a/10;\r
+        j|=b%10;\r
+        b=b/10;\r
+        if (j>1) {\r
+          decStatus(res, DEC_Invalid_operation, set);\r
+          return res;\r
+          }\r
+        if (uc==msuc && i==msudigs-1) break;      // just did final digit\r
+        } // each digit\r
+      } // non-zero\r
+    } // each unit\r
+  // [here uc-1 is the msu of the result]\r
+  res->digits=decGetDigits(res->lsu, uc-res->lsu);\r
+  res->exponent=0;                      // integer\r
+  res->bits=0;                          // sign=0\r
+  return res;  // [no status to set]\r
+  } // decNumberXor\r
+\r
+\r
+/* ================================================================== */\r
+/* Utility routines                                                   */\r
+/* ================================================================== */\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberClass -- return the decClass of a decNumber               */\r
+/*   dn -- the decNumber to test                                      */\r
+/*   set -- the context to use for Emin                               */\r
+/*   returns the decClass enum                                        */\r
+/* ------------------------------------------------------------------ */\r
+enum decClass decNumberClass(const decNumber *dn, decContext *set) {\r
+  if (decNumberIsSpecial(dn)) {\r
+    if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;\r
+    if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;\r
+    // must be an infinity\r
+    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;\r
+    return DEC_CLASS_POS_INF;\r
+    }\r
+  // is finite\r
+  if (decNumberIsNormal(dn, set)) { // most common\r
+    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;\r
+    return DEC_CLASS_POS_NORMAL;\r
+    }\r
+  // is subnormal or zero\r
+  if (decNumberIsZero(dn)) {    // most common\r
+    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;\r
+    return DEC_CLASS_POS_ZERO;\r
+    }\r
+  if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;\r
+  return DEC_CLASS_POS_SUBNORMAL;\r
+  } // decNumberClass\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberClassToString -- convert decClass to a string             */\r
+/*                                                                    */\r
+/*  eclass is a valid decClass                                        */\r
+/*  returns a constant string describing the class (max 13+1 chars)   */\r
+/* ------------------------------------------------------------------ */\r
+const char *decNumberClassToString(enum decClass eclass) {\r
+  if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;\r
+  if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;\r
+  if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;\r
+  if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;\r
+  if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;\r
+  if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;\r
+  if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;\r
+  if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;\r
+  if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;\r
+  if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;\r
+  return DEC_ClassString_UN;           // Unknown\r
+  } // decNumberClassToString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberCopy -- copy a number                                     */\r
+/*                                                                    */\r
+/*   dest is the target decNumber                                     */\r
+/*   src  is the source decNumber                                     */\r
+/*   returns dest                                                     */\r
+/*                                                                    */\r
+/* (dest==src is allowed and is a no-op)                              */\r
+/* All fields are updated as required.  This is a utility operation,  */\r
+/* so special values are unchanged and no error is possible.          */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {\r
+\r
+  #if DECCHECK\r
+  if (src==NULL) return decNumberZero(dest);\r
+  #endif\r
+\r
+  if (dest==src) return dest;                // no copy required\r
+\r
+  // Use explicit assignments here as structure assignment could copy\r
+  // more than just the lsu (for small DECDPUN).  This would not affect\r
+  // the value of the results, but could disturb test harness spill\r
+  // checking.\r
+  dest->bits=src->bits;\r
+  dest->exponent=src->exponent;\r
+  dest->digits=src->digits;\r
+  dest->lsu[0]=src->lsu[0];\r
+  if (src->digits>DECDPUN) {                 // more Units to come\r
+    const Unit *smsup, *s;                   // work\r
+    Unit  *d;                                // ..\r
+    // memcpy for the remaining Units would be safe as they cannot\r
+    // overlap.  However, this explicit loop is faster in short cases.\r
+    d=dest->lsu+1;                           // -> first destination\r
+    smsup=src->lsu+D2U(src->digits);         // -> source msu+1\r
+    for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;\r
+    }\r
+  return dest;\r
+  } // decNumberCopy\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberCopyAbs -- quiet absolute value operator                  */\r
+/*                                                                    */\r
+/*   This sets C = abs(A)                                             */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* No exception or error can occur; this is a quiet bitwise operation.*/\r
+/* See also decNumberAbs for a checking version of this.              */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;\r
+  #endif\r
+  decNumberCopy(res, rhs);\r
+  res->bits&=~DECNEG;                   // turn off sign\r
+  return res;\r
+  } // decNumberCopyAbs\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberCopyNegate -- quiet negate value operator                 */\r
+/*                                                                    */\r
+/*   This sets C = negate(A)                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* No exception or error can occur; this is a quiet bitwise operation.*/\r
+/* See also decNumberMinus for a checking version of this.            */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;\r
+  #endif\r
+  decNumberCopy(res, rhs);\r
+  res->bits^=DECNEG;                    // invert the sign\r
+  return res;\r
+  } // decNumberCopyNegate\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberCopySign -- quiet copy and set sign operator              */\r
+/*                                                                    */\r
+/*   This sets C = A with the sign of B                               */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* No exception or error can occur; this is a quiet bitwise operation.*/\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,\r
+                              const decNumber *rhs) {\r
+  uByte sign;                           // rhs sign\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;\r
+  #endif\r
+  sign=rhs->bits & DECNEG;              // save sign bit\r
+  decNumberCopy(res, lhs);\r
+  res->bits&=~DECNEG;                   // clear the sign\r
+  res->bits|=sign;                      // set from rhs\r
+  return res;\r
+  } // decNumberCopySign\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberGetBCD -- get the coefficient in BCD8                     */\r
+/*   dn is the source decNumber                                       */\r
+/*   bcd is the uInt array that will receive dn->digits BCD bytes,    */\r
+/*     most-significant at offset 0                                   */\r
+/*   returns bcd                                                      */\r
+/*                                                                    */\r
+/* bcd must have at least dn->digits bytes.  No error is possible; if */\r
+/* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */\r
+/* ------------------------------------------------------------------ */\r
+uByte * decNumberGetBCD(const decNumber *dn, uByte *bcd) {\r
+  uByte *ub=bcd+dn->digits-1;      // -> lsd\r
+  const Unit *up=dn->lsu;          // Unit pointer, -> lsu\r
+\r
+  #if DECDPUN==1                   // trivial simple copy\r
+    for (; ub>=bcd; ub--, up++) *ub=*up;\r
+  #else                            // chopping needed\r
+    uInt u=*up;                    // work\r
+    uInt cut=DECDPUN;              // downcounter through unit\r
+    for (; ub>=bcd; ub--) {\r
+      *ub=(uByte)(u%10);           // [*6554 trick inhibits, here]\r
+      u=u/10;\r
+      cut--;\r
+      if (cut>0) continue;         // more in this unit\r
+      up++;\r
+      u=*up;\r
+      cut=DECDPUN;\r
+      }\r
+  #endif\r
+  return bcd;\r
+  } // decNumberGetBCD\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberSetBCD -- set (replace) the coefficient from BCD8         */\r
+/*   dn is the target decNumber                                       */\r
+/*   bcd is the uInt array that will source n BCD bytes, most-        */\r
+/*     significant at offset 0                                        */\r
+/*   n is the number of digits in the source BCD array (bcd)          */\r
+/*   returns dn                                                       */\r
+/*                                                                    */\r
+/* dn must have space for at least n digits.  No error is possible;   */\r
+/* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */\r
+/* and bcd[0] zero.                                                   */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {\r
+  Unit *up=dn->lsu+D2U(dn->digits)-1;   // -> msu [target pointer]\r
+  const uByte *ub=bcd;                  // -> source msd\r
+\r
+  #if DECDPUN==1                        // trivial simple copy\r
+    for (; ub<bcd+n; ub++, up--) *up=*ub;\r
+  #else                                 // some assembly needed\r
+    // calculate how many digits in msu, and hence first cut\r
+    Int cut=MSUDIGITS(n);               // [faster than remainder]\r
+    for (;up>=dn->lsu; up--) {          // each Unit from msu\r
+      *up=0;                            // will take <=DECDPUN digits\r
+      for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;\r
+      cut=DECDPUN;                      // next Unit has all digits\r
+      }\r
+  #endif\r
+  dn->digits=n;                         // set digit count\r
+  return dn;\r
+  } // decNumberSetBCD\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberIsNormal -- test normality of a decNumber                 */\r
+/*   dn is the decNumber to test                                      */\r
+/*   set is the context to use for Emin                               */\r
+/*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */\r
+/* ------------------------------------------------------------------ */\r
+Int decNumberIsNormal(const decNumber *dn, decContext *set) {\r
+  Int ae;                               // adjusted exponent\r
+  #if DECCHECK\r
+  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;\r
+  #endif\r
+\r
+  if (decNumberIsSpecial(dn)) return 0; // not finite\r
+  if (decNumberIsZero(dn)) return 0;    // not non-zero\r
+\r
+  ae=dn->exponent+dn->digits-1;         // adjusted exponent\r
+  if (ae<set->emin) return 0;           // is subnormal\r
+  return 1;\r
+  } // decNumberIsNormal\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberIsSubnormal -- test subnormality of a decNumber           */\r
+/*   dn is the decNumber to test                                      */\r
+/*   set is the context to use for Emin                               */\r
+/*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */\r
+/* ------------------------------------------------------------------ */\r
+Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {\r
+  Int ae;                               // adjusted exponent\r
+  #if DECCHECK\r
+  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;\r
+  #endif\r
+\r
+  if (decNumberIsSpecial(dn)) return 0; // not finite\r
+  if (decNumberIsZero(dn)) return 0;    // not non-zero\r
+\r
+  ae=dn->exponent+dn->digits-1;         // adjusted exponent\r
+  if (ae<set->emin) return 1;           // is subnormal\r
+  return 0;\r
+  } // decNumberIsSubnormal\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberTrim -- remove insignificant zeros                        */\r
+/*                                                                    */\r
+/*   dn is the number to trim                                         */\r
+/*   returns dn                                                       */\r
+/*                                                                    */\r
+/* All fields are updated as required.  This is a utility operation,  */\r
+/* so special values are unchanged and no error is possible.  The     */\r
+/* zeros are removed unconditionally.                                 */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decNumberTrim(decNumber *dn) {\r
+  Int  dropped;                    // work\r
+  decContext set;                  // ..\r
+  #if DECCHECK\r
+  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;\r
+  #endif\r
+  decContextDefault(&set, DEC_INIT_BASE);    // clamp=0\r
+  return decTrim(dn, &set, 0, 1, &dropped);\r
+  } // decNumberTrim\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberVersion -- return the name and version of this module     */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+const char * decNumberVersion(void) {\r
+  return DECVERSION;\r
+  } // decNumberVersion\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberZero -- set a number to 0                                 */\r
+/*                                                                    */\r
+/*   dn is the number to set, with space for one digit                */\r
+/*   returns dn                                                       */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+// Memset is not used as it is much slower in some environments.\r
+decNumber * decNumberZero(decNumber *dn) {\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;\r
+  #endif\r
+\r
+  dn->bits=0;\r
+  dn->exponent=0;\r
+  dn->digits=1;\r
+  dn->lsu[0]=0;\r
+  return dn;\r
+  } // decNumberZero\r
+\r
+/* ================================================================== */\r
+/* Local routines                                                     */\r
+/* ================================================================== */\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decToString -- lay out a number into a string                      */\r
+/*                                                                    */\r
+/*   dn     is the number to lay out                                  */\r
+/*   string is where to lay out the number                            */\r
+/*   eng    is 1 if Engineering, 0 if Scientific                      */\r
+/*                                                                    */\r
+/* string must be at least dn->digits+14 characters long              */\r
+/* No error is possible.                                              */\r
+/*                                                                    */\r
+/* Note that this routine can generate a -0 or 0.000.  These are      */\r
+/* never generated in subset to-number or arithmetic, but can occur   */\r
+/* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */\r
+/* ------------------------------------------------------------------ */\r
+// If DECCHECK is enabled the string "?" is returned if a number is\r
+// invalid.\r
+static void decToString(const decNumber *dn, char *string, Flag eng) {\r
+  Int exp=dn->exponent;       // local copy\r
+  Int e;                      // E-part value\r
+  Int pre;                    // digits before the '.'\r
+  Int cut;                    // for counting digits in a Unit\r
+  char *c=string;             // work [output pointer]\r
+  const Unit *up=dn->lsu+D2U(dn->digits)-1; // -> msu [input pointer]\r
+  uInt u, pow;                // work\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {\r
+    strcpy(string, "?");\r
+    return;}\r
+  #endif\r
+\r
+  if (decNumberIsNegative(dn)) {   // Negatives get a minus\r
+    *c='-';\r
+    c++;\r
+    }\r
+  if (dn->bits&DECSPECIAL) {       // Is a special value\r
+    if (decNumberIsInfinite(dn)) {\r
+      strcpy(c,   "Inf");\r
+      strcpy(c+3, "inity");\r
+      return;}\r
+    // a NaN\r
+    if (dn->bits&DECSNAN) {        // signalling NaN\r
+      *c='s';\r
+      c++;\r
+      }\r
+    strcpy(c, "NaN");\r
+    c+=3;                          // step past\r
+    // if not a clean non-zero coefficient, that's all there is in a\r
+    // NaN string\r
+    if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;\r
+    // [drop through to add integer]\r
+    }\r
+\r
+  // calculate how many digits in msu, and hence first cut\r
+  cut=MSUDIGITS(dn->digits);       // [faster than remainder]\r
+  cut--;                           // power of ten for digit\r
+\r
+  if (exp==0) {                    // simple integer [common fastpath]\r
+    for (;up>=dn->lsu; up--) {     // each Unit from msu\r
+      u=*up;                       // contains DECDPUN digits to lay out\r
+      for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);\r
+      cut=DECDPUN-1;               // next Unit has all digits\r
+      }\r
+    *c='\0';                       // terminate the string\r
+    return;}\r
+\r
+  /* non-0 exponent -- assume plain form */\r
+  pre=dn->digits+exp;              // digits before '.'\r
+  e=0;                             // no E\r
+  if ((exp>0) || (pre<-5)) {       // need exponential form\r
+    e=exp+dn->digits-1;            // calculate E value\r
+    pre=1;                         // assume one digit before '.'\r
+    if (eng && (e!=0)) {           // engineering: may need to adjust\r
+      Int adj;                     // adjustment\r
+      // The C remainder operator is undefined for negative numbers, so\r
+      // a positive remainder calculation must be used here\r
+      if (e<0) {\r
+        adj=(-e)%3;\r
+        if (adj!=0) adj=3-adj;\r
+        }\r
+       else { // e>0\r
+        adj=e%3;\r
+        }\r
+      e=e-adj;\r
+      // if dealing with zero still produce an exponent which is a\r
+      // multiple of three, as expected, but there will only be the\r
+      // one zero before the E, still.  Otherwise note the padding.\r
+      if (!ISZERO(dn)) pre+=adj;\r
+       else {  // is zero\r
+        if (adj!=0) {              // 0.00Esnn needed\r
+          e=e+3;\r
+          pre=-(2-adj);\r
+          }\r
+        } // zero\r
+      } // eng\r
+    } // need exponent\r
+\r
+  /* lay out the digits of the coefficient, adding 0s and . as needed */\r
+  u=*up;\r
+  if (pre>0) {                     // xxx.xxx or xx00 (engineering) form\r
+    Int n=pre;\r
+    for (; pre>0; pre--, c++, cut--) {\r
+      if (cut<0) {                 // need new Unit\r
+        if (up==dn->lsu) break;    // out of input digits (pre>digits)\r
+        up--;\r
+        cut=DECDPUN-1;\r
+        u=*up;\r
+        }\r
+      TODIGIT(u, cut, c, pow);\r
+      }\r
+    if (n<dn->digits) {            // more to come, after '.'\r
+      *c='.'; c++;\r
+      for (;; c++, cut--) {\r
+        if (cut<0) {               // need new Unit\r
+          if (up==dn->lsu) break;  // out of input digits\r
+          up--;\r
+          cut=DECDPUN-1;\r
+          u=*up;\r
+          }\r
+        TODIGIT(u, cut, c, pow);\r
+        }\r
+      }\r
+     else for (; pre>0; pre--, c++) *c='0'; // 0 padding (for engineering) needed\r
+    }\r
+   else {                          // 0.xxx or 0.000xxx form\r
+    *c='0'; c++;\r
+    *c='.'; c++;\r
+    for (; pre<0; pre++, c++) *c='0';   // add any 0's after '.'\r
+    for (; ; c++, cut--) {\r
+      if (cut<0) {                 // need new Unit\r
+        if (up==dn->lsu) break;    // out of input digits\r
+        up--;\r
+        cut=DECDPUN-1;\r
+        u=*up;\r
+        }\r
+      TODIGIT(u, cut, c, pow);\r
+      }\r
+    }\r
+\r
+  /* Finally add the E-part, if needed.  It will never be 0, has a\r
+     base maximum and minimum of +999999999 through -999999999, but\r
+     could range down to -1999999998 for anormal numbers */\r
+  if (e!=0) {\r
+    Flag had=0;               // 1=had non-zero\r
+    *c='E'; c++;\r
+    *c='+'; c++;              // assume positive\r
+    u=e;                      // ..\r
+    if (e<0) {\r
+      *(c-1)='-';             // oops, need -\r
+      u=-e;                   // uInt, please\r
+      }\r
+    // lay out the exponent [_itoa or equivalent is not ANSI C]\r
+    for (cut=9; cut>=0; cut--) {\r
+      TODIGIT(u, cut, c, pow);\r
+      if (*c=='0' && !had) continue;    // skip leading zeros\r
+      had=1;                            // had non-0\r
+      c++;                              // step for next\r
+      } // cut\r
+    }\r
+  *c='\0';          // terminate the string (all paths)\r
+  return;\r
+  } // decToString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decAddOp -- add/subtract operation                                 */\r
+/*                                                                    */\r
+/*   This computes C = A + B                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*   negate is DECNEG if rhs should be negated, or 0 otherwise        */\r
+/*   status accumulates status for the caller                         */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/* Inexact in status must be 0 for correct Exact zero sign in result  */\r
+/* ------------------------------------------------------------------ */\r
+/* If possible, the coefficient is calculated directly into C.        */\r
+/* However, if:                                                       */\r
+/*   -- a digits+1 calculation is needed because the numbers are      */\r
+/*      unaligned and span more than set->digits digits               */\r
+/*   -- a carry to digits+1 digits looks possible                     */\r
+/*   -- C is the same as A or B, and the result would destructively   */\r
+/*      overlap the A or B coefficient                                */\r
+/* then the result must be calculated into a temporary buffer.  In    */\r
+/* this case a local (stack) buffer is used if possible, and only if  */\r
+/* too long for that does malloc become the final resort.             */\r
+/*                                                                    */\r
+/* Misalignment is handled as follows:                                */\r
+/*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */\r
+/*   BPad: Apply the padding by a combination of shifting (whole      */\r
+/*         units) and multiplication (part units).                    */\r
+/*                                                                    */\r
+/* Addition, especially x=x+1, is speed-critical.                     */\r
+/* The static buffer is larger than might be expected to allow for    */\r
+/* calls from higher-level funtions (notable exp).                    */\r
+/* ------------------------------------------------------------------ */\r
+static decNumber * decAddOp(decNumber *res, const decNumber *lhs,\r
+                            const decNumber *rhs, decContext *set,\r
+                            uByte negate, uInt *status) {\r
+  #if DECSUBSET\r
+  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated\r
+  decNumber *allocrhs=NULL;        // .., rhs\r
+  #endif\r
+  Int   rhsshift;                  // working shift (in Units)\r
+  Int   maxdigits;                 // longest logical length\r
+  Int   mult;                      // multiplier\r
+  Int   residue;                   // rounding accumulator\r
+  uByte bits;                      // result bits\r
+  Flag  diffsign;                  // non-0 if arguments have different sign\r
+  Unit  *acc;                      // accumulator for result\r
+  Unit  accbuff[SD2U(DECBUFFER*2+20)]; // local buffer [*2+20 reduces many\r
+                                   // allocations when called from\r
+                                   // other operations, notable exp]\r
+  Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated\r
+  Int   reqdigits=set->digits;     // local copy; requested DIGITS\r
+  Int   padding;                   // work\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                             // protect allocated storage\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operands and set lostDigits status, as needed\r
+      if (lhs->digits>reqdigits) {\r
+        alloclhs=decRoundOperand(lhs, set, status);\r
+        if (alloclhs==NULL) break;\r
+        lhs=alloclhs;\r
+        }\r
+      if (rhs->digits>reqdigits) {\r
+        allocrhs=decRoundOperand(rhs, set, status);\r
+        if (allocrhs==NULL) break;\r
+        rhs=allocrhs;\r
+        }\r
+      }\r
+    #endif\r
+    // [following code does not require input rounding]\r
+\r
+    // note whether signs differ [used all paths]\r
+    diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);\r
+\r
+    // handle infinities and NaNs\r
+    if (SPECIALARGS) {                  // a special bit set\r
+      if (SPECIALARGS & (DECSNAN | DECNAN))  // a NaN\r
+        decNaNs(res, lhs, rhs, set, status);\r
+       else { // one or two infinities\r
+        if (decNumberIsInfinite(lhs)) { // LHS is infinity\r
+          // two infinities with different signs is invalid\r
+          if (decNumberIsInfinite(rhs) && diffsign) {\r
+            *status|=DEC_Invalid_operation;\r
+            break;\r
+            }\r
+          bits=lhs->bits & DECNEG;      // get sign from LHS\r
+          }\r
+         else bits=(rhs->bits^negate) & DECNEG;// RHS must be Infinity\r
+        bits|=DECINF;\r
+        decNumberZero(res);\r
+        res->bits=bits;                 // set +/- infinity\r
+        } // an infinity\r
+      break;\r
+      }\r
+\r
+    // Quick exit for add 0s; return the non-0, modified as need be\r
+    if (ISZERO(lhs)) {\r
+      Int adjust;                       // work\r
+      Int lexp=lhs->exponent;           // save in case LHS==RES\r
+      bits=lhs->bits;                   // ..\r
+      residue=0;                        // clear accumulator\r
+      decCopyFit(res, rhs, set, &residue, status); // copy (as needed)\r
+      res->bits^=negate;                // flip if rhs was negated\r
+      #if DECSUBSET\r
+      if (set->extended) {              // exponents on zeros count\r
+      #endif\r
+        // exponent will be the lower of the two\r
+        adjust=lexp-res->exponent;      // adjustment needed [if -ve]\r
+        if (ISZERO(res)) {              // both 0: special IEEE 754 rules\r
+          if (adjust<0) res->exponent=lexp;  // set exponent\r
+          // 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0\r
+          if (diffsign) {\r
+            if (set->round!=DEC_ROUND_FLOOR) res->bits=0;\r
+             else res->bits=DECNEG;     // preserve 0 sign\r
+            }\r
+          }\r
+         else { // non-0 res\r
+          if (adjust<0) {     // 0-padding needed\r
+            if ((res->digits-adjust)>set->digits) {\r
+              adjust=res->digits-set->digits;     // to fit exactly\r
+              *status|=DEC_Rounded;               // [but exact]\r
+              }\r
+            res->digits=decShiftToMost(res->lsu, res->digits, -adjust);\r
+            res->exponent+=adjust;                // set the exponent.\r
+            }\r
+          } // non-0 res\r
+      #if DECSUBSET\r
+        } // extended\r
+      #endif\r
+      decFinish(res, set, &residue, status);      // clean and finalize\r
+      break;}\r
+\r
+    if (ISZERO(rhs)) {                  // [lhs is non-zero]\r
+      Int adjust;                       // work\r
+      Int rexp=rhs->exponent;           // save in case RHS==RES\r
+      bits=rhs->bits;                   // be clean\r
+      residue=0;                        // clear accumulator\r
+      decCopyFit(res, lhs, set, &residue, status); // copy (as needed)\r
+      #if DECSUBSET\r
+      if (set->extended) {              // exponents on zeros count\r
+      #endif\r
+        // exponent will be the lower of the two\r
+        // [0-0 case handled above]\r
+        adjust=rexp-res->exponent;      // adjustment needed [if -ve]\r
+        if (adjust<0) {     // 0-padding needed\r
+          if ((res->digits-adjust)>set->digits) {\r
+            adjust=res->digits-set->digits;     // to fit exactly\r
+            *status|=DEC_Rounded;               // [but exact]\r
+            }\r
+          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);\r
+          res->exponent+=adjust;                // set the exponent.\r
+          }\r
+      #if DECSUBSET\r
+        } // extended\r
+      #endif\r
+      decFinish(res, set, &residue, status);      // clean and finalize\r
+      break;}\r
+\r
+    // [NB: both fastpath and mainpath code below assume these cases\r
+    // (notably 0-0) have already been handled]\r
+\r
+    // calculate the padding needed to align the operands\r
+    padding=rhs->exponent-lhs->exponent;\r
+\r
+    // Fastpath cases where the numbers are aligned and normal, the RHS\r
+    // is all in one unit, no operand rounding is needed, and no carry,\r
+    // lengthening, or borrow is needed\r
+    if (padding==0\r
+        && rhs->digits<=DECDPUN\r
+        && rhs->exponent>=set->emin     // [some normals drop through]\r
+        && rhs->exponent<=set->emax-set->digits+1 // [could clamp]\r
+        && rhs->digits<=reqdigits\r
+        && lhs->digits<=reqdigits) {\r
+      Int partial=*lhs->lsu;\r
+      if (!diffsign) {                  // adding\r
+        partial+=*rhs->lsu;\r
+        if ((partial<=DECDPUNMAX)       // result fits in unit\r
+         && (lhs->digits>=DECDPUN ||    // .. and no digits-count change\r
+             partial<(Int)powers[lhs->digits])) { // ..\r
+          if (res!=lhs) decNumberCopy(res, lhs);  // not in place\r
+          *res->lsu=(Unit)partial;      // [copy could have overwritten RHS]\r
+          break;\r
+          }\r
+        // else drop out for careful add\r
+        }\r
+       else {                           // signs differ\r
+        partial-=*rhs->lsu;\r
+        if (partial>0) { // no borrow needed, and non-0 result\r
+          if (res!=lhs) decNumberCopy(res, lhs);  // not in place\r
+          *res->lsu=(Unit)partial;\r
+          // this could have reduced digits [but result>0]\r
+          res->digits=decGetDigits(res->lsu, D2U(res->digits));\r
+          break;\r
+          }\r
+        // else drop out for careful subtract\r
+        }\r
+      }\r
+\r
+    // Now align (pad) the lhs or rhs so they can be added or\r
+    // subtracted, as necessary.  If one number is much larger than\r
+    // the other (that is, if in plain form there is a least one\r
+    // digit between the lowest digit of one and the highest of the\r
+    // other) padding with up to DIGITS-1 trailing zeros may be\r
+    // needed; then apply rounding (as exotic rounding modes may be\r
+    // affected by the residue).\r
+    rhsshift=0;               // rhs shift to left (padding) in Units\r
+    bits=lhs->bits;           // assume sign is that of LHS\r
+    mult=1;                   // likely multiplier\r
+\r
+    // [if padding==0 the operands are aligned; no padding is needed]\r
+    if (padding!=0) {\r
+      // some padding needed; always pad the RHS, as any required\r
+      // padding can then be effected by a simple combination of\r
+      // shifts and a multiply\r
+      Flag swapped=0;\r
+      if (padding<0) {                  // LHS needs the padding\r
+        const decNumber *t;\r
+        padding=-padding;               // will be +ve\r
+        bits=(uByte)(rhs->bits^negate); // assumed sign is now that of RHS\r
+        t=lhs; lhs=rhs; rhs=t;\r
+        swapped=1;\r
+        }\r
+\r
+      // If, after pad, rhs would be longer than lhs by digits+1 or\r
+      // more then lhs cannot affect the answer, except as a residue,\r
+      // so only need to pad up to a length of DIGITS+1.\r
+      if (rhs->digits+padding > lhs->digits+reqdigits+1) {\r
+        // The RHS is sufficient\r
+        // for residue use the relative sign indication...\r
+        Int shift=reqdigits-rhs->digits;     // left shift needed\r
+        residue=1;                           // residue for rounding\r
+        if (diffsign) residue=-residue;      // signs differ\r
+        // copy, shortening if necessary\r
+        decCopyFit(res, rhs, set, &residue, status);\r
+        // if it was already shorter, then need to pad with zeros\r
+        if (shift>0) {\r
+          res->digits=decShiftToMost(res->lsu, res->digits, shift);\r
+          res->exponent-=shift;              // adjust the exponent.\r
+          }\r
+        // flip the result sign if unswapped and rhs was negated\r
+        if (!swapped) res->bits^=negate;\r
+        decFinish(res, set, &residue, status);    // done\r
+        break;}\r
+\r
+      // LHS digits may affect result\r
+      rhsshift=D2U(padding+1)-1;        // this much by Unit shift ..\r
+      mult=powers[padding-(rhsshift*DECDPUN)]; // .. this by multiplication\r
+      } // padding needed\r
+\r
+    if (diffsign) mult=-mult;           // signs differ\r
+\r
+    // determine the longer operand\r
+    maxdigits=rhs->digits+padding;      // virtual length of RHS\r
+    if (lhs->digits>maxdigits) maxdigits=lhs->digits;\r
+\r
+    // Decide on the result buffer to use; if possible place directly\r
+    // into result.\r
+    acc=res->lsu;                       // assume add direct to result\r
+    // If destructive overlap, or the number is too long, or a carry or\r
+    // borrow to DIGITS+1 might be possible, a buffer must be used.\r
+    // [Might be worth more sophisticated tests when maxdigits==reqdigits]\r
+    if ((maxdigits>=reqdigits)          // is, or could be, too large\r
+     || (res==rhs && rhsshift>0)) {     // destructive overlap\r
+      // buffer needed, choose it; units for maxdigits digits will be\r
+      // needed, +1 Unit for carry or borrow\r
+      Int need=D2U(maxdigits)+1;\r
+      acc=accbuff;                      // assume use local buffer\r
+      if (need*sizeof(Unit)>sizeof(accbuff)) {\r
+        // printf("malloc add %ld %ld\n", need, sizeof(accbuff));\r
+        allocacc=(Unit *)malloc(need*sizeof(Unit));\r
+        if (allocacc==NULL) {           // hopeless -- abandon\r
+          *status|=DEC_Insufficient_storage;\r
+          break;}\r
+        acc=allocacc;\r
+        }\r
+      }\r
+\r
+    res->bits=(uByte)(bits&DECNEG);     // it's now safe to overwrite..\r
+    res->exponent=lhs->exponent;        // .. operands (even if aliased)\r
+\r
+    #if DECTRACE\r
+      decDumpAr('A', lhs->lsu, D2U(lhs->digits));\r
+      decDumpAr('B', rhs->lsu, D2U(rhs->digits));\r
+      printf("  :h: %ld %ld\n", rhsshift, mult);\r
+    #endif\r
+\r
+    // add [A+B*m] or subtract [A+B*(-m)]\r
+    res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),\r
+                              rhs->lsu, D2U(rhs->digits),\r
+                              rhsshift, acc, mult)\r
+               *DECDPUN;           // [units -> digits]\r
+    if (res->digits<0) {           // borrowed...\r
+      res->digits=-res->digits;\r
+      res->bits^=DECNEG;           // flip the sign\r
+      }\r
+    #if DECTRACE\r
+      decDumpAr('+', acc, D2U(res->digits));\r
+    #endif\r
+\r
+    // If a buffer was used the result must be copied back, possibly\r
+    // shortening.  (If no buffer was used then the result must have\r
+    // fit, so can't need rounding and residue must be 0.)\r
+    residue=0;                     // clear accumulator\r
+    if (acc!=res->lsu) {\r
+      #if DECSUBSET\r
+      if (set->extended) {         // round from first significant digit\r
+      #endif\r
+        // remove leading zeros that were added due to rounding up to\r
+        // integral Units -- before the test for rounding.\r
+        if (res->digits>reqdigits)\r
+          res->digits=decGetDigits(acc, D2U(res->digits));\r
+        decSetCoeff(res, set, acc, res->digits, &residue, status);\r
+      #if DECSUBSET\r
+        }\r
+       else { // subset arithmetic rounds from original significant digit\r
+        // May have an underestimate.  This only occurs when both\r
+        // numbers fit in DECDPUN digits and are padding with a\r
+        // negative multiple (-10, -100...) and the top digit(s) become\r
+        // 0.  (This only matters when using X3.274 rules where the\r
+        // leading zero could be included in the rounding.)\r
+        if (res->digits<maxdigits) {\r
+          *(acc+D2U(res->digits))=0; // ensure leading 0 is there\r
+          res->digits=maxdigits;\r
+          }\r
+         else {\r
+          // remove leading zeros that added due to rounding up to\r
+          // integral Units (but only those in excess of the original\r
+          // maxdigits length, unless extended) before test for rounding.\r
+          if (res->digits>reqdigits) {\r
+            res->digits=decGetDigits(acc, D2U(res->digits));\r
+            if (res->digits<maxdigits) res->digits=maxdigits;\r
+            }\r
+          }\r
+        decSetCoeff(res, set, acc, res->digits, &residue, status);\r
+        // Now apply rounding if needed before removing leading zeros.\r
+        // This is safe because subnormals are not a possibility\r
+        if (residue!=0) {\r
+          decApplyRound(res, set, residue, status);\r
+          residue=0;                 // did what needed to be done\r
+          }\r
+        } // subset\r
+      #endif\r
+      } // used buffer\r
+\r
+    // strip leading zeros [these were left on in case of subset subtract]\r
+    res->digits=decGetDigits(res->lsu, D2U(res->digits));\r
+\r
+    // apply checks and rounding\r
+    decFinish(res, set, &residue, status);\r
+\r
+    // "When the sum of two operands with opposite signs is exactly\r
+    // zero, the sign of that sum shall be '+' in all rounding modes\r
+    // except round toward -Infinity, in which mode that sign shall be\r
+    // '-'."  [Subset zeros also never have '-', set by decFinish.]\r
+    if (ISZERO(res) && diffsign\r
+     #if DECSUBSET\r
+     && set->extended\r
+     #endif\r
+     && (*status&DEC_Inexact)==0) {\r
+      if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   // sign -\r
+                                  else res->bits&=~DECNEG;  // sign +\r
+      }\r
+    } while(0);                              // end protected\r
+\r
+  if (allocacc!=NULL) free(allocacc);        // drop any storage used\r
+  #if DECSUBSET\r
+  if (allocrhs!=NULL) free(allocrhs);        // ..\r
+  if (alloclhs!=NULL) free(alloclhs);        // ..\r
+  #endif\r
+  return res;\r
+  } // decAddOp\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decDivideOp -- division operation                                  */\r
+/*                                                                    */\r
+/*  This routine performs the calculations for all four division      */\r
+/*  operators (divide, divideInteger, remainder, remainderNear).      */\r
+/*                                                                    */\r
+/*  C=A op B                                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */\r
+/*   status is the usual accumulator                                  */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+/*   The underlying algorithm of this routine is the same as in the   */\r
+/*   1981 S/370 implementation, that is, non-restoring long division  */\r
+/*   with bi-unit (rather than bi-digit) estimation for each unit     */\r
+/*   multiplier.  In this pseudocode overview, complications for the  */\r
+/*   Remainder operators and division residues for exact rounding are */\r
+/*   omitted for clarity.                                             */\r
+/*                                                                    */\r
+/*     Prepare operands and handle special values                     */\r
+/*     Test for x/0 and then 0/x                                      */\r
+/*     Exp =Exp1 - Exp2                                               */\r
+/*     Exp =Exp +len(var1) -len(var2)                                 */\r
+/*     Sign=Sign1 * Sign2                                             */\r
+/*     Pad accumulator (Var1) to double-length with 0's (pad1)        */\r
+/*     Pad Var2 to same length as Var1                                */\r
+/*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */\r
+/*     have=0                                                         */\r
+/*     Do until (have=digits+1 OR residue=0)                          */\r
+/*       if exp<0 then if integer divide/residue then leave           */\r
+/*       this_unit=0                                                  */\r
+/*       Do forever                                                   */\r
+/*          compare numbers                                           */\r
+/*          if <0 then leave inner_loop                               */\r
+/*          if =0 then (* quick exit without subtract *) do           */\r
+/*             this_unit=this_unit+1; output this_unit                */\r
+/*             leave outer_loop; end                                  */\r
+/*          Compare lengths of numbers (mantissae):                   */\r
+/*          If same then tops2=msu2pair -- {units 1&2 of var2}        */\r
+/*                  else tops2=msu2plus -- {0, unit 1 of var2}        */\r
+/*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */\r
+/*          mult=tops1/tops2  -- Good and safe guess at divisor       */\r
+/*          if mult=0 then mult=1                                     */\r
+/*          this_unit=this_unit+mult                                  */\r
+/*          subtract                                                  */\r
+/*          end inner_loop                                            */\r
+/*        if have\=0 | this_unit\=0 then do                           */\r
+/*          output this_unit                                          */\r
+/*          have=have+1; end                                          */\r
+/*        var2=var2/10                                                */\r
+/*        exp=exp-1                                                   */\r
+/*        end outer_loop                                              */\r
+/*     exp=exp+1   -- set the proper exponent                         */\r
+/*     if have=0 then generate answer=0                               */\r
+/*     Return (Result is defined by Var1)                             */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+/* Two working buffers are needed during the division; one (digits+   */\r
+/* 1) to accumulate the result, and the other (up to 2*digits+1) for  */\r
+/* long subtractions.  These are acc and var1 respectively.           */\r
+/* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/\r
+/* The static buffers may be larger than might be expected to allow   */\r
+/* for calls from higher-level funtions (notable exp).                */\r
+/* ------------------------------------------------------------------ */\r
+static decNumber * decDivideOp(decNumber *res,\r
+                               const decNumber *lhs, const decNumber *rhs,\r
+                               decContext *set, Flag op, uInt *status) {\r
+  #if DECSUBSET\r
+  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated\r
+  decNumber *allocrhs=NULL;        // .., rhs\r
+  #endif\r
+  Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; // local buffer\r
+  Unit  *acc=accbuff;              // -> accumulator array for result\r
+  Unit  *allocacc=NULL;            // -> allocated buffer, iff allocated\r
+  Unit  *accnext;                  // -> where next digit will go\r
+  Int   acclength;                 // length of acc needed [Units]\r
+  Int   accunits;                  // count of units accumulated\r
+  Int   accdigits;                 // count of digits accumulated\r
+\r
+  Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  // buffer for var1\r
+  Unit  *var1=varbuff;             // -> var1 array for long subtraction\r
+  Unit  *varalloc=NULL;            // -> allocated buffer, iff used\r
+  Unit  *msu1;                     // -> msu of var1\r
+\r
+  const Unit *var2;                // -> var2 array\r
+  const Unit *msu2;                // -> msu of var2\r
+  Int   msu2plus;                  // msu2 plus one [does not vary]\r
+  eInt  msu2pair;                  // msu2 pair plus one [does not vary]\r
+\r
+  Int   var1units, var2units;      // actual lengths\r
+  Int   var2ulen;                  // logical length (units)\r
+  Int   var1initpad=0;             // var1 initial padding (digits)\r
+  Int   maxdigits;                 // longest LHS or required acc length\r
+  Int   mult;                      // multiplier for subtraction\r
+  Unit  thisunit;                  // current unit being accumulated\r
+  Int   residue;                   // for rounding\r
+  Int   reqdigits=set->digits;     // requested DIGITS\r
+  Int   exponent;                  // working exponent\r
+  Int   maxexponent=0;             // DIVIDE maximum exponent if unrounded\r
+  uByte bits;                      // working sign\r
+  Unit  *target;                   // work\r
+  const Unit *source;              // ..\r
+  uInt  const *pow;                // ..\r
+  Int   shift, cut;                // ..\r
+  #if DECSUBSET\r
+  Int   dropped;                   // work\r
+  #endif\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                             // protect allocated storage\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operands and set lostDigits status, as needed\r
+      if (lhs->digits>reqdigits) {\r
+        alloclhs=decRoundOperand(lhs, set, status);\r
+        if (alloclhs==NULL) break;\r
+        lhs=alloclhs;\r
+        }\r
+      if (rhs->digits>reqdigits) {\r
+        allocrhs=decRoundOperand(rhs, set, status);\r
+        if (allocrhs==NULL) break;\r
+        rhs=allocrhs;\r
+        }\r
+      }\r
+    #endif\r
+    // [following code does not require input rounding]\r
+\r
+    bits=(lhs->bits^rhs->bits)&DECNEG;  // assumed sign for divisions\r
+\r
+    // handle infinities and NaNs\r
+    if (SPECIALARGS) {                  // a special bit set\r
+      if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs\r
+        decNaNs(res, lhs, rhs, set, status);\r
+        break;\r
+        }\r
+      // one or two infinities\r
+      if (decNumberIsInfinite(lhs)) {   // LHS (dividend) is infinite\r
+        if (decNumberIsInfinite(rhs) || // two infinities are invalid ..\r
+            op & (REMAINDER | REMNEAR)) { // as is remainder of infinity\r
+          *status|=DEC_Invalid_operation;\r
+          break;\r
+          }\r
+        // [Note that infinity/0 raises no exceptions]\r
+        decNumberZero(res);\r
+        res->bits=bits|DECINF;          // set +/- infinity\r
+        break;\r
+        }\r
+       else {                           // RHS (divisor) is infinite\r
+        residue=0;\r
+        if (op&(REMAINDER|REMNEAR)) {\r
+          // result is [finished clone of] lhs\r
+          decCopyFit(res, lhs, set, &residue, status);\r
+          }\r
+         else {  // a division\r
+          decNumberZero(res);\r
+          res->bits=bits;               // set +/- zero\r
+          // for DIVIDEINT the exponent is always 0.  For DIVIDE, result\r
+          // is a 0 with infinitely negative exponent, clamped to minimum\r
+          if (op&DIVIDE) {\r
+            res->exponent=set->emin-set->digits+1;\r
+            *status|=DEC_Clamped;\r
+            }\r
+          }\r
+        decFinish(res, set, &residue, status);\r
+        break;\r
+        }\r
+      }\r
+\r
+    // handle 0 rhs (x/0)\r
+    if (ISZERO(rhs)) {                  // x/0 is always exceptional\r
+      if (ISZERO(lhs)) {\r
+        decNumberZero(res);             // [after lhs test]\r
+        *status|=DEC_Division_undefined;// 0/0 will become NaN\r
+        }\r
+       else {\r
+        decNumberZero(res);\r
+        if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;\r
+         else {\r
+          *status|=DEC_Division_by_zero; // x/0\r
+          res->bits=bits|DECINF;         // .. is +/- Infinity\r
+          }\r
+        }\r
+      break;}\r
+\r
+    // handle 0 lhs (0/x)\r
+    if (ISZERO(lhs)) {                  // 0/x [x!=0]\r
+      #if DECSUBSET\r
+      if (!set->extended) decNumberZero(res);\r
+       else {\r
+      #endif\r
+        if (op&DIVIDE) {\r
+          residue=0;\r
+          exponent=lhs->exponent-rhs->exponent; // ideal exponent\r
+          decNumberCopy(res, lhs);      // [zeros always fit]\r
+          res->bits=bits;               // sign as computed\r
+          res->exponent=exponent;       // exponent, too\r
+          decFinalize(res, set, &residue, status);   // check exponent\r
+          }\r
+         else if (op&DIVIDEINT) {\r
+          decNumberZero(res);           // integer 0\r
+          res->bits=bits;               // sign as computed\r
+          }\r
+         else {                         // a remainder\r
+          exponent=rhs->exponent;       // [save in case overwrite]\r
+          decNumberCopy(res, lhs);      // [zeros always fit]\r
+          if (exponent<res->exponent) res->exponent=exponent; // use lower\r
+          }\r
+      #if DECSUBSET\r
+        }\r
+      #endif\r
+      break;}\r
+\r
+    // Precalculate exponent.  This starts off adjusted (and hence fits\r
+    // in 31 bits) and becomes the usual unadjusted exponent as the\r
+    // division proceeds.  The order of evaluation is important, here,\r
+    // to avoid wrap.\r
+    exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);\r
+\r
+    // If the working exponent is -ve, then some quick exits are\r
+    // possible because the quotient is known to be <1\r
+    // [for REMNEAR, it needs to be < -1, as -0.5 could need work]\r
+    if (exponent<0 && !(op==DIVIDE)) {\r
+      if (op&DIVIDEINT) {\r
+        decNumberZero(res);                  // integer part is 0\r
+        #if DECSUBSET\r
+        if (set->extended)\r
+        #endif\r
+          res->bits=bits;                    // set +/- zero\r
+        break;}\r
+      // fastpath remainders so long as the lhs has the smaller\r
+      // (or equal) exponent\r
+      if (lhs->exponent<=rhs->exponent) {\r
+        if (op&REMAINDER || exponent<-1) {\r
+          // It is REMAINDER or safe REMNEAR; result is [finished\r
+          // clone of] lhs  (r = x - 0*y)\r
+          residue=0;\r
+          decCopyFit(res, lhs, set, &residue, status);\r
+          decFinish(res, set, &residue, status);\r
+          break;\r
+          }\r
+        // [unsafe REMNEAR drops through]\r
+        }\r
+      } // fastpaths\r
+\r
+    /* Long (slow) division is needed; roll up the sleeves... */\r
+\r
+    // The accumulator will hold the quotient of the division.\r
+    // If it needs to be too long for stack storage, then allocate.\r
+    acclength=D2U(reqdigits+DECDPUN);   // in Units\r
+    if (acclength*sizeof(Unit)>sizeof(accbuff)) {\r
+      // printf("malloc dvacc %ld units\n", acclength);\r
+      allocacc=(Unit *)malloc(acclength*sizeof(Unit));\r
+      if (allocacc==NULL) {             // hopeless -- abandon\r
+        *status|=DEC_Insufficient_storage;\r
+        break;}\r
+      acc=allocacc;                     // use the allocated space\r
+      }\r
+\r
+    // var1 is the padded LHS ready for subtractions.\r
+    // If it needs to be too long for stack storage, then allocate.\r
+    // The maximum units needed for var1 (long subtraction) is:\r
+    // Enough for\r
+    //     (rhs->digits+reqdigits-1) -- to allow full slide to right\r
+    // or  (lhs->digits)             -- to allow for long lhs\r
+    // whichever is larger\r
+    //   +1                -- for rounding of slide to right\r
+    //   +1                -- for leading 0s\r
+    //   +1                -- for pre-adjust if a remainder or DIVIDEINT\r
+    // [Note: unused units do not participate in decUnitAddSub data]\r
+    maxdigits=rhs->digits+reqdigits-1;\r
+    if (lhs->digits>maxdigits) maxdigits=lhs->digits;\r
+    var1units=D2U(maxdigits)+2;\r
+    // allocate a guard unit above msu1 for REMAINDERNEAR\r
+    if (!(op&DIVIDE)) var1units++;\r
+    if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {\r
+      // printf("malloc dvvar %ld units\n", var1units+1);\r
+      varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));\r
+      if (varalloc==NULL) {             // hopeless -- abandon\r
+        *status|=DEC_Insufficient_storage;\r
+        break;}\r
+      var1=varalloc;                    // use the allocated space\r
+      }\r
+\r
+    // Extend the lhs and rhs to full long subtraction length.  The lhs\r
+    // is truly extended into the var1 buffer, with 0 padding, so a\r
+    // subtract in place is always possible.  The rhs (var2) has\r
+    // virtual padding (implemented by decUnitAddSub).\r
+    // One guard unit was allocated above msu1 for rem=rem+rem in\r
+    // REMAINDERNEAR.\r
+    msu1=var1+var1units-1;              // msu of var1\r
+    source=lhs->lsu+D2U(lhs->digits)-1; // msu of input array\r
+    for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;\r
+    for (; target>=var1; target--) *target=0;\r
+\r
+    // rhs (var2) is left-aligned with var1 at the start\r
+    var2ulen=var1units;                 // rhs logical length (units)\r
+    var2units=D2U(rhs->digits);         // rhs actual length (units)\r
+    var2=rhs->lsu;                      // -> rhs array\r
+    msu2=var2+var2units-1;              // -> msu of var2 [never changes]\r
+    // now set up the variables which will be used for estimating the\r
+    // multiplication factor.  If these variables are not exact, add\r
+    // 1 to make sure that the multiplier is never overestimated.\r
+    msu2plus=*msu2;                     // it's value ..\r
+    if (var2units>1) msu2plus++;        // .. +1 if any more\r
+    msu2pair=(eInt)*msu2*(DECDPUNMAX+1);// top two pair ..\r
+    if (var2units>1) {                  // .. [else treat 2nd as 0]\r
+      msu2pair+=*(msu2-1);              // ..\r
+      if (var2units>2) msu2pair++;      // .. +1 if any more\r
+      }\r
+\r
+    // The calculation is working in units, which may have leading zeros,\r
+    // but the exponent was calculated on the assumption that they are\r
+    // both left-aligned.  Adjust the exponent to compensate: add the\r
+    // number of leading zeros in var1 msu and subtract those in var2 msu.\r
+    // [This is actually done by counting the digits and negating, as\r
+    // lead1=DECDPUN-digits1, and similarly for lead2.]\r
+    for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;\r
+    for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;\r
+\r
+    // Now, if doing an integer divide or remainder, ensure that\r
+    // the result will be Unit-aligned.  To do this, shift the var1\r
+    // accumulator towards least if need be.  (It's much easier to\r
+    // do this now than to reassemble the residue afterwards, if\r
+    // doing a remainder.)  Also ensure the exponent is not negative.\r
+    if (!(op&DIVIDE)) {\r
+      Unit *u;                          // work\r
+      // save the initial 'false' padding of var1, in digits\r
+      var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;\r
+      // Determine the shift to do.\r
+      if (exponent<0) cut=-exponent;\r
+       else cut=DECDPUN-exponent%DECDPUN;\r
+      decShiftToLeast(var1, var1units, cut);\r
+      exponent+=cut;                    // maintain numerical value\r
+      var1initpad-=cut;                 // .. and reduce padding\r
+      // clean any most-significant units which were just emptied\r
+      for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;\r
+      } // align\r
+     else { // is DIVIDE\r
+      maxexponent=lhs->exponent-rhs->exponent;    // save\r
+      // optimization: if the first iteration will just produce 0,\r
+      // preadjust to skip it [valid for DIVIDE only]\r
+      if (*msu1<*msu2) {\r
+        var2ulen--;                     // shift down\r
+        exponent-=DECDPUN;              // update the exponent\r
+        }\r
+      }\r
+\r
+    // ---- start the long-division loops ------------------------------\r
+    accunits=0;                         // no units accumulated yet\r
+    accdigits=0;                        // .. or digits\r
+    accnext=acc+acclength-1;            // -> msu of acc [NB: allows digits+1]\r
+    for (;;) {                          // outer forever loop\r
+      thisunit=0;                       // current unit assumed 0\r
+      // find the next unit\r
+      for (;;) {                        // inner forever loop\r
+        // strip leading zero units [from either pre-adjust or from\r
+        // subtract last time around].  Leave at least one unit.\r
+        for (; *msu1==0 && msu1>var1; msu1--) var1units--;\r
+\r
+        if (var1units<var2ulen) break;       // var1 too low for subtract\r
+        if (var1units==var2ulen) {           // unit-by-unit compare needed\r
+          // compare the two numbers, from msu\r
+          const Unit *pv1, *pv2;\r
+          Unit v2;                           // units to compare\r
+          pv2=msu2;                          // -> msu\r
+          for (pv1=msu1; ; pv1--, pv2--) {\r
+            // v1=*pv1 -- always OK\r
+            v2=0;                            // assume in padding\r
+            if (pv2>=var2) v2=*pv2;          // in range\r
+            if (*pv1!=v2) break;             // no longer the same\r
+            if (pv1==var1) break;            // done; leave pv1 as is\r
+            }\r
+          // here when all inspected or a difference seen\r
+          if (*pv1<v2) break;                // var1 too low to subtract\r
+          if (*pv1==v2) {                    // var1 == var2\r
+            // reach here if var1 and var2 are identical; subtraction\r
+            // would increase digit by one, and the residue will be 0 so\r
+            // the calculation is done; leave the loop with residue=0.\r
+            thisunit++;                      // as though subtracted\r
+            *var1=0;                         // set var1 to 0\r
+            var1units=1;                     // ..\r
+            break;  // from inner\r
+            } // var1 == var2\r
+          // *pv1>v2.  Prepare for real subtraction; the lengths are equal\r
+          // Estimate the multiplier (there's always a msu1-1)...\r
+          // Bring in two units of var2 to provide a good estimate.\r
+          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);\r
+          } // lengths the same\r
+         else { // var1units > var2ulen, so subtraction is safe\r
+          // The var2 msu is one unit towards the lsu of the var1 msu,\r
+          // so only one unit for var2 can be used.\r
+          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);\r
+          }\r
+        if (mult==0) mult=1;                 // must always be at least 1\r
+        // subtraction needed; var1 is > var2\r
+        thisunit=(Unit)(thisunit+mult);      // accumulate\r
+        // subtract var1-var2, into var1; only the overlap needs\r
+        // processing, as this is an in-place calculation\r
+        shift=var2ulen-var2units;\r
+        #if DECTRACE\r
+          decDumpAr('1', &var1[shift], var1units-shift);\r
+          decDumpAr('2', var2, var2units);\r
+          printf("m=%ld\n", -mult);\r
+        #endif\r
+        decUnitAddSub(&var1[shift], var1units-shift,\r
+                      var2, var2units, 0,\r
+                      &var1[shift], -mult);\r
+        #if DECTRACE\r
+          decDumpAr('#', &var1[shift], var1units-shift);\r
+        #endif\r
+        // var1 now probably has leading zeros; these are removed at the\r
+        // top of the inner loop.\r
+        } // inner loop\r
+\r
+      // The next unit has been calculated in full; unless it's a\r
+      // leading zero, add to acc\r
+      if (accunits!=0 || thisunit!=0) {      // is first or non-zero\r
+        *accnext=thisunit;                   // store in accumulator\r
+        // account exactly for the new digits\r
+        if (accunits==0) {\r
+          accdigits++;                       // at least one\r
+          for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;\r
+          }\r
+         else accdigits+=DECDPUN;\r
+        accunits++;                          // update count\r
+        accnext--;                           // ready for next\r
+        if (accdigits>reqdigits) break;      // have enough digits\r
+        }\r
+\r
+      // if the residue is zero, the operation is done (unless divide\r
+      // or divideInteger and still not enough digits yet)\r
+      if (*var1==0 && var1units==1) {        // residue is 0\r
+        if (op&(REMAINDER|REMNEAR)) break;\r
+        if ((op&DIVIDE) && (exponent<=maxexponent)) break;\r
+        // [drop through if divideInteger]\r
+        }\r
+      // also done enough if calculating remainder or integer\r
+      // divide and just did the last ('units') unit\r
+      if (exponent==0 && !(op&DIVIDE)) break;\r
+\r
+      // to get here, var1 is less than var2, so divide var2 by the per-\r
+      // Unit power of ten and go for the next digit\r
+      var2ulen--;                            // shift down\r
+      exponent-=DECDPUN;                     // update the exponent\r
+      } // outer loop\r
+\r
+    // ---- division is complete ---------------------------------------\r
+    // here: acc      has at least reqdigits+1 of good results (or fewer\r
+    //                if early stop), starting at accnext+1 (its lsu)\r
+    //       var1     has any residue at the stopping point\r
+    //       accunits is the number of digits collected in acc\r
+    if (accunits==0) {             // acc is 0\r
+      accunits=1;                  // show have a unit ..\r
+      accdigits=1;                 // ..\r
+      *accnext=0;                  // .. whose value is 0\r
+      }\r
+     else accnext++;               // back to last placed\r
+    // accnext now -> lowest unit of result\r
+\r
+    residue=0;                     // assume no residue\r
+    if (op&DIVIDE) {\r
+      // record the presence of any residue, for rounding\r
+      if (*var1!=0 || var1units>1) residue=1;\r
+       else { // no residue\r
+        // Had an exact division; clean up spurious trailing 0s.\r
+        // There will be at most DECDPUN-1, from the final multiply,\r
+        // and then only if the result is non-0 (and even) and the\r
+        // exponent is 'loose'.\r
+        #if DECDPUN>1\r
+        Unit lsu=*accnext;\r
+        if (!(lsu&0x01) && (lsu!=0)) {\r
+          // count the trailing zeros\r
+          Int drop=0;\r
+          for (;; drop++) {    // [will terminate because lsu!=0]\r
+            if (exponent>=maxexponent) break;     // don't chop real 0s\r
+            #if DECDPUN<=4\r
+              if ((lsu-QUOT10(lsu, drop+1)\r
+                  *powers[drop+1])!=0) break;     // found non-0 digit\r
+            #else\r
+              if (lsu%powers[drop+1]!=0) break;   // found non-0 digit\r
+            #endif\r
+            exponent++;\r
+            }\r
+          if (drop>0) {\r
+            accunits=decShiftToLeast(accnext, accunits, drop);\r
+            accdigits=decGetDigits(accnext, accunits);\r
+            accunits=D2U(accdigits);\r
+            // [exponent was adjusted in the loop]\r
+            }\r
+          } // neither odd nor 0\r
+        #endif\r
+        } // exact divide\r
+      } // divide\r
+     else /* op!=DIVIDE */ {\r
+      // check for coefficient overflow\r
+      if (accdigits+exponent>reqdigits) {\r
+        *status|=DEC_Division_impossible;\r
+        break;\r
+        }\r
+      if (op & (REMAINDER|REMNEAR)) {\r
+        // [Here, the exponent will be 0, because var1 was adjusted\r
+        // appropriately.]\r
+        Int postshift;                       // work\r
+        Flag wasodd=0;                       // integer was odd\r
+        Unit *quotlsu;                       // for save\r
+        Int  quotdigits;                     // ..\r
+\r
+        bits=lhs->bits;                      // remainder sign is always as lhs\r
+\r
+        // Fastpath when residue is truly 0 is worthwhile [and\r
+        // simplifies the code below]\r
+        if (*var1==0 && var1units==1) {      // residue is 0\r
+          Int exp=lhs->exponent;             // save min(exponents)\r
+          if (rhs->exponent<exp) exp=rhs->exponent;\r
+          decNumberZero(res);                // 0 coefficient\r
+          #if DECSUBSET\r
+          if (set->extended)\r
+          #endif\r
+          res->exponent=exp;                 // .. with proper exponent\r
+          res->bits=(uByte)(bits&DECNEG);          // [cleaned]\r
+          decFinish(res, set, &residue, status);   // might clamp\r
+          break;\r
+          }\r
+        // note if the quotient was odd\r
+        if (*accnext & 0x01) wasodd=1;       // acc is odd\r
+        quotlsu=accnext;                     // save in case need to reinspect\r
+        quotdigits=accdigits;                // ..\r
+\r
+        // treat the residue, in var1, as the value to return, via acc\r
+        // calculate the unused zero digits.  This is the smaller of:\r
+        //   var1 initial padding (saved above)\r
+        //   var2 residual padding, which happens to be given by:\r
+        postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;\r
+        // [the 'exponent' term accounts for the shifts during divide]\r
+        if (var1initpad<postshift) postshift=var1initpad;\r
+\r
+        // shift var1 the requested amount, and adjust its digits\r
+        var1units=decShiftToLeast(var1, var1units, postshift);\r
+        accnext=var1;\r
+        accdigits=decGetDigits(var1, var1units);\r
+        accunits=D2U(accdigits);\r
+\r
+        exponent=lhs->exponent;         // exponent is smaller of lhs & rhs\r
+        if (rhs->exponent<exponent) exponent=rhs->exponent;\r
+\r
+        // Now correct the result if doing remainderNear; if it\r
+        // (looking just at coefficients) is > rhs/2, or == rhs/2 and\r
+        // the integer was odd then the result should be rem-rhs.\r
+        if (op&REMNEAR) {\r
+          Int compare, tarunits;        // work\r
+          Unit *up;                     // ..\r
+          // calculate remainder*2 into the var1 buffer (which has\r
+          // 'headroom' of an extra unit and hence enough space)\r
+          // [a dedicated 'double' loop would be faster, here]\r
+          tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,\r
+                                 0, accnext, 1);\r
+          // decDumpAr('r', accnext, tarunits);\r
+\r
+          // Here, accnext (var1) holds tarunits Units with twice the\r
+          // remainder's coefficient, which must now be compared to the\r
+          // RHS.  The remainder's exponent may be smaller than the RHS's.\r
+          compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),\r
+                                 rhs->exponent-exponent);\r
+          if (compare==BADINT) {             // deep trouble\r
+            *status|=DEC_Insufficient_storage;\r
+            break;}\r
+\r
+          // now restore the remainder by dividing by two; the lsu\r
+          // is known to be even.\r
+          for (up=accnext; up<accnext+tarunits; up++) {\r
+            Int half;              // half to add to lower unit\r
+            half=*up & 0x01;\r
+            *up/=2;                // [shift]\r
+            if (!half) continue;\r
+            *(up-1)+=(DECDPUNMAX+1)/2;\r
+            }\r
+          // [accunits still describes the original remainder length]\r
+\r
+          if (compare>0 || (compare==0 && wasodd)) { // adjustment needed\r
+            Int exp, expunits, exprem;       // work\r
+            // This is effectively causing round-up of the quotient,\r
+            // so if it was the rare case where it was full and all\r
+            // nines, it would overflow and hence division-impossible\r
+            // should be raised\r
+            Flag allnines=0;                 // 1 if quotient all nines\r
+            if (quotdigits==reqdigits) {     // could be borderline\r
+              for (up=quotlsu; ; up++) {\r
+                if (quotdigits>DECDPUN) {\r
+                  if (*up!=DECDPUNMAX) break;// non-nines\r
+                  }\r
+                 else {                      // this is the last Unit\r
+                  if (*up==powers[quotdigits]-1) allnines=1;\r
+                  break;\r
+                  }\r
+                quotdigits-=DECDPUN;         // checked those digits\r
+                } // up\r
+              } // borderline check\r
+            if (allnines) {\r
+              *status|=DEC_Division_impossible;\r
+              break;}\r
+\r
+            // rem-rhs is needed; the sign will invert.  Again, var1\r
+            // can safely be used for the working Units array.\r
+            exp=rhs->exponent-exponent;      // RHS padding needed\r
+            // Calculate units and remainder from exponent.\r
+            expunits=exp/DECDPUN;\r
+            exprem=exp%DECDPUN;\r
+            // subtract [A+B*(-m)]; the result will always be negative\r
+            accunits=-decUnitAddSub(accnext, accunits,\r
+                                    rhs->lsu, D2U(rhs->digits),\r
+                                    expunits, accnext, -(Int)powers[exprem]);\r
+            accdigits=decGetDigits(accnext, accunits); // count digits exactly\r
+            accunits=D2U(accdigits);    // and recalculate the units for copy\r
+            // [exponent is as for original remainder]\r
+            bits^=DECNEG;               // flip the sign\r
+            }\r
+          } // REMNEAR\r
+        } // REMAINDER or REMNEAR\r
+      } // not DIVIDE\r
+\r
+    // Set exponent and bits\r
+    res->exponent=exponent;\r
+    res->bits=(uByte)(bits&DECNEG);          // [cleaned]\r
+\r
+    // Now the coefficient.\r
+    decSetCoeff(res, set, accnext, accdigits, &residue, status);\r
+\r
+    decFinish(res, set, &residue, status);   // final cleanup\r
+\r
+    #if DECSUBSET\r
+    // If a divide then strip trailing zeros if subset [after round]\r
+    if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);\r
+    #endif\r
+    } while(0);                              // end protected\r
+\r
+  if (varalloc!=NULL) free(varalloc);   // drop any storage used\r
+  if (allocacc!=NULL) free(allocacc);   // ..\r
+  #if DECSUBSET\r
+  if (allocrhs!=NULL) free(allocrhs);   // ..\r
+  if (alloclhs!=NULL) free(alloclhs);   // ..\r
+  #endif\r
+  return res;\r
+  } // decDivideOp\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decMultiplyOp -- multiplication operation                          */\r
+/*                                                                    */\r
+/*  This routine performs the multiplication C=A x B.                 */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*   status is the usual accumulator                                  */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+/* 'Classic' multiplication is used rather than Karatsuba, as the     */\r
+/* latter would give only a minor improvement for the short numbers   */\r
+/* expected to be handled most (and uses much more memory).           */\r
+/*                                                                    */\r
+/* There are two major paths here: the general-purpose ('old code')   */\r
+/* path which handles all DECDPUN values, and a fastpath version      */\r
+/* which is used if 64-bit ints are available, DECDPUN<=4, and more   */\r
+/* than two calls to decUnitAddSub would be made.                     */\r
+/*                                                                    */\r
+/* The fastpath version lumps units together into 8-digit or 9-digit  */\r
+/* chunks, and also uses a lazy carry strategy to minimise expensive  */\r
+/* 64-bit divisions.  The chunks are then broken apart again into     */\r
+/* units for continuing processing.  Despite this overhead, the       */\r
+/* fastpath can speed up some 16-digit operations by 10x (and much    */\r
+/* more for higher-precision calculations).                           */\r
+/*                                                                    */\r
+/* A buffer always has to be used for the accumulator; in the         */\r
+/* fastpath, buffers are also always needed for the chunked copies of */\r
+/* of the operand coefficients.                                       */\r
+/* Static buffers are larger than needed just for multiply, to allow  */\r
+/* for calls from other operations (notably exp).                     */\r
+/* ------------------------------------------------------------------ */\r
+#define FASTMUL (DECUSE64 && DECDPUN<5)\r
+static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,\r
+                                 const decNumber *rhs, decContext *set,\r
+                                 uInt *status) {\r
+  Int    accunits;                 // Units of accumulator in use\r
+  Int    exponent;                 // work\r
+  Int    residue=0;                // rounding residue\r
+  uByte  bits;                     // result sign\r
+  Unit  *acc;                      // -> accumulator Unit array\r
+  Int    needbytes;                // size calculator\r
+  void  *allocacc=NULL;            // -> allocated accumulator, iff allocated\r
+  Unit  accbuff[SD2U(DECBUFFER*4+1)]; // buffer (+1 for DECBUFFER==0,\r
+                                   // *4 for calls from other operations)\r
+  const Unit *mer, *mermsup;       // work\r
+  Int   madlength;                 // Units in multiplicand\r
+  Int   shift;                     // Units to shift multiplicand by\r
+\r
+  #if FASTMUL\r
+    // if DECDPUN is 1 or 3 work in base 10**9, otherwise\r
+    // (DECDPUN is 2 or 4) then work in base 10**8\r
+    #if DECDPUN & 1                // odd\r
+      #define FASTBASE 1000000000  // base\r
+      #define FASTDIGS          9  // digits in base\r
+      #define FASTLAZY         18  // carry resolution point [1->18]\r
+    #else\r
+      #define FASTBASE  100000000\r
+      #define FASTDIGS          8\r
+      #define FASTLAZY       1844  // carry resolution point [1->1844]\r
+    #endif\r
+    // three buffers are used, two for chunked copies of the operands\r
+    // (base 10**8 or base 10**9) and one base 2**64 accumulator with\r
+    // lazy carry evaluation\r
+    uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)\r
+    uInt  *zlhi=zlhibuff;                 // -> lhs array\r
+    uInt  *alloclhi=NULL;                 // -> allocated buffer, iff allocated\r
+    uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)\r
+    uInt  *zrhi=zrhibuff;                 // -> rhs array\r
+    uInt  *allocrhi=NULL;                 // -> allocated buffer, iff allocated\r
+    uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; // buffer (+1 for DECBUFFER==0)\r
+    // [allocacc is shared for both paths, as only one will run]\r
+    uLong *zacc=zaccbuff;          // -> accumulator array for exact result\r
+    #if DECDPUN==1\r
+    Int    zoff;                   // accumulator offset\r
+    #endif\r
+    uInt  *lip, *rip;              // item pointers\r
+    uInt  *lmsi, *rmsi;            // most significant items\r
+    Int    ilhs, irhs, iacc;       // item counts in the arrays\r
+    Int    lazy;                   // lazy carry counter\r
+    uLong  lcarry;                 // uLong carry\r
+    uInt   carry;                  // carry (NB not uLong)\r
+    Int    count;                  // work\r
+    const  Unit *cup;              // ..\r
+    Unit  *up;                     // ..\r
+    uLong *lp;                     // ..\r
+    Int    p;                      // ..\r
+  #endif\r
+\r
+  #if DECSUBSET\r
+    decNumber *alloclhs=NULL;      // -> allocated buffer, iff allocated\r
+    decNumber *allocrhs=NULL;      // -> allocated buffer, iff allocated\r
+  #endif\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  // precalculate result sign\r
+  bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);\r
+\r
+  // handle infinities and NaNs\r
+  if (SPECIALARGS) {               // a special bit set\r
+    if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs\r
+      decNaNs(res, lhs, rhs, set, status);\r
+      return res;}\r
+    // one or two infinities; Infinity * 0 is invalid\r
+    if (((lhs->bits & DECINF)==0 && ISZERO(lhs))\r
+      ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {\r
+      *status|=DEC_Invalid_operation;\r
+      return res;}\r
+    decNumberZero(res);\r
+    res->bits=bits|DECINF;         // infinity\r
+    return res;}\r
+\r
+  // For best speed, as in DMSRCN [the original Rexx numerics\r
+  // module], use the shorter number as the multiplier (rhs) and\r
+  // the longer as the multiplicand (lhs) to minimise the number of\r
+  // adds (partial products)\r
+  if (lhs->digits<rhs->digits) {   // swap...\r
+    const decNumber *hold=lhs;\r
+    lhs=rhs;\r
+    rhs=hold;\r
+    }\r
+\r
+  do {                             // protect allocated storage\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operands and set lostDigits status, as needed\r
+      if (lhs->digits>set->digits) {\r
+        alloclhs=decRoundOperand(lhs, set, status);\r
+        if (alloclhs==NULL) break;\r
+        lhs=alloclhs;\r
+        }\r
+      if (rhs->digits>set->digits) {\r
+        allocrhs=decRoundOperand(rhs, set, status);\r
+        if (allocrhs==NULL) break;\r
+        rhs=allocrhs;\r
+        }\r
+      }\r
+    #endif\r
+    // [following code does not require input rounding]\r
+\r
+    #if FASTMUL                    // fastpath can be used\r
+    // use the fast path if there are enough digits in the shorter\r
+    // operand to make the setup and takedown worthwhile\r
+    #define NEEDTWO (DECDPUN*2)    // within two decUnitAddSub calls\r
+    if (rhs->digits>NEEDTWO) {     // use fastpath...\r
+      // calculate the number of elements in each array\r
+      ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; // [ceiling]\r
+      irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; // ..\r
+      iacc=ilhs+irhs;\r
+\r
+      // allocate buffers if required, as usual\r
+      needbytes=ilhs*sizeof(uInt);\r
+      if (needbytes>(Int)sizeof(zlhibuff)) {\r
+        alloclhi=(uInt *)malloc(needbytes);\r
+        zlhi=alloclhi;}\r
+      needbytes=irhs*sizeof(uInt);\r
+      if (needbytes>(Int)sizeof(zrhibuff)) {\r
+        allocrhi=(uInt *)malloc(needbytes);\r
+        zrhi=allocrhi;}\r
+\r
+      // Allocating the accumulator space needs a special case when\r
+      // DECDPUN=1 because when converting the accumulator to Units\r
+      // after the multiplication each 8-byte item becomes 9 1-byte\r
+      // units.  Therefore iacc extra bytes are needed at the front\r
+      // (rounded up to a multiple of 8 bytes), and the uLong\r
+      // accumulator starts offset the appropriate number of units\r
+      // to the right to avoid overwrite during the unchunking.\r
+      needbytes=iacc*sizeof(uLong);\r
+      #if DECDPUN==1\r
+      zoff=(iacc+7)/8;        // items to offset by\r
+      needbytes+=zoff*8;\r
+      #endif\r
+      if (needbytes>(Int)sizeof(zaccbuff)) {\r
+        allocacc=(uLong *)malloc(needbytes);\r
+        zacc=(uLong *)allocacc;}\r
+      if (zlhi==NULL||zrhi==NULL||zacc==NULL) {\r
+        *status|=DEC_Insufficient_storage;\r
+        break;}\r
+\r
+      acc=(Unit *)zacc;       // -> target Unit array\r
+      #if DECDPUN==1\r
+      zacc+=zoff;             // start uLong accumulator to right\r
+      #endif\r
+\r
+      // assemble the chunked copies of the left and right sides\r
+      for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)\r
+        for (p=0, *lip=0; p<FASTDIGS && count>0;\r
+             p+=DECDPUN, cup++, count-=DECDPUN)\r
+          *lip+=*cup*powers[p];\r
+      lmsi=lip-1;     // save -> msi\r
+      for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)\r
+        for (p=0, *rip=0; p<FASTDIGS && count>0;\r
+             p+=DECDPUN, cup++, count-=DECDPUN)\r
+          *rip+=*cup*powers[p];\r
+      rmsi=rip-1;     // save -> msi\r
+\r
+      // zero the accumulator\r
+      for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;\r
+\r
+      /* Start the multiplication */\r
+      // Resolving carries can dominate the cost of accumulating the\r
+      // partial products, so this is only done when necessary.\r
+      // Each uLong item in the accumulator can hold values up to\r
+      // 2**64-1, and each partial product can be as large as\r
+      // (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to\r
+      // itself 18.4 times in a uLong without overflowing, so during\r
+      // the main calculation resolution is carried out every 18th\r
+      // add -- every 162 digits.  Similarly, when FASTDIGS=8, the\r
+      // partial products can be added to themselves 1844.6 times in\r
+      // a uLong without overflowing, so intermediate carry\r
+      // resolution occurs only every 14752 digits.  Hence for common\r
+      // short numbers usually only the one final carry resolution\r
+      // occurs.\r
+      // (The count is set via FASTLAZY to simplify experiments to\r
+      // measure the value of this approach: a 35% improvement on a\r
+      // [34x34] multiply.)\r
+      lazy=FASTLAZY;                         // carry delay count\r
+      for (rip=zrhi; rip<=rmsi; rip++) {     // over each item in rhs\r
+        lp=zacc+(rip-zrhi);                  // where to add the lhs\r
+        for (lip=zlhi; lip<=lmsi; lip++, lp++) { // over each item in lhs\r
+          *lp+=(uLong)(*lip)*(*rip);         // [this should in-line]\r
+          } // lip loop\r
+        lazy--;\r
+        if (lazy>0 && rip!=rmsi) continue;\r
+        lazy=FASTLAZY;                       // reset delay count\r
+        // spin up the accumulator resolving overflows\r
+        for (lp=zacc; lp<zacc+iacc; lp++) {\r
+          if (*lp<FASTBASE) continue;        // it fits\r
+          lcarry=*lp/FASTBASE;               // top part [slow divide]\r
+          // lcarry can exceed 2**32-1, so check again; this check\r
+          // and occasional extra divide (slow) is well worth it, as\r
+          // it allows FASTLAZY to be increased to 18 rather than 4\r
+          // in the FASTDIGS=9 case\r
+          if (lcarry<FASTBASE) carry=(uInt)lcarry;  // [usual]\r
+           else { // two-place carry [fairly rare]\r
+            uInt carry2=(uInt)(lcarry/FASTBASE);    // top top part\r
+            *(lp+2)+=carry2;                        // add to item+2\r
+            *lp-=((uLong)FASTBASE*FASTBASE*carry2); // [slow]\r
+            carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); // [inline]\r
+            }\r
+          *(lp+1)+=carry;                    // add to item above [inline]\r
+          *lp-=((uLong)FASTBASE*carry);      // [inline]\r
+          } // carry resolution\r
+        } // rip loop\r
+\r
+      // The multiplication is complete; time to convert back into\r
+      // units.  This can be done in-place in the accumulator and in\r
+      // 32-bit operations, because carries were resolved after the\r
+      // final add.  This needs N-1 divides and multiplies for\r
+      // each item in the accumulator (which will become up to N\r
+      // units, where 2<=N<=9).\r
+      for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {\r
+        uInt item=(uInt)*lp;                 // decapitate to uInt\r
+        for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {\r
+          uInt part=item/(DECDPUNMAX+1);\r
+          *up=(Unit)(item-(part*(DECDPUNMAX+1)));\r
+          item=part;\r
+          } // p\r
+        *up=(Unit)item; up++;                // [final needs no division]\r
+        } // lp\r
+      accunits=up-acc;                       // count of units\r
+      }\r
+     else { // here to use units directly, without chunking ['old code']\r
+    #endif\r
+\r
+      // if accumulator will be too long for local storage, then allocate\r
+      acc=accbuff;                 // -> assume buffer for accumulator\r
+      needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);\r
+      if (needbytes>(Int)sizeof(accbuff)) {\r
+        allocacc=(Unit *)malloc(needbytes);\r
+        if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}\r
+        acc=(Unit *)allocacc;                // use the allocated space\r
+        }\r
+\r
+      /* Now the main long multiplication loop */\r
+      // Unlike the equivalent in the IBM Java implementation, there\r
+      // is no advantage in calculating from msu to lsu.  So, do it\r
+      // by the book, as it were.\r
+      // Each iteration calculates ACC=ACC+MULTAND*MULT\r
+      accunits=1;                  // accumulator starts at '0'\r
+      *acc=0;                      // .. (lsu=0)\r
+      shift=0;                     // no multiplicand shift at first\r
+      madlength=D2U(lhs->digits);  // this won't change\r
+      mermsup=rhs->lsu+D2U(rhs->digits); // -> msu+1 of multiplier\r
+\r
+      for (mer=rhs->lsu; mer<mermsup; mer++) {\r
+        // Here, *mer is the next Unit in the multiplier to use\r
+        // If non-zero [optimization] add it...\r
+        if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,\r
+                                            lhs->lsu, madlength, 0,\r
+                                            &acc[shift], *mer)\r
+                                            + shift;\r
+         else { // extend acc with a 0; it will be used shortly\r
+          *(acc+accunits)=0;       // [this avoids length of <=0 later]\r
+          accunits++;\r
+          }\r
+        // multiply multiplicand by 10**DECDPUN for next Unit to left\r
+        shift++;                   // add this for 'logical length'\r
+        } // n\r
+    #if FASTMUL\r
+      } // unchunked units\r
+    #endif\r
+    // common end-path\r
+    #if DECTRACE\r
+      decDumpAr('*', acc, accunits);         // Show exact result\r
+    #endif\r
+\r
+    // acc now contains the exact result of the multiplication,\r
+    // possibly with a leading zero unit; build the decNumber from\r
+    // it, noting if any residue\r
+    res->bits=bits;                          // set sign\r
+    res->digits=decGetDigits(acc, accunits); // count digits exactly\r
+\r
+    // There can be a 31-bit wrap in calculating the exponent.\r
+    // This can only happen if both input exponents are negative and\r
+    // both their magnitudes are large.  If there was a wrap, set a\r
+    // safe very negative exponent, from which decFinalize() will\r
+    // raise a hard underflow shortly.\r
+    exponent=lhs->exponent+rhs->exponent;    // calculate exponent\r
+    if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)\r
+      exponent=-2*DECNUMMAXE;                // force underflow\r
+    res->exponent=exponent;                  // OK to overwrite now\r
+\r
+\r
+    // Set the coefficient.  If any rounding, residue records\r
+    decSetCoeff(res, set, acc, res->digits, &residue, status);\r
+    decFinish(res, set, &residue, status);   // final cleanup\r
+    } while(0);                         // end protected\r
+\r
+  if (allocacc!=NULL) free(allocacc);   // drop any storage used\r
+  #if DECSUBSET\r
+  if (allocrhs!=NULL) free(allocrhs);   // ..\r
+  if (alloclhs!=NULL) free(alloclhs);   // ..\r
+  #endif\r
+  #if FASTMUL\r
+  if (allocrhi!=NULL) free(allocrhi);   // ..\r
+  if (alloclhi!=NULL) free(alloclhi);   // ..\r
+  #endif\r
+  return res;\r
+  } // decMultiplyOp\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decExpOp -- effect exponentiation                                  */\r
+/*                                                                    */\r
+/*   This computes C = exp(A)                                         */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context; note that rounding mode has no effect        */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits. status is updated but    */\r
+/* not set.                                                           */\r
+/*                                                                    */\r
+/* Restrictions:                                                      */\r
+/*                                                                    */\r
+/*   digits, emax, and -emin in the context must be less than         */\r
+/*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */\r
+/*   bounds or a zero.  This is an internal routine, so these         */\r
+/*   restrictions are contractual and not enforced.                   */\r
+/*                                                                    */\r
+/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */\r
+/* almost always be correctly rounded, but may be up to 1 ulp in      */\r
+/* error in rare cases.                                               */\r
+/*                                                                    */\r
+/* Finite results will always be full precision and Inexact, except   */\r
+/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */\r
+/* ------------------------------------------------------------------ */\r
+/* This approach used here is similar to the algorithm described in   */\r
+/*                                                                    */\r
+/*   Variable Precision Exponential Function, T. E. Hull and          */\r
+/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */\r
+/*   pp79-91, ACM, June 1986.                                         */\r
+/*                                                                    */\r
+/* with the main difference being that the iterations in the series   */\r
+/* evaluation are terminated dynamically (which does not require the  */\r
+/* extra variable-precision variables which are expensive in this     */\r
+/* context).                                                          */\r
+/*                                                                    */\r
+/* The error analysis in Hull & Abrham's paper applies except for the */\r
+/* round-off error accumulation during the series evaluation.  This   */\r
+/* code does not precalculate the number of iterations and so cannot  */\r
+/* use Horner's scheme.  Instead, the accumulation is done at double- */\r
+/* precision, which ensures that the additions of the terms are exact */\r
+/* and do not accumulate round-off (and any round-off errors in the   */\r
+/* terms themselves move 'to the right' faster than they can          */\r
+/* accumulate).  This code also extends the calculation by allowing,  */\r
+/* in the spirit of other decNumber operators, the input to be more   */\r
+/* precise than the result (the precision used is based on the more   */\r
+/* precise of the input or requested result).                         */\r
+/*                                                                    */\r
+/* Implementation notes:                                              */\r
+/*                                                                    */\r
+/* 1. This is separated out as decExpOp so it can be called from      */\r
+/*    other Mathematical functions (notably Ln) with a wider range    */\r
+/*    than normal.  In particular, it can handle the slightly wider   */\r
+/*    (double) range needed by Ln (which has to be able to calculate  */\r
+/*    exp(-x) where x can be the tiniest number (Ntiny).              */\r
+/*                                                                    */\r
+/* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */\r
+/*    iterations by appoximately a third with additional (although    */\r
+/*    diminishing) returns as the range is reduced to even smaller    */\r
+/*    fractions.  However, h (the power of 10 used to correct the     */\r
+/*    result at the end, see below) must be kept <=8 as otherwise     */\r
+/*    the final result cannot be computed.  Hence the leverage is a   */\r
+/*    sliding value (8-h), where potentially the range is reduced     */\r
+/*    more for smaller values.                                        */\r
+/*                                                                    */\r
+/*    The leverage that can be applied in this way is severely        */\r
+/*    limited by the cost of the raise-to-the power at the end,       */\r
+/*    which dominates when the number of iterations is small (less    */\r
+/*    than ten) or when rhs is short.  As an example, the adjustment  */\r
+/*    x**10,000,000 needs 31 multiplications, all but one full-width. */\r
+/*                                                                    */\r
+/* 3. The restrictions (especially precision) could be raised with    */\r
+/*    care, but the full decNumber range seems very hard within the   */\r
+/*    32-bit limits.                                                  */\r
+/*                                                                    */\r
+/* 4. The working precisions for the static buffers are twice the     */\r
+/*    obvious size to allow for calls from decNumberPower.            */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decExpOp(decNumber *res, const decNumber *rhs,\r
+                         decContext *set, uInt *status) {\r
+  uInt ignore=0;                   // working status\r
+  Int h;                           // adjusted exponent for 0.xxxx\r
+  Int p;                           // working precision\r
+  Int residue;                     // rounding residue\r
+  uInt needbytes;                  // for space calculations\r
+  const decNumber *x=rhs;          // (may point to safe copy later)\r
+  decContext aset, tset, dset;     // working contexts\r
+  Int comp;                        // work\r
+\r
+  // the argument is often copied to normalize it, so (unusually) it\r
+  // is treated like other buffers, using DECBUFFER, +1 in case\r
+  // DECBUFFER is 0\r
+  decNumber bufr[D2N(DECBUFFER*2+1)];\r
+  decNumber *allocrhs=NULL;        // non-NULL if rhs buffer allocated\r
+\r
+  // the working precision will be no more than set->digits+8+1\r
+  // so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER\r
+  // is 0 (and twice that for the accumulator)\r
+\r
+  // buffer for t, term (working precision plus)\r
+  decNumber buft[D2N(DECBUFFER*2+9+1)];\r
+  decNumber *allocbuft=NULL;       // -> allocated buft, iff allocated\r
+  decNumber *t=buft;               // term\r
+  // buffer for a, accumulator (working precision * 2), at least 9\r
+  decNumber bufa[D2N(DECBUFFER*4+18+1)];\r
+  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated\r
+  decNumber *a=bufa;               // accumulator\r
+  // decNumber for the divisor term; this needs at most 9 digits\r
+  // and so can be fixed size [16 so can use standard context]\r
+  decNumber bufd[D2N(16)];\r
+  decNumber *d=bufd;               // divisor\r
+  decNumber numone;                // constant 1\r
+\r
+  #if DECCHECK\r
+  Int iterations=0;                // for later sanity check\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                                  // protect allocated storage\r
+    if (SPECIALARG) {                   // handle infinities and NaNs\r
+      if (decNumberIsInfinite(rhs)) {   // an infinity\r
+        if (decNumberIsNegative(rhs))   // -Infinity -> +0\r
+          decNumberZero(res);\r
+         else decNumberCopy(res, rhs);  // +Infinity -> self\r
+        }\r
+       else decNaNs(res, rhs, NULL, set, status); // a NaN\r
+      break;}\r
+\r
+    if (ISZERO(rhs)) {                  // zeros -> exact 1\r
+      decNumberZero(res);               // make clean 1\r
+      *res->lsu=1;                      // ..\r
+      break;}                           // [no status to set]\r
+\r
+    // e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path\r
+    // positive and negative tiny cases which will result in inexact\r
+    // 1.  This also allows the later add-accumulate to always be\r
+    // exact (because its length will never be more than twice the\r
+    // working precision).\r
+    // The comparator (tiny) needs just one digit, so use the\r
+    // decNumber d for it (reused as the divisor, etc., below); its\r
+    // exponent is such that if x is positive it will have\r
+    // set->digits-1 zeros between the decimal point and the digit,\r
+    // which is 4, and if x is negative one more zero there as the\r
+    // more precise result will be of the form 0.9999999 rather than\r
+    // 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0\r
+    // or 0.00000004 if digits=7 and x<0.  If RHS not larger than\r
+    // this then the result will be 1.000000\r
+    decNumberZero(d);                   // clean\r
+    *d->lsu=4;                          // set 4 ..\r
+    d->exponent=-set->digits;           // * 10**(-d)\r
+    if (decNumberIsNegative(rhs)) d->exponent--;  // negative case\r
+    comp=decCompare(d, rhs, 1);         // signless compare\r
+    if (comp==BADINT) {\r
+      *status|=DEC_Insufficient_storage;\r
+      break;}\r
+    if (comp>=0) {                      // rhs < d\r
+      Int shift=set->digits-1;\r
+      decNumberZero(res);               // set 1\r
+      *res->lsu=1;                      // ..\r
+      res->digits=decShiftToMost(res->lsu, 1, shift);\r
+      res->exponent=-shift;                  // make 1.0000...\r
+      *status|=DEC_Inexact | DEC_Rounded;    // .. inexactly\r
+      break;} // tiny\r
+\r
+    // set up the context to be used for calculating a, as this is\r
+    // used on both paths below\r
+    decContextDefault(&aset, DEC_INIT_DECIMAL64);\r
+    // accumulator bounds are as requested (could underflow)\r
+    aset.emax=set->emax;                // usual bounds\r
+    aset.emin=set->emin;                // ..\r
+    aset.clamp=0;                       // and no concrete format\r
+\r
+    // calculate the adjusted (Hull & Abrham) exponent (where the\r
+    // decimal point is just to the left of the coefficient msd)\r
+    h=rhs->exponent+rhs->digits;\r
+    // if h>8 then 10**h cannot be calculated safely; however, when\r
+    // h=8 then exp(|rhs|) will be at least exp(1E+7) which is at\r
+    // least 6.59E+4342944, so (due to the restriction on Emax/Emin)\r
+    // overflow (or underflow to 0) is guaranteed -- so this case can\r
+    // be handled by simply forcing the appropriate excess\r
+    if (h>8) {                          // overflow/underflow\r
+      // set up here so Power call below will over or underflow to\r
+      // zero; set accumulator to either 2 or 0.02\r
+      // [stack buffer for a is always big enough for this]\r
+      decNumberZero(a);\r
+      *a->lsu=2;                        // not 1 but < exp(1)\r
+      if (decNumberIsNegative(rhs)) a->exponent=-2; // make 0.02\r
+      h=8;                              // clamp so 10**h computable\r
+      p=9;                              // set a working precision\r
+      }\r
+     else {                             // h<=8\r
+      Int maxlever=(rhs->digits>8?1:0);\r
+      // [could/should increase this for precisions >40 or so, too]\r
+\r
+      // if h is 8, cannot normalize to a lower upper limit because\r
+      // the final result will not be computable (see notes above),\r
+      // but leverage can be applied whenever h is less than 8.\r
+      // Apply as much as possible, up to a MAXLEVER digits, which\r
+      // sets the tradeoff against the cost of the later a**(10**h).\r
+      // As h is increased, the working precision below also\r
+      // increases to compensate for the "constant digits at the\r
+      // front" effect.\r
+      Int lever=MINI(8-h, maxlever);    // leverage attainable\r
+      Int use=-rhs->digits-lever;       // exponent to use for RHS\r
+      h+=lever;                         // apply leverage selected\r
+      if (h<0) {                        // clamp\r
+        use+=h;                         // [may end up subnormal]\r
+        h=0;\r
+        }\r
+      // Take a copy of RHS if it needs normalization (true whenever x>=1)\r
+      if (rhs->exponent!=use) {\r
+        decNumber *newrhs=bufr;         // assume will fit on stack\r
+        needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);\r
+        if (needbytes>sizeof(bufr)) {   // need malloc space\r
+          allocrhs=(decNumber *)malloc(needbytes);\r
+          if (allocrhs==NULL) {         // hopeless -- abandon\r
+            *status|=DEC_Insufficient_storage;\r
+            break;}\r
+          newrhs=allocrhs;              // use the allocated space\r
+          }\r
+        decNumberCopy(newrhs, rhs);     // copy to safe space\r
+        newrhs->exponent=use;           // normalize; now <1\r
+        x=newrhs;                       // ready for use\r
+        // decNumberShow(x);\r
+        }\r
+\r
+      // Now use the usual power series to evaluate exp(x).  The\r
+      // series starts as 1 + x + x^2/2 ... so prime ready for the\r
+      // third term by setting the term variable t=x, the accumulator\r
+      // a=1, and the divisor d=2.\r
+\r
+      // First determine the working precision.  From Hull & Abrham\r
+      // this is set->digits+h+2.  However, if x is 'over-precise' we\r
+      // need to allow for all its digits to potentially participate\r
+      // (consider an x where all the excess digits are 9s) so in\r
+      // this case use x->digits+h+2\r
+      p=MAXI(x->digits, set->digits)+h+2;    // [h<=8]\r
+\r
+      // a and t are variable precision, and depend on p, so space\r
+      // must be allocated for them if necessary\r
+\r
+      // the accumulator needs to be able to hold 2p digits so that\r
+      // the additions on the second and subsequent iterations are\r
+      // sufficiently exact.\r
+      needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);\r
+      if (needbytes>sizeof(bufa)) {     // need malloc space\r
+        allocbufa=(decNumber *)malloc(needbytes);\r
+        if (allocbufa==NULL) {          // hopeless -- abandon\r
+          *status|=DEC_Insufficient_storage;\r
+          break;}\r
+        a=allocbufa;                    // use the allocated space\r
+        }\r
+      // the term needs to be able to hold p digits (which is\r
+      // guaranteed to be larger than x->digits, so the initial copy\r
+      // is safe); it may also be used for the raise-to-power\r
+      // calculation below, which needs an extra two digits\r
+      needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);\r
+      if (needbytes>sizeof(buft)) {     // need malloc space\r
+        allocbuft=(decNumber *)malloc(needbytes);\r
+        if (allocbuft==NULL) {          // hopeless -- abandon\r
+          *status|=DEC_Insufficient_storage;\r
+          break;}\r
+        t=allocbuft;                    // use the allocated space\r
+        }\r
+\r
+      decNumberCopy(t, x);              // term=x\r
+      decNumberZero(a); *a->lsu=1;      // accumulator=1\r
+      decNumberZero(d); *d->lsu=2;      // divisor=2\r
+      decNumberZero(&numone); *numone.lsu=1; // constant 1 for increment\r
+\r
+      // set up the contexts for calculating a, t, and d\r
+      decContextDefault(&tset, DEC_INIT_DECIMAL64);\r
+      dset=tset;\r
+      // accumulator bounds are set above, set precision now\r
+      aset.digits=p*2;                  // double\r
+      // term bounds avoid any underflow or overflow\r
+      tset.digits=p;\r
+      tset.emin=DEC_MIN_EMIN;           // [emax is plenty]\r
+      // [dset.digits=16, etc., are sufficient]\r
+\r
+      // finally ready to roll\r
+      for (;;) {\r
+        #if DECCHECK\r
+        iterations++;\r
+        #endif\r
+        // only the status from the accumulation is interesting\r
+        // [but it should remain unchanged after first add]\r
+        decAddOp(a, a, t, &aset, 0, status);           // a=a+t\r
+        decMultiplyOp(t, t, x, &tset, &ignore);        // t=t*x\r
+        decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  // t=t/d\r
+        // the iteration ends when the term cannot affect the result,\r
+        // if rounded to p digits, which is when its value is smaller\r
+        // than the accumulator by p+1 digits.  There must also be\r
+        // full precision in a.\r
+        if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))\r
+            && (a->digits>=p)) break;\r
+        decAddOp(d, d, &numone, &dset, 0, &ignore);    // d=d+1\r
+        } // iterate\r
+\r
+      #if DECCHECK\r
+      // just a sanity check; comment out test to show always\r
+      if (iterations>p+3)\r
+        printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",\r
+               (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);\r
+      #endif\r
+      } // h<=8\r
+\r
+    // apply postconditioning: a=a**(10**h) -- this is calculated\r
+    // at a slightly higher precision than Hull & Abrham suggest\r
+    if (h>0) {\r
+      Int seenbit=0;               // set once a 1-bit is seen\r
+      Int i;                       // counter\r
+      Int n=powers[h];             // always positive\r
+      aset.digits=p+2;             // sufficient precision\r
+      // avoid the overhead and many extra digits of decNumberPower\r
+      // as all that is needed is the short 'multipliers' loop; here\r
+      // accumulate the answer into t\r
+      decNumberZero(t); *t->lsu=1; // acc=1\r
+      for (i=1;;i++){              // for each bit [top bit ignored]\r
+        // abandon if have had overflow or terminal underflow\r
+        if (*status & (DEC_Overflow|DEC_Underflow)) { // interesting?\r
+          if (*status&DEC_Overflow || ISZERO(t)) break;}\r
+        n=n<<1;                    // move next bit to testable position\r
+        if (n<0) {                 // top bit is set\r
+          seenbit=1;               // OK, have a significant bit\r
+          decMultiplyOp(t, t, a, &aset, status); // acc=acc*x\r
+          }\r
+        if (i==31) break;          // that was the last bit\r
+        if (!seenbit) continue;    // no need to square 1\r
+        decMultiplyOp(t, t, t, &aset, status); // acc=acc*acc [square]\r
+        } /*i*/ // 32 bits\r
+      // decNumberShow(t);\r
+      a=t;                         // and carry on using t instead of a\r
+      }\r
+\r
+    // Copy and round the result to res\r
+    residue=1;                          // indicate dirt to right ..\r
+    if (ISZERO(a)) residue=0;           // .. unless underflowed to 0\r
+    aset.digits=set->digits;            // [use default rounding]\r
+    decCopyFit(res, a, &aset, &residue, status); // copy & shorten\r
+    decFinish(res, set, &residue, status);       // cleanup/set flags\r
+    } while(0);                         // end protected\r
+\r
+  if (allocrhs !=NULL) free(allocrhs);  // drop any storage used\r
+  if (allocbufa!=NULL) free(allocbufa); // ..\r
+  if (allocbuft!=NULL) free(allocbuft); // ..\r
+  // [status is handled by caller]\r
+  return res;\r
+  } // decExpOp\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* Initial-estimate natural logarithm table                           */\r
+/*                                                                    */\r
+/*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */\r
+/*           The result is a 4-digit encode of the coefficient (c=the */\r
+/*           top 14 bits encoding 0-9999) and a 2-digit encode of the */\r
+/*           exponent (e=the bottom 2 bits encoding 0-3)              */\r
+/*                                                                    */\r
+/*           The resulting value is given by:                         */\r
+/*                                                                    */\r
+/*             v = -c * 10**(-e-3)                                    */\r
+/*                                                                    */\r
+/*           where e and c are extracted from entry k = LNnn[x-10]    */\r
+/*           where x is truncated (NB) into the range 10 through 99,  */\r
+/*           and then c = k>>2 and e = k&3.                           */\r
+/* ------------------------------------------------------------------ */\r
+const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,\r
+  6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,\r
+  5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,\r
+ 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,\r
+ 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,\r
+ 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,\r
+ 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,\r
+ 10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,\r
+  5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,\r
+ 10130,  6046, 20055};\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decLnOp -- effect natural logarithm                                */\r
+/*                                                                    */\r
+/*   This computes C = ln(A)                                          */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A                                */\r
+/*   rhs is A                                                         */\r
+/*   set is the context; note that rounding mode has no effect        */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Notable cases:                                                     */\r
+/*   A<0 -> Invalid                                                   */\r
+/*   A=0 -> -Infinity (Exact)                                         */\r
+/*   A=+Infinity -> +Infinity (Exact)                                 */\r
+/*   A=1 exactly -> 0 (Exact)                                         */\r
+/*                                                                    */\r
+/* Restrictions (as for Exp):                                         */\r
+/*                                                                    */\r
+/*   digits, emax, and -emin in the context must be less than         */\r
+/*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */\r
+/*   bounds or a zero.  This is an internal routine, so these         */\r
+/*   restrictions are contractual and not enforced.                   */\r
+/*                                                                    */\r
+/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */\r
+/* almost always be correctly rounded, but may be up to 1 ulp in      */\r
+/* error in rare cases.                                               */\r
+/* ------------------------------------------------------------------ */\r
+/* The result is calculated using Newton's method, with each          */\r
+/* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */\r
+/* Epperson 1989.                                                     */\r
+/*                                                                    */\r
+/* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */\r
+/* This has to be calculated at the sum of the precision of x and the */\r
+/* working precision.                                                 */\r
+/*                                                                    */\r
+/* Implementation notes:                                              */\r
+/*                                                                    */\r
+/* 1. This is separated out as decLnOp so it can be called from       */\r
+/*    other Mathematical functions (e.g., Log 10) with a wider range  */\r
+/*    than normal.  In particular, it can handle the slightly wider   */\r
+/*    (+9+2) range needed by a power function.                        */\r
+/*                                                                    */\r
+/* 2. The speed of this function is about 10x slower than exp, as     */\r
+/*    it typically needs 4-6 iterations for short numbers, and the    */\r
+/*    extra precision needed adds a squaring effect, twice.           */\r
+/*                                                                    */\r
+/* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */\r
+/*    as these are common requests.  ln(10) is used by log10(x).      */\r
+/*                                                                    */\r
+/* 4. An iteration might be saved by widening the LNnn table, and     */\r
+/*    would certainly save at least one if it were made ten times     */\r
+/*    bigger, too (for truncated fractions 0.100 through 0.999).      */\r
+/*    However, for most practical evaluations, at least four or five  */\r
+/*    iterations will be neede -- so this would only speed up by      */\r
+/*    20-25% and that probably does not justify increasing the table  */\r
+/*    size.                                                           */\r
+/*                                                                    */\r
+/* 5. The static buffers are larger than might be expected to allow   */\r
+/*    for calls from decNumberPower.                                  */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decLnOp(decNumber *res, const decNumber *rhs,\r
+                    decContext *set, uInt *status) {\r
+  uInt ignore=0;                   // working status accumulator\r
+  uInt needbytes;                  // for space calculations\r
+  Int residue;                     // rounding residue\r
+  Int r;                           // rhs=f*10**r [see below]\r
+  Int p;                           // working precision\r
+  Int pp;                          // precision for iteration\r
+  Int t;                           // work\r
+\r
+  // buffers for a (accumulator, typically precision+2) and b\r
+  // (adjustment calculator, same size)\r
+  decNumber bufa[D2N(DECBUFFER+12)];\r
+  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated\r
+  decNumber *a=bufa;               // accumulator/work\r
+  decNumber bufb[D2N(DECBUFFER*2+2)];\r
+  decNumber *allocbufb=NULL;       // -> allocated bufa, iff allocated\r
+  decNumber *b=bufb;               // adjustment/work\r
+\r
+  decNumber  numone;               // constant 1\r
+  decNumber  cmp;                  // work\r
+  decContext aset, bset;           // working contexts\r
+\r
+  #if DECCHECK\r
+  Int iterations=0;                // for later sanity check\r
+  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                                  // protect allocated storage\r
+    if (SPECIALARG) {                   // handle infinities and NaNs\r
+      if (decNumberIsInfinite(rhs)) {   // an infinity\r
+        if (decNumberIsNegative(rhs))   // -Infinity -> error\r
+          *status|=DEC_Invalid_operation;\r
+         else decNumberCopy(res, rhs);  // +Infinity -> self\r
+        }\r
+       else decNaNs(res, rhs, NULL, set, status); // a NaN\r
+      break;}\r
+\r
+    if (ISZERO(rhs)) {                  // +/- zeros -> -Infinity\r
+      decNumberZero(res);               // make clean\r
+      res->bits=DECINF|DECNEG;          // set - infinity\r
+      break;}                           // [no status to set]\r
+\r
+    // Non-zero negatives are bad...\r
+    if (decNumberIsNegative(rhs)) {     // -x -> error\r
+      *status|=DEC_Invalid_operation;\r
+      break;}\r
+\r
+    // Here, rhs is positive, finite, and in range\r
+\r
+    // lookaside fastpath code for ln(2) and ln(10) at common lengths\r
+    if (rhs->exponent==0 && set->digits<=40) {\r
+      #if DECDPUN==1\r
+      if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { // ln(10)\r
+      #else\r
+      if (rhs->lsu[0]==10 && rhs->digits==2) {                  // ln(10)\r
+      #endif\r
+        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;\r
+        #define LN10 "2.302585092994045684017991454684364207601"\r
+        decNumberFromString(res, LN10, &aset);\r
+        *status|=(DEC_Inexact | DEC_Rounded); // is inexact\r
+        break;}\r
+      if (rhs->lsu[0]==2 && rhs->digits==1) { // ln(2)\r
+        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;\r
+        #define LN2 "0.6931471805599453094172321214581765680755"\r
+        decNumberFromString(res, LN2, &aset);\r
+        *status|=(DEC_Inexact | DEC_Rounded);\r
+        break;}\r
+      } // integer and short\r
+\r
+    // Determine the working precision.  This is normally the\r
+    // requested precision + 2, with a minimum of 9.  However, if\r
+    // the rhs is 'over-precise' then allow for all its digits to\r
+    // potentially participate (consider an rhs where all the excess\r
+    // digits are 9s) so in this case use rhs->digits+2.\r
+    p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;\r
+\r
+    // Allocate space for the accumulator and the high-precision\r
+    // adjustment calculator, if necessary.  The accumulator must\r
+    // be able to hold p digits, and the adjustment up to\r
+    // rhs->digits+p digits.  They are also made big enough for 16\r
+    // digits so that they can be used for calculating the initial\r
+    // estimate.\r
+    needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);\r
+    if (needbytes>sizeof(bufa)) {     // need malloc space\r
+      allocbufa=(decNumber *)malloc(needbytes);\r
+      if (allocbufa==NULL) {          // hopeless -- abandon\r
+        *status|=DEC_Insufficient_storage;\r
+        break;}\r
+      a=allocbufa;                    // use the allocated space\r
+      }\r
+    pp=p+rhs->digits;\r
+    needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);\r
+    if (needbytes>sizeof(bufb)) {     // need malloc space\r
+      allocbufb=(decNumber *)malloc(needbytes);\r
+      if (allocbufb==NULL) {          // hopeless -- abandon\r
+        *status|=DEC_Insufficient_storage;\r
+        break;}\r
+      b=allocbufb;                    // use the allocated space\r
+      }\r
+\r
+    // Prepare an initial estimate in acc. Calculate this by\r
+    // considering the coefficient of x to be a normalized fraction,\r
+    // f, with the decimal point at far left and multiplied by\r
+    // 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and\r
+    //   ln(x) = ln(f) + ln(10)*r\r
+    // Get the initial estimate for ln(f) from a small lookup\r
+    // table (see above) indexed by the first two digits of f,\r
+    // truncated.\r
+\r
+    decContextDefault(&aset, DEC_INIT_DECIMAL64); // 16-digit extended\r
+    r=rhs->exponent+rhs->digits;        // 'normalised' exponent\r
+    decNumberFromInt32(a, r);           // a=r\r
+    decNumberFromInt32(b, 2302585);     // b=ln(10) (2.302585)\r
+    b->exponent=-6;                     //  ..\r
+    decMultiplyOp(a, a, b, &aset, &ignore);  // a=a*b\r
+    // now get top two digits of rhs into b by simple truncate and\r
+    // force to integer\r
+    residue=0;                          // (no residue)\r
+    aset.digits=2; aset.round=DEC_ROUND_DOWN;\r
+    decCopyFit(b, rhs, &aset, &residue, &ignore); // copy & shorten\r
+    b->exponent=0;                      // make integer\r
+    t=decGetInt(b);                     // [cannot fail]\r
+    if (t<10) t=X10(t);                 // adjust single-digit b\r
+    t=LNnn[t-10];                       // look up ln(b)\r
+    decNumberFromInt32(b, t>>2);        // b=ln(b) coefficient\r
+    b->exponent=-(t&3)-3;               // set exponent\r
+    b->bits=DECNEG;                     // ln(0.10)->ln(0.99) always -ve\r
+    aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; // restore\r
+    decAddOp(a, a, b, &aset, 0, &ignore); // acc=a+b\r
+    // the initial estimate is now in a, with up to 4 digits correct.\r
+    // When rhs is at or near Nmax the estimate will be low, so we\r
+    // will approach it from below, avoiding overflow when calling exp.\r
+\r
+    decNumberZero(&numone); *numone.lsu=1;   // constant 1 for adjustment\r
+\r
+    // accumulator bounds are as requested (could underflow, but\r
+    // cannot overflow)\r
+    aset.emax=set->emax;\r
+    aset.emin=set->emin;\r
+    aset.clamp=0;                       // no concrete format\r
+    // set up a context to be used for the multiply and subtract\r
+    bset=aset;\r
+    bset.emax=DEC_MAX_MATH*2;           // use double bounds for the\r
+    bset.emin=-DEC_MAX_MATH*2;          // adjustment calculation\r
+                                        // [see decExpOp call below]\r
+    // for each iteration double the number of digits to calculate,\r
+    // up to a maximum of p\r
+    pp=9;                               // initial precision\r
+    // [initially 9 as then the sequence starts 7+2, 16+2, and\r
+    // 34+2, which is ideal for standard-sized numbers]\r
+    aset.digits=pp;                     // working context\r
+    bset.digits=pp+rhs->digits;         // wider context\r
+    for (;;) {                          // iterate\r
+      #if DECCHECK\r
+      iterations++;\r
+      if (iterations>24) break;         // consider 9 * 2**24\r
+      #endif\r
+      // calculate the adjustment (exp(-a)*x-1) into b.  This is a\r
+      // catastrophic subtraction but it really is the difference\r
+      // from 1 that is of interest.\r
+      // Use the internal entry point to Exp as it allows the double\r
+      // range for calculating exp(-a) when a is the tiniest subnormal.\r
+      a->bits^=DECNEG;                  // make -a\r
+      decExpOp(b, a, &bset, &ignore);   // b=exp(-a)\r
+      a->bits^=DECNEG;                  // restore sign of a\r
+      // now multiply by rhs and subtract 1, at the wider precision\r
+      decMultiplyOp(b, b, rhs, &bset, &ignore);        // b=b*rhs\r
+      decAddOp(b, b, &numone, &bset, DECNEG, &ignore); // b=b-1\r
+\r
+      // the iteration ends when the adjustment cannot affect the\r
+      // result by >=0.5 ulp (at the requested digits), which\r
+      // is when its value is smaller than the accumulator by\r
+      // set->digits+1 digits (or it is zero) -- this is a looser\r
+      // requirement than for Exp because all that happens to the\r
+      // accumulator after this is the final rounding (but note that\r
+      // there must also be full precision in a, or a=0).\r
+\r
+      if (decNumberIsZero(b) ||\r
+          (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {\r
+        if (a->digits==p) break;\r
+        if (decNumberIsZero(a)) {\r
+          decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); // rhs=1 ?\r
+          if (cmp.lsu[0]==0) a->exponent=0;            // yes, exact 0\r
+           else *status|=(DEC_Inexact | DEC_Rounded);  // no, inexact\r
+          break;\r
+          }\r
+        // force padding if adjustment has gone to 0 before full length\r
+        if (decNumberIsZero(b)) b->exponent=a->exponent-p;\r
+        }\r
+\r
+      // not done yet ...\r
+      decAddOp(a, a, b, &aset, 0, &ignore);  // a=a+b for next estimate\r
+      if (pp==p) continue;                   // precision is at maximum\r
+      // lengthen the next calculation\r
+      pp=pp*2;                               // double precision\r
+      if (pp>p) pp=p;                        // clamp to maximum\r
+      aset.digits=pp;                        // working context\r
+      bset.digits=pp+rhs->digits;            // wider context\r
+      } // Newton's iteration\r
+\r
+    #if DECCHECK\r
+    // just a sanity check; remove the test to show always\r
+    if (iterations>24)\r
+      printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",\r
+            (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);\r
+    #endif\r
+\r
+    // Copy and round the result to res\r
+    residue=1;                          // indicate dirt to right\r
+    if (ISZERO(a)) residue=0;           // .. unless underflowed to 0\r
+    aset.digits=set->digits;            // [use default rounding]\r
+    decCopyFit(res, a, &aset, &residue, status); // copy & shorten\r
+    decFinish(res, set, &residue, status);       // cleanup/set flags\r
+    } while(0);                         // end protected\r
+\r
+  if (allocbufa!=NULL) free(allocbufa); // drop any storage used\r
+  if (allocbufb!=NULL) free(allocbufb); // ..\r
+  // [status is handled by caller]\r
+  return res;\r
+  } // decLnOp\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decQuantizeOp  -- force exponent to requested value                */\r
+/*                                                                    */\r
+/*   This computes C = op(A, B), where op adjusts the coefficient     */\r
+/*   of C (by rounding or shifting) such that the exponent (-scale)   */\r
+/*   of C has the value B or matches the exponent of B.               */\r
+/*   The numerical value of C will equal A, except for the effects of */\r
+/*   any rounding that occurred.                                      */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A or B                           */\r
+/*   lhs is A, the number to adjust                                   */\r
+/*   rhs is B, the requested exponent                                 */\r
+/*   set is the context                                               */\r
+/*   quant is 1 for quantize or 0 for rescale                         */\r
+/*   status is the status accumulator (this can be called without     */\r
+/*          risk of control loss)                                     */\r
+/*                                                                    */\r
+/* C must have space for set->digits digits.                          */\r
+/*                                                                    */\r
+/* Unless there is an error or the result is infinite, the exponent   */\r
+/* after the operation is guaranteed to be that requested.            */\r
+/* ------------------------------------------------------------------ */\r
+static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,\r
+                                 const decNumber *rhs, decContext *set,\r
+                                 Flag quant, uInt *status) {\r
+  #if DECSUBSET\r
+  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated\r
+  decNumber *allocrhs=NULL;        // .., rhs\r
+  #endif\r
+  const decNumber *inrhs=rhs;      // save original rhs\r
+  Int   reqdigits=set->digits;     // requested DIGITS\r
+  Int   reqexp;                    // requested exponent [-scale]\r
+  Int   residue=0;                 // rounding residue\r
+  Int   etiny=set->emin-(reqdigits-1);\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                             // protect allocated storage\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operands and set lostDigits status, as needed\r
+      if (lhs->digits>reqdigits) {\r
+        alloclhs=decRoundOperand(lhs, set, status);\r
+        if (alloclhs==NULL) break;\r
+        lhs=alloclhs;\r
+        }\r
+      if (rhs->digits>reqdigits) { // [this only checks lostDigits]\r
+        allocrhs=decRoundOperand(rhs, set, status);\r
+        if (allocrhs==NULL) break;\r
+        rhs=allocrhs;\r
+        }\r
+      }\r
+    #endif\r
+    // [following code does not require input rounding]\r
+\r
+    // Handle special values\r
+    if (SPECIALARGS) {\r
+      // NaNs get usual processing\r
+      if (SPECIALARGS & (DECSNAN | DECNAN))\r
+        decNaNs(res, lhs, rhs, set, status);\r
+      // one infinity but not both is bad\r
+      else if ((lhs->bits ^ rhs->bits) & DECINF)\r
+        *status|=DEC_Invalid_operation;\r
+      // both infinity: return lhs\r
+      else decNumberCopy(res, lhs);          // [nop if in place]\r
+      break;\r
+      }\r
+\r
+    // set requested exponent\r
+    if (quant) reqexp=inrhs->exponent;  // quantize -- match exponents\r
+     else {                             // rescale -- use value of rhs\r
+      // Original rhs must be an integer that fits and is in range,\r
+      // which could be from -1999999997 to +999999999, thanks to\r
+      // subnormals\r
+      reqexp=decGetInt(inrhs);               // [cannot fail]\r
+      }\r
+\r
+    #if DECSUBSET\r
+    if (!set->extended) etiny=set->emin;     // no subnormals\r
+    #endif\r
+\r
+    if (reqexp==BADINT                       // bad (rescale only) or ..\r
+     || reqexp==BIGODD || reqexp==BIGEVEN    // very big (ditto) or ..\r
+     || (reqexp<etiny)                       // < lowest\r
+     || (reqexp>set->emax)) {                // > emax\r
+      *status|=DEC_Invalid_operation;\r
+      break;}\r
+\r
+    // the RHS has been processed, so it can be overwritten now if necessary\r
+    if (ISZERO(lhs)) {                       // zero coefficient unchanged\r
+      decNumberCopy(res, lhs);               // [nop if in place]\r
+      res->exponent=reqexp;                  // .. just set exponent\r
+      #if DECSUBSET\r
+      if (!set->extended) res->bits=0;       // subset specification; no -0\r
+      #endif\r
+      }\r
+     else {                                  // non-zero lhs\r
+      Int adjust=reqexp-lhs->exponent;       // digit adjustment needed\r
+      // if adjusted coefficient will definitely not fit, give up now\r
+      if ((lhs->digits-adjust)>reqdigits) {\r
+        *status|=DEC_Invalid_operation;\r
+        break;\r
+        }\r
+\r
+      if (adjust>0) {                        // increasing exponent\r
+        // this will decrease the length of the coefficient by adjust\r
+        // digits, and must round as it does so\r
+        decContext workset;                  // work\r
+        workset=*set;                        // clone rounding, etc.\r
+        workset.digits=lhs->digits-adjust;   // set requested length\r
+        // [note that the latter can be <1, here]\r
+        decCopyFit(res, lhs, &workset, &residue, status); // fit to result\r
+        decApplyRound(res, &workset, residue, status);    // .. and round\r
+        residue=0;                                        // [used]\r
+        // If just rounded a 999s case, exponent will be off by one;\r
+        // adjust back (after checking space), if so.\r
+        if (res->exponent>reqexp) {\r
+          // re-check needed, e.g., for quantize(0.9999, 0.001) under\r
+          // set->digits==3\r
+          if (res->digits==reqdigits) {      // cannot shift by 1\r
+            *status&=~(DEC_Inexact | DEC_Rounded); // [clean these]\r
+            *status|=DEC_Invalid_operation;\r
+            break;\r
+            }\r
+          res->digits=decShiftToMost(res->lsu, res->digits, 1); // shift\r
+          res->exponent--;                   // (re)adjust the exponent.\r
+          }\r
+        #if DECSUBSET\r
+        if (ISZERO(res) && !set->extended) res->bits=0; // subset; no -0\r
+        #endif\r
+        } // increase\r
+       else /* adjust<=0 */ {                // decreasing or = exponent\r
+        // this will increase the length of the coefficient by -adjust\r
+        // digits, by adding zero or more trailing zeros; this is\r
+        // already checked for fit, above\r
+        decNumberCopy(res, lhs);             // [it will fit]\r
+        // if padding needed (adjust<0), add it now...\r
+        if (adjust<0) {\r
+          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);\r
+          res->exponent+=adjust;             // adjust the exponent\r
+          }\r
+        } // decrease\r
+      } // non-zero\r
+\r
+    // Check for overflow [do not use Finalize in this case, as an\r
+    // overflow here is a "don't fit" situation]\r
+    if (res->exponent>set->emax-res->digits+1) {  // too big\r
+      *status|=DEC_Invalid_operation;\r
+      break;\r
+      }\r
+     else {\r
+      decFinalize(res, set, &residue, status);    // set subnormal flags\r
+      *status&=~DEC_Underflow;          // suppress Underflow [as per 754]\r
+      }\r
+    } while(0);                         // end protected\r
+\r
+  #if DECSUBSET\r
+  if (allocrhs!=NULL) free(allocrhs);   // drop any storage used\r
+  if (alloclhs!=NULL) free(alloclhs);   // ..\r
+  #endif\r
+  return res;\r
+  } // decQuantizeOp\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decCompareOp -- compare, min, or max two Numbers                   */\r
+/*                                                                    */\r
+/*   This computes C = A ? B and carries out one of four operations:  */\r
+/*     COMPARE    -- returns the signum (as a number) giving the      */\r
+/*                   result of a comparison unless one or both        */\r
+/*                   operands is a NaN (in which case a NaN results)  */\r
+/*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */\r
+/*                   Invalid operation.                               */\r
+/*     COMPMAX    -- returns the larger of the operands, using the    */\r
+/*                   754 maxnum operation                             */\r
+/*     COMPMAXMAG -- ditto, comparing absolute values                 */\r
+/*     COMPMIN    -- the 754 minnum operation                         */\r
+/*     COMPMINMAG -- ditto, comparing absolute values                 */\r
+/*     COMTOTAL   -- returns the signum (as a number) giving the      */\r
+/*                   result of a comparison using 754 total ordering  */\r
+/*                                                                    */\r
+/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */\r
+/*   lhs is A                                                         */\r
+/*   rhs is B                                                         */\r
+/*   set is the context                                               */\r
+/*   op  is the operation flag                                        */\r
+/*   status is the usual accumulator                                  */\r
+/*                                                                    */\r
+/* C must have space for one digit for COMPARE or set->digits for     */\r
+/* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */\r
+/* ------------------------------------------------------------------ */\r
+/* The emphasis here is on speed for common cases, and avoiding       */\r
+/* coefficient comparison if possible.                                */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decCompareOp(decNumber *res, const decNumber *lhs,\r
+                         const decNumber *rhs, decContext *set,\r
+                         Flag op, uInt *status) {\r
+  #if DECSUBSET\r
+  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated\r
+  decNumber *allocrhs=NULL;        // .., rhs\r
+  #endif\r
+  Int   result=0;                  // default result value\r
+  uByte merged;                    // work\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(res, lhs, rhs, set)) return res;\r
+  #endif\r
+\r
+  do {                             // protect allocated storage\r
+    #if DECSUBSET\r
+    if (!set->extended) {\r
+      // reduce operands and set lostDigits status, as needed\r
+      if (lhs->digits>set->digits) {\r
+        alloclhs=decRoundOperand(lhs, set, status);\r
+        if (alloclhs==NULL) {result=BADINT; break;}\r
+        lhs=alloclhs;\r
+        }\r
+      if (rhs->digits>set->digits) {\r
+        allocrhs=decRoundOperand(rhs, set, status);\r
+        if (allocrhs==NULL) {result=BADINT; break;}\r
+        rhs=allocrhs;\r
+        }\r
+      }\r
+    #endif\r
+    // [following code does not require input rounding]\r
+\r
+    // If total ordering then handle differing signs 'up front'\r
+    if (op==COMPTOTAL) {                // total ordering\r
+      if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {\r
+        result=-1;\r
+        break;\r
+        }\r
+      if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {\r
+        result=+1;\r
+        break;\r
+        }\r
+      }\r
+\r
+    // handle NaNs specially; let infinities drop through\r
+    // This assumes sNaN (even just one) leads to NaN.\r
+    merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);\r
+    if (merged) {                       // a NaN bit set\r
+      if (op==COMPARE);                 // result will be NaN\r
+       else if (op==COMPSIG)            // treat qNaN as sNaN\r
+        *status|=DEC_Invalid_operation | DEC_sNaN;\r
+       else if (op==COMPTOTAL) {        // total ordering, always finite\r
+        // signs are known to be the same; compute the ordering here\r
+        // as if the signs are both positive, then invert for negatives\r
+        if (!decNumberIsNaN(lhs)) result=-1;\r
+         else if (!decNumberIsNaN(rhs)) result=+1;\r
+         // here if both NaNs\r
+         else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;\r
+         else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;\r
+         else { // both NaN or both sNaN\r
+          // now it just depends on the payload\r
+          result=decUnitCompare(lhs->lsu, D2U(lhs->digits),\r
+                                rhs->lsu, D2U(rhs->digits), 0);\r
+          // [Error not possible, as these are 'aligned']\r
+          } // both same NaNs\r
+        if (decNumberIsNegative(lhs)) result=-result;\r
+        break;\r
+        } // total order\r
+\r
+       else if (merged & DECSNAN);           // sNaN -> qNaN\r
+       else { // here if MIN or MAX and one or two quiet NaNs\r
+        // min or max -- 754 rules ignore single NaN\r
+        if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {\r
+          // just one NaN; force choice to be the non-NaN operand\r
+          op=COMPMAX;\r
+          if (lhs->bits & DECNAN) result=-1; // pick rhs\r
+                             else result=+1; // pick lhs\r
+          break;\r
+          }\r
+        } // max or min\r
+      op=COMPNAN;                            // use special path\r
+      decNaNs(res, lhs, rhs, set, status);   // propagate NaN\r
+      break;\r
+      }\r
+    // have numbers\r
+    if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);\r
+     else result=decCompare(lhs, rhs, 0);    // sign matters\r
+    } while(0);                              // end protected\r
+\r
+  if (result==BADINT) *status|=DEC_Insufficient_storage; // rare\r
+   else {\r
+    if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { // returning signum\r
+      if (op==COMPTOTAL && result==0) {\r
+        // operands are numerically equal or same NaN (and same sign,\r
+        // tested first); if identical, leave result 0\r
+        if (lhs->exponent!=rhs->exponent) {\r
+          if (lhs->exponent<rhs->exponent) result=-1;\r
+           else result=+1;\r
+          if (decNumberIsNegative(lhs)) result=-result;\r
+          } // lexp!=rexp\r
+        } // total-order by exponent\r
+      decNumberZero(res);               // [always a valid result]\r
+      if (result!=0) {                  // must be -1 or +1\r
+        *res->lsu=1;\r
+        if (result<0) res->bits=DECNEG;\r
+        }\r
+      }\r
+     else if (op==COMPNAN);             // special, drop through\r
+     else {                             // MAX or MIN, non-NaN result\r
+      Int residue=0;                    // rounding accumulator\r
+      // choose the operand for the result\r
+      const decNumber *choice;\r
+      if (result==0) { // operands are numerically equal\r
+        // choose according to sign then exponent (see 754)\r
+        uByte slhs=(lhs->bits & DECNEG);\r
+        uByte srhs=(rhs->bits & DECNEG);\r
+        #if DECSUBSET\r
+        if (!set->extended) {           // subset: force left-hand\r
+          op=COMPMAX;\r
+          result=+1;\r
+          }\r
+        else\r
+        #endif\r
+        if (slhs!=srhs) {          // signs differ\r
+          if (slhs) result=-1;     // rhs is max\r
+               else result=+1;     // lhs is max\r
+          }\r
+         else if (slhs && srhs) {  // both negative\r
+          if (lhs->exponent<rhs->exponent) result=+1;\r
+                                      else result=-1;\r
+          // [if equal, use lhs, technically identical]\r
+          }\r
+         else {                    // both positive\r
+          if (lhs->exponent>rhs->exponent) result=+1;\r
+                                      else result=-1;\r
+          // [ditto]\r
+          }\r
+        } // numerically equal\r
+      // here result will be non-0; reverse if looking for MIN\r
+      if (op==COMPMIN || op==COMPMINMAG) result=-result;\r
+      choice=(result>0 ? lhs : rhs);    // choose\r
+      // copy chosen to result, rounding if need be\r
+      decCopyFit(res, choice, set, &residue, status);\r
+      decFinish(res, set, &residue, status);\r
+      }\r
+    }\r
+  #if DECSUBSET\r
+  if (allocrhs!=NULL) free(allocrhs);   // free any storage used\r
+  if (alloclhs!=NULL) free(alloclhs);   // ..\r
+  #endif\r
+  return res;\r
+  } // decCompareOp\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decCompare -- compare two decNumbers by numerical value            */\r
+/*                                                                    */\r
+/*  This routine compares A ? B without altering them.                */\r
+/*                                                                    */\r
+/*  Arg1 is A, a decNumber which is not a NaN                         */\r
+/*  Arg2 is B, a decNumber which is not a NaN                         */\r
+/*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */\r
+/*                                                                    */\r
+/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */\r
+/*  (the only possible failure is an allocation error)                */\r
+/* ------------------------------------------------------------------ */\r
+static Int decCompare(const decNumber *lhs, const decNumber *rhs,\r
+                      Flag abs) {\r
+  Int   result;                    // result value\r
+  Int   sigr;                      // rhs signum\r
+  Int   compare;                   // work\r
+\r
+  result=1;                                  // assume signum(lhs)\r
+  if (ISZERO(lhs)) result=0;\r
+  if (abs) {\r
+    if (ISZERO(rhs)) return result;          // LHS wins or both 0\r
+    // RHS is non-zero\r
+    if (result==0) return -1;                // LHS is 0; RHS wins\r
+    // [here, both non-zero, result=1]\r
+    }\r
+   else {                                    // signs matter\r
+    if (result && decNumberIsNegative(lhs)) result=-1;\r
+    sigr=1;                                  // compute signum(rhs)\r
+    if (ISZERO(rhs)) sigr=0;\r
+     else if (decNumberIsNegative(rhs)) sigr=-1;\r
+    if (result > sigr) return +1;            // L > R, return 1\r
+    if (result < sigr) return -1;            // L < R, return -1\r
+    if (result==0) return 0;                   // both 0\r
+    }\r
+\r
+  // signums are the same; both are non-zero\r
+  if ((lhs->bits | rhs->bits) & DECINF) {    // one or more infinities\r
+    if (decNumberIsInfinite(rhs)) {\r
+      if (decNumberIsInfinite(lhs)) result=0;// both infinite\r
+       else result=-result;                  // only rhs infinite\r
+      }\r
+    return result;\r
+    }\r
+  // must compare the coefficients, allowing for exponents\r
+  if (lhs->exponent>rhs->exponent) {         // LHS exponent larger\r
+    // swap sides, and sign\r
+    const decNumber *temp=lhs;\r
+    lhs=rhs;\r
+    rhs=temp;\r
+    result=-result;\r
+    }\r
+  compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),\r
+                         rhs->lsu, D2U(rhs->digits),\r
+                         rhs->exponent-lhs->exponent);\r
+  if (compare!=BADINT) compare*=result;      // comparison succeeded\r
+  return compare;\r
+  } // decCompare\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decUnitCompare -- compare two >=0 integers in Unit arrays          */\r
+/*                                                                    */\r
+/*  This routine compares A ? B*10**E where A and B are unit arrays   */\r
+/*  A is a plain integer                                              */\r
+/*  B has an exponent of E (which must be non-negative)               */\r
+/*                                                                    */\r
+/*  Arg1 is A first Unit (lsu)                                        */\r
+/*  Arg2 is A length in Units                                         */\r
+/*  Arg3 is B first Unit (lsu)                                        */\r
+/*  Arg4 is B length in Units                                         */\r
+/*  Arg5 is E (0 if the units are aligned)                            */\r
+/*                                                                    */\r
+/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */\r
+/*  (the only possible failure is an allocation error, which can      */\r
+/*  only occur if E!=0)                                               */\r
+/* ------------------------------------------------------------------ */\r
+static Int decUnitCompare(const Unit *a, Int alength,\r
+                          const Unit *b, Int blength, Int exp) {\r
+  Unit  *acc;                      // accumulator for result\r
+  Unit  accbuff[SD2U(DECBUFFER*2+1)]; // local buffer\r
+  Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated\r
+  Int   accunits, need;            // units in use or needed for acc\r
+  const Unit *l, *r, *u;           // work\r
+  Int   expunits, exprem, result;  // ..\r
+\r
+  if (exp==0) {                    // aligned; fastpath\r
+    if (alength>blength) return 1;\r
+    if (alength<blength) return -1;\r
+    // same number of units in both -- need unit-by-unit compare\r
+    l=a+alength-1;\r
+    r=b+alength-1;\r
+    for (;l>=a; l--, r--) {\r
+      if (*l>*r) return 1;\r
+      if (*l<*r) return -1;\r
+      }\r
+    return 0;                      // all units match\r
+    } // aligned\r
+\r
+  // Unaligned.  If one is >1 unit longer than the other, padded\r
+  // approximately, then can return easily\r
+  if (alength>blength+(Int)D2U(exp)) return 1;\r
+  if (alength+1<blength+(Int)D2U(exp)) return -1;\r
+\r
+  // Need to do a real subtract.  For this, a result buffer is needed\r
+  // even though only the sign is of interest.  Its length needs\r
+  // to be the larger of alength and padded blength, +2\r
+  need=blength+D2U(exp);                // maximum real length of B\r
+  if (need<alength) need=alength;\r
+  need+=2;\r
+  acc=accbuff;                          // assume use local buffer\r
+  if (need*sizeof(Unit)>sizeof(accbuff)) {\r
+    allocacc=(Unit *)malloc(need*sizeof(Unit));\r
+    if (allocacc==NULL) return BADINT;  // hopeless -- abandon\r
+    acc=allocacc;\r
+    }\r
+  // Calculate units and remainder from exponent.\r
+  expunits=exp/DECDPUN;\r
+  exprem=exp%DECDPUN;\r
+  // subtract [A+B*(-m)]\r
+  accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,\r
+                         -(Int)powers[exprem]);\r
+  // [UnitAddSub result may have leading zeros, even on zero]\r
+  if (accunits<0) result=-1;            // negative result\r
+   else {                               // non-negative result\r
+    // check units of the result before freeing any storage\r
+    for (u=acc; u<acc+accunits-1 && *u==0;) u++;\r
+    result=(*u==0 ? 0 : +1);\r
+    }\r
+  // clean up and return the result\r
+  if (allocacc!=NULL) free(allocacc);   // drop any storage used\r
+  return result;\r
+  } // decUnitCompare\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */\r
+/*                                                                    */\r
+/*  This routine performs the calculation:                            */\r
+/*                                                                    */\r
+/*  C=A+(B*M)                                                         */\r
+/*                                                                    */\r
+/*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */\r
+/*                                                                    */\r
+/*  A may be shorter or longer than B.                                */\r
+/*                                                                    */\r
+/*  Leading zeros are not removed after a calculation.  The result is */\r
+/*  either the same length as the longer of A and B (adding any       */\r
+/*  shift), or one Unit longer than that (if a Unit carry occurred).  */\r
+/*                                                                    */\r
+/*  A and B content are not altered unless C is also A or B.          */\r
+/*  C may be the same array as A or B, but only if no zero padding is */\r
+/*  requested (that is, C may be B only if bshift==0).                */\r
+/*  C is filled from the lsu; only those units necessary to complete  */\r
+/*  the calculation are referenced.                                   */\r
+/*                                                                    */\r
+/*  Arg1 is A first Unit (lsu)                                        */\r
+/*  Arg2 is A length in Units                                         */\r
+/*  Arg3 is B first Unit (lsu)                                        */\r
+/*  Arg4 is B length in Units                                         */\r
+/*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */\r
+/*  Arg6 is C first Unit (lsu)                                        */\r
+/*  Arg7 is M, the multiplier                                         */\r
+/*                                                                    */\r
+/*  returns the count of Units written to C, which will be non-zero   */\r
+/*  and negated if the result is negative.  That is, the sign of the  */\r
+/*  returned Int is the sign of the result (positive for zero) and    */\r
+/*  the absolute value of the Int is the count of Units.              */\r
+/*                                                                    */\r
+/*  It is the caller's responsibility to make sure that C size is     */\r
+/*  safe, allowing space if necessary for a one-Unit carry.           */\r
+/*                                                                    */\r
+/*  This routine is severely performance-critical; *any* change here  */\r
+/*  must be measured (timed) to assure no performance degradation.    */\r
+/*  In particular, trickery here tends to be counter-productive, as   */\r
+/*  increased complexity of code hurts register optimizations on      */\r
+/*  register-poor architectures.  Avoiding divisions is nearly        */\r
+/*  always a Good Idea, however.                                      */\r
+/*                                                                    */\r
+/* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */\r
+/* (IBM Warwick, UK) for some of the ideas used in this routine.      */\r
+/* ------------------------------------------------------------------ */\r
+static Int decUnitAddSub(const Unit *a, Int alength,\r
+                         const Unit *b, Int blength, Int bshift,\r
+                         Unit *c, Int m) {\r
+  const Unit *alsu=a;              // A lsu [need to remember it]\r
+  Unit *clsu=c;                    // C ditto\r
+  Unit *minC;                      // low water mark for C\r
+  Unit *maxC;                      // high water mark for C\r
+  eInt carry=0;                    // carry integer (could be Long)\r
+  Int  add;                        // work\r
+  #if DECDPUN<=4                   // myriadal, millenary, etc.\r
+  Int  est;                        // estimated quotient\r
+  #endif\r
+\r
+  #if DECTRACE\r
+  if (alength<1 || blength<1)\r
+    printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);\r
+  #endif\r
+\r
+  maxC=c+alength;                  // A is usually the longer\r
+  minC=c+blength;                  // .. and B the shorter\r
+  if (bshift!=0) {                 // B is shifted; low As copy across\r
+    minC+=bshift;\r
+    // if in place [common], skip copy unless there's a gap [rare]\r
+    if (a==c && bshift<=alength) {\r
+      c+=bshift;\r
+      a+=bshift;\r
+      }\r
+     else for (; c<clsu+bshift; a++, c++) {  // copy needed\r
+      if (a<alsu+alength) *c=*a;\r
+       else *c=0;\r
+      }\r
+    }\r
+  if (minC>maxC) { // swap\r
+    Unit *hold=minC;\r
+    minC=maxC;\r
+    maxC=hold;\r
+    }\r
+\r
+  // For speed, do the addition as two loops; the first where both A\r
+  // and B contribute, and the second (if necessary) where only one or\r
+  // other of the numbers contribute.\r
+  // Carry handling is the same (i.e., duplicated) in each case.\r
+  for (; c<minC; c++) {\r
+    carry+=*a;\r
+    a++;\r
+    carry+=((eInt)*b)*m;                // [special-casing m=1/-1\r
+    b++;                                // here is not a win]\r
+    // here carry is new Unit of digits; it could be +ve or -ve\r
+    if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX\r
+      *c=(Unit)carry;\r
+      carry=0;\r
+      continue;\r
+      }\r
+    #if DECDPUN==4                           // use divide-by-multiply\r
+      if (carry>=0) {\r
+        est=(((ueInt)carry>>11)*53687)>>18;\r
+        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder\r
+        carry=est;                           // likely quotient [89%]\r
+        if (*c<DECDPUNMAX+1) continue;       // estimate was correct\r
+        carry++;\r
+        *c-=DECDPUNMAX+1;\r
+        continue;\r
+        }\r
+      // negative case\r
+      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive\r
+      est=(((ueInt)carry>>11)*53687)>>18;\r
+      *c=(Unit)(carry-est*(DECDPUNMAX+1));\r
+      carry=est-(DECDPUNMAX+1);              // correctly negative\r
+      if (*c<DECDPUNMAX+1) continue;         // was OK\r
+      carry++;\r
+      *c-=DECDPUNMAX+1;\r
+    #elif DECDPUN==3\r
+      if (carry>=0) {\r
+        est=(((ueInt)carry>>3)*16777)>>21;\r
+        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder\r
+        carry=est;                           // likely quotient [99%]\r
+        if (*c<DECDPUNMAX+1) continue;       // estimate was correct\r
+        carry++;\r
+        *c-=DECDPUNMAX+1;\r
+        continue;\r
+        }\r
+      // negative case\r
+      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive\r
+      est=(((ueInt)carry>>3)*16777)>>21;\r
+      *c=(Unit)(carry-est*(DECDPUNMAX+1));\r
+      carry=est-(DECDPUNMAX+1);              // correctly negative\r
+      if (*c<DECDPUNMAX+1) continue;         // was OK\r
+      carry++;\r
+      *c-=DECDPUNMAX+1;\r
+    #elif DECDPUN<=2\r
+      // Can use QUOT10 as carry <= 4 digits\r
+      if (carry>=0) {\r
+        est=QUOT10(carry, DECDPUN);\r
+        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder\r
+        carry=est;                           // quotient\r
+        continue;\r
+        }\r
+      // negative case\r
+      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive\r
+      est=QUOT10(carry, DECDPUN);\r
+      *c=(Unit)(carry-est*(DECDPUNMAX+1));\r
+      carry=est-(DECDPUNMAX+1);              // correctly negative\r
+    #else\r
+      // remainder operator is undefined if negative, so must test\r
+      if ((ueInt)carry<(DECDPUNMAX+1)*2) {   // fastpath carry +1\r
+        *c=(Unit)(carry-(DECDPUNMAX+1));     // [helps additions]\r
+        carry=1;\r
+        continue;\r
+        }\r
+      if (carry>=0) {\r
+        *c=(Unit)(carry%(DECDPUNMAX+1));\r
+        carry=carry/(DECDPUNMAX+1);\r
+        continue;\r
+        }\r
+      // negative case\r
+      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive\r
+      *c=(Unit)(carry%(DECDPUNMAX+1));\r
+      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);\r
+    #endif\r
+    } // c\r
+\r
+  // now may have one or other to complete\r
+  // [pretest to avoid loop setup/shutdown]\r
+  if (c<maxC) for (; c<maxC; c++) {\r
+    if (a<alsu+alength) {               // still in A\r
+      carry+=*a;\r
+      a++;\r
+      }\r
+     else {                             // inside B\r
+      carry+=((eInt)*b)*m;\r
+      b++;\r
+      }\r
+    // here carry is new Unit of digits; it could be +ve or -ve and\r
+    // magnitude up to DECDPUNMAX squared\r
+    if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX\r
+      *c=(Unit)carry;\r
+      carry=0;\r
+      continue;\r
+      }\r
+    // result for this unit is negative or >DECDPUNMAX\r
+    #if DECDPUN==4                           // use divide-by-multiply\r
+      if (carry>=0) {\r
+        est=(((ueInt)carry>>11)*53687)>>18;\r
+        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder\r
+        carry=est;                           // likely quotient [79.7%]\r
+        if (*c<DECDPUNMAX+1) continue;       // estimate was correct\r
+        carry++;\r
+        *c-=DECDPUNMAX+1;\r
+        continue;\r
+        }\r
+      // negative case\r
+      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive\r
+      est=(((ueInt)carry>>11)*53687)>>18;\r
+      *c=(Unit)(carry-est*(DECDPUNMAX+1));\r
+      carry=est-(DECDPUNMAX+1);              // correctly negative\r
+      if (*c<DECDPUNMAX+1) continue;         // was OK\r
+      carry++;\r
+      *c-=DECDPUNMAX+1;\r
+    #elif DECDPUN==3\r
+      if (carry>=0) {\r
+        est=(((ueInt)carry>>3)*16777)>>21;\r
+        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder\r
+        carry=est;                           // likely quotient [99%]\r
+        if (*c<DECDPUNMAX+1) continue;       // estimate was correct\r
+        carry++;\r
+        *c-=DECDPUNMAX+1;\r
+        continue;\r
+        }\r
+      // negative case\r
+      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive\r
+      est=(((ueInt)carry>>3)*16777)>>21;\r
+      *c=(Unit)(carry-est*(DECDPUNMAX+1));\r
+      carry=est-(DECDPUNMAX+1);              // correctly negative\r
+      if (*c<DECDPUNMAX+1) continue;         // was OK\r
+      carry++;\r
+      *c-=DECDPUNMAX+1;\r
+    #elif DECDPUN<=2\r
+      if (carry>=0) {\r
+        est=QUOT10(carry, DECDPUN);\r
+        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder\r
+        carry=est;                           // quotient\r
+        continue;\r
+        }\r
+      // negative case\r
+      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive\r
+      est=QUOT10(carry, DECDPUN);\r
+      *c=(Unit)(carry-est*(DECDPUNMAX+1));\r
+      carry=est-(DECDPUNMAX+1);              // correctly negative\r
+    #else\r
+      if ((ueInt)carry<(DECDPUNMAX+1)*2){    // fastpath carry 1\r
+        *c=(Unit)(carry-(DECDPUNMAX+1));\r
+        carry=1;\r
+        continue;\r
+        }\r
+      // remainder operator is undefined if negative, so must test\r
+      if (carry>=0) {\r
+        *c=(Unit)(carry%(DECDPUNMAX+1));\r
+        carry=carry/(DECDPUNMAX+1);\r
+        continue;\r
+        }\r
+      // negative case\r
+      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive\r
+      *c=(Unit)(carry%(DECDPUNMAX+1));\r
+      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);\r
+    #endif\r
+    } // c\r
+\r
+  // OK, all A and B processed; might still have carry or borrow\r
+  // return number of Units in the result, negated if a borrow\r
+  if (carry==0) return c-clsu;     // no carry, so no more to do\r
+  if (carry>0) {                   // positive carry\r
+    *c=(Unit)carry;                // place as new unit\r
+    c++;                           // ..\r
+    return c-clsu;\r
+    }\r
+  // -ve carry: it's a borrow; complement needed\r
+  add=1;                           // temporary carry...\r
+  for (c=clsu; c<maxC; c++) {\r
+    add=DECDPUNMAX+add-*c;\r
+    if (add<=DECDPUNMAX) {\r
+      *c=(Unit)add;\r
+      add=0;\r
+      }\r
+     else {\r
+      *c=0;\r
+      add=1;\r
+      }\r
+    }\r
+  // add an extra unit iff it would be non-zero\r
+  #if DECTRACE\r
+    printf("UAS borrow: add %ld, carry %ld\n", add, carry);\r
+  #endif\r
+  if ((add-carry-1)!=0) {\r
+    *c=(Unit)(add-carry-1);\r
+    c++;                      // interesting, include it\r
+    }\r
+  return clsu-c;              // -ve result indicates borrowed\r
+  } // decUnitAddSub\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decTrim -- trim trailing zeros or normalize                        */\r
+/*                                                                    */\r
+/*   dn is the number to trim or normalize                            */\r
+/*   set is the context to use to check for clamp                     */\r
+/*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */\r
+/*   noclamp is 1 to unconditional (unclamped) trim                   */\r
+/*   dropped returns the number of discarded trailing zeros           */\r
+/*   returns dn                                                       */\r
+/*                                                                    */\r
+/* If clamp is set in the context then the number of zeros trimmed    */\r
+/* may be limited if the exponent is high.                            */\r
+/* All fields are updated as required.  This is a utility operation,  */\r
+/* so special values are unchanged and no error is possible.          */\r
+/* ------------------------------------------------------------------ */\r
+static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,\r
+                           Flag noclamp, Int *dropped) {\r
+  Int   d, exp;                    // work\r
+  uInt  cut;                       // ..\r
+  Unit  *up;                       // -> current Unit\r
+\r
+  #if DECCHECK\r
+  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;\r
+  #endif\r
+\r
+  *dropped=0;                           // assume no zeros dropped\r
+  if ((dn->bits & DECSPECIAL)           // fast exit if special ..\r
+    || (*dn->lsu & 0x01)) return dn;    // .. or odd\r
+  if (ISZERO(dn)) {                     // .. or 0\r
+    dn->exponent=0;                     // (sign is preserved)\r
+    return dn;\r
+    }\r
+\r
+  // have a finite number which is even\r
+  exp=dn->exponent;\r
+  cut=1;                           // digit (1-DECDPUN) in Unit\r
+  up=dn->lsu;                      // -> current Unit\r
+  for (d=0; d<dn->digits-1; d++) { // [don't strip the final digit]\r
+    // slice by powers\r
+    #if DECDPUN<=4\r
+      uInt quot=QUOT10(*up, cut);\r
+      if ((*up-quot*powers[cut])!=0) break;  // found non-0 digit\r
+    #else\r
+      if (*up%powers[cut]!=0) break;         // found non-0 digit\r
+    #endif\r
+    // have a trailing 0\r
+    if (!all) {                    // trimming\r
+      // [if exp>0 then all trailing 0s are significant for trim]\r
+      if (exp<=0) {                // if digit might be significant\r
+        if (exp==0) break;         // then quit\r
+        exp++;                     // next digit might be significant\r
+        }\r
+      }\r
+    cut++;                         // next power\r
+    if (cut>DECDPUN) {             // need new Unit\r
+      up++;\r
+      cut=1;\r
+      }\r
+    } // d\r
+  if (d==0) return dn;             // none to drop\r
+\r
+  // may need to limit drop if clamping\r
+  if (set->clamp && !noclamp) {\r
+    Int maxd=set->emax-set->digits+1-dn->exponent;\r
+    if (maxd<=0) return dn;        // nothing possible\r
+    if (d>maxd) d=maxd;\r
+    }\r
+\r
+  // effect the drop\r
+  decShiftToLeast(dn->lsu, D2U(dn->digits), d);\r
+  dn->exponent+=d;                 // maintain numerical value\r
+  dn->digits-=d;                   // new length\r
+  *dropped=d;                      // report the count\r
+  return dn;\r
+  } // decTrim\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decReverse -- reverse a Unit array in place                        */\r
+/*                                                                    */\r
+/*   ulo    is the start of the array                                 */\r
+/*   uhi    is the end of the array (highest Unit to include)         */\r
+/*                                                                    */\r
+/* The units ulo through uhi are reversed in place (if the number     */\r
+/* of units is odd, the middle one is untouched).  Note that the      */\r
+/* digit(s) in each unit are unaffected.                              */\r
+/* ------------------------------------------------------------------ */\r
+static void decReverse(Unit *ulo, Unit *uhi) {\r
+  Unit temp;\r
+  for (; ulo<uhi; ulo++, uhi--) {\r
+    temp=*ulo;\r
+    *ulo=*uhi;\r
+    *uhi=temp;\r
+    }\r
+  return;\r
+  } // decReverse\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decShiftToMost -- shift digits in array towards most significant   */\r
+/*                                                                    */\r
+/*   uar    is the array                                              */\r
+/*   digits is the count of digits in use in the array                */\r
+/*   shift  is the number of zeros to pad with (least significant);   */\r
+/*     it must be zero or positive                                    */\r
+/*                                                                    */\r
+/*   returns the new length of the integer in the array, in digits    */\r
+/*                                                                    */\r
+/* No overflow is permitted (that is, the uar array must be known to  */\r
+/* be large enough to hold the result, after shifting).               */\r
+/* ------------------------------------------------------------------ */\r
+static Int decShiftToMost(Unit *uar, Int digits, Int shift) {\r
+  Unit  *target, *source, *first;  // work\r
+  Int   cut;                       // odd 0's to add\r
+  uInt  next;                      // work\r
+\r
+  if (shift==0) return digits;     // [fastpath] nothing to do\r
+  if ((digits+shift)<=DECDPUN) {   // [fastpath] single-unit case\r
+    *uar=(Unit)(*uar*powers[shift]);\r
+    return digits+shift;\r
+    }\r
+\r
+  next=0;                          // all paths\r
+  source=uar+D2U(digits)-1;        // where msu comes from\r
+  target=source+D2U(shift);        // where upper part of first cut goes\r
+  cut=DECDPUN-MSUDIGITS(shift);    // where to slice\r
+  if (cut==0) {                    // unit-boundary case\r
+    for (; source>=uar; source--, target--) *target=*source;\r
+    }\r
+   else {\r
+    first=uar+D2U(digits+shift)-1; // where msu of source will end up\r
+    for (; source>=uar; source--, target--) {\r
+      // split the source Unit and accumulate remainder for next\r
+      #if DECDPUN<=4\r
+        uInt quot=QUOT10(*source, cut);\r
+        uInt rem=*source-quot*powers[cut];\r
+        next+=quot;\r
+      #else\r
+        uInt rem=*source%powers[cut];\r
+        next+=*source/powers[cut];\r
+      #endif\r
+      if (target<=first) *target=(Unit)next;   // write to target iff valid\r
+      next=rem*powers[DECDPUN-cut];            // save remainder for next Unit\r
+      }\r
+    } // shift-move\r
+\r
+  // propagate any partial unit to one below and clear the rest\r
+  for (; target>=uar; target--) {\r
+    *target=(Unit)next;\r
+    next=0;\r
+    }\r
+  return digits+shift;\r
+  } // decShiftToMost\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decShiftToLeast -- shift digits in array towards least significant */\r
+/*                                                                    */\r
+/*   uar   is the array                                               */\r
+/*   units is length of the array, in units                           */\r
+/*   shift is the number of digits to remove from the lsu end; it     */\r
+/*     must be zero or positive and <= than units*DECDPUN.            */\r
+/*                                                                    */\r
+/*   returns the new length of the integer in the array, in units     */\r
+/*                                                                    */\r
+/* Removed digits are discarded (lost).  Units not required to hold   */\r
+/* the final result are unchanged.                                    */\r
+/* ------------------------------------------------------------------ */\r
+static Int decShiftToLeast(Unit *uar, Int units, Int shift) {\r
+  Unit  *target, *up;              // work\r
+  Int   cut, count;                // work\r
+  Int   quot, rem;                 // for division\r
+\r
+  if (shift==0) return units;      // [fastpath] nothing to do\r
+  if (shift==units*DECDPUN) {      // [fastpath] little to do\r
+    *uar=0;                        // all digits cleared gives zero\r
+    return 1;                      // leaves just the one\r
+    }\r
+\r
+  target=uar;                      // both paths\r
+  cut=MSUDIGITS(shift);\r
+  if (cut==DECDPUN) {              // unit-boundary case; easy\r
+    up=uar+D2U(shift);\r
+    for (; up<uar+units; target++, up++) *target=*up;\r
+    return target-uar;\r
+    }\r
+\r
+  // messier\r
+  up=uar+D2U(shift-cut);           // source; correct to whole Units\r
+  count=units*DECDPUN-shift;       // the maximum new length\r
+  #if DECDPUN<=4\r
+    quot=QUOT10(*up, cut);\r
+  #else\r
+    quot=*up/powers[cut];\r
+  #endif\r
+  for (; ; target++) {\r
+    *target=(Unit)quot;\r
+    count-=(DECDPUN-cut);\r
+    if (count<=0) break;\r
+    up++;\r
+    quot=*up;\r
+    #if DECDPUN<=4\r
+      quot=QUOT10(quot, cut);\r
+      rem=*up-quot*powers[cut];\r
+    #else\r
+      rem=quot%powers[cut];\r
+      quot=quot/powers[cut];\r
+    #endif\r
+    *target=(Unit)(*target+rem*powers[DECDPUN-cut]);\r
+    count-=cut;\r
+    if (count<=0) break;\r
+    }\r
+  return target-uar+1;\r
+  } // decShiftToLeast\r
+\r
+#if DECSUBSET\r
+/* ------------------------------------------------------------------ */\r
+/* decRoundOperand -- round an operand  [used for subset only]        */\r
+/*                                                                    */\r
+/*   dn is the number to round (dn->digits is > set->digits)          */\r
+/*   set is the relevant context                                      */\r
+/*   status is the status accumulator                                 */\r
+/*                                                                    */\r
+/*   returns an allocated decNumber with the rounded result.          */\r
+/*                                                                    */\r
+/* lostDigits and other status may be set by this.                    */\r
+/*                                                                    */\r
+/* Since the input is an operand, it must not be modified.            */\r
+/* Instead, return an allocated decNumber, rounded as required.       */\r
+/* It is the caller's responsibility to free the allocated storage.   */\r
+/*                                                                    */\r
+/* If no storage is available then the result cannot be used, so NULL */\r
+/* is returned.                                                       */\r
+/* ------------------------------------------------------------------ */\r
+static decNumber *decRoundOperand(const decNumber *dn, decContext *set,\r
+                                  uInt *status) {\r
+  decNumber *res;                       // result structure\r
+  uInt newstatus=0;                     // status from round\r
+  Int  residue=0;                       // rounding accumulator\r
+\r
+  // Allocate storage for the returned decNumber, big enough for the\r
+  // length specified by the context\r
+  res=(decNumber *)malloc(sizeof(decNumber)\r
+                          +(D2U(set->digits)-1)*sizeof(Unit));\r
+  if (res==NULL) {\r
+    *status|=DEC_Insufficient_storage;\r
+    return NULL;\r
+    }\r
+  decCopyFit(res, dn, set, &residue, &newstatus);\r
+  decApplyRound(res, set, residue, &newstatus);\r
+\r
+  // If that set Inexact then "lost digits" is raised...\r
+  if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;\r
+  *status|=newstatus;\r
+  return res;\r
+  } // decRoundOperand\r
+#endif\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decCopyFit -- copy a number, truncating the coefficient if needed  */\r
+/*                                                                    */\r
+/*   dest is the target decNumber                                     */\r
+/*   src  is the source decNumber                                     */\r
+/*   set is the context [used for length (digits) and rounding mode]  */\r
+/*   residue is the residue accumulator                               */\r
+/*   status contains the current status to be updated                 */\r
+/*                                                                    */\r
+/* (dest==src is allowed and will be a no-op if fits)                 */\r
+/* All fields are updated as required.                                */\r
+/* ------------------------------------------------------------------ */\r
+static void decCopyFit(decNumber *dest, const decNumber *src,\r
+                       decContext *set, Int *residue, uInt *status) {\r
+  dest->bits=src->bits;\r
+  dest->exponent=src->exponent;\r
+  decSetCoeff(dest, set, src->lsu, src->digits, residue, status);\r
+  } // decCopyFit\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decSetCoeff -- set the coefficient of a number                     */\r
+/*                                                                    */\r
+/*   dn    is the number whose coefficient array is to be set.        */\r
+/*         It must have space for set->digits digits                  */\r
+/*   set   is the context [for size]                                  */\r
+/*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */\r
+/*   len   is digits in the source coefficient [may be dn->digits]    */\r
+/*   residue is the residue accumulator.  This has values as in       */\r
+/*         decApplyRound, and will be unchanged unless the            */\r
+/*         target size is less than len.  In this case, the           */\r
+/*         coefficient is truncated and the residue is updated to     */\r
+/*         reflect the previous residue and the dropped digits.       */\r
+/*   status is the status accumulator, as usual                       */\r
+/*                                                                    */\r
+/* The coefficient may already be in the number, or it can be an      */\r
+/* external intermediate array.  If it is in the number, lsu must ==  */\r
+/* dn->lsu and len must == dn->digits.                                */\r
+/*                                                                    */\r
+/* Note that the coefficient length (len) may be < set->digits, and   */\r
+/* in this case this merely copies the coefficient (or is a no-op     */\r
+/* if dn->lsu==lsu).                                                  */\r
+/*                                                                    */\r
+/* Note also that (only internally, from decQuantizeOp and            */\r
+/* decSetSubnormal) the value of set->digits may be less than one,    */\r
+/* indicating a round to left.  This routine handles that case        */\r
+/* correctly; caller ensures space.                                   */\r
+/*                                                                    */\r
+/* dn->digits, dn->lsu (and as required), and dn->exponent are        */\r
+/* updated as necessary.   dn->bits (sign) is unchanged.              */\r
+/*                                                                    */\r
+/* DEC_Rounded status is set if any digits are discarded.             */\r
+/* DEC_Inexact status is set if any non-zero digits are discarded, or */\r
+/*                       incoming residue was non-0 (implies rounded) */\r
+/* ------------------------------------------------------------------ */\r
+// mapping array: maps 0-9 to canonical residues, so that a residue\r
+// can be adjusted in the range [-1, +1] and achieve correct rounding\r
+//                             0  1  2  3  4  5  6  7  8  9\r
+static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};\r
+static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,\r
+                        Int len, Int *residue, uInt *status) {\r
+  Int   discard;              // number of digits to discard\r
+  uInt  cut;                  // cut point in Unit\r
+  const Unit *up;             // work\r
+  Unit  *target;              // ..\r
+  Int   count;                // ..\r
+  #if DECDPUN<=4\r
+  uInt  temp;                 // ..\r
+  #endif\r
+\r
+  discard=len-set->digits;    // digits to discard\r
+  if (discard<=0) {           // no digits are being discarded\r
+    if (dn->lsu!=lsu) {       // copy needed\r
+      // copy the coefficient array to the result number; no shift needed\r
+      count=len;              // avoids D2U\r
+      up=lsu;\r
+      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)\r
+        *target=*up;\r
+      dn->digits=len;         // set the new length\r
+      }\r
+    // dn->exponent and residue are unchanged, record any inexactitude\r
+    if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);\r
+    return;\r
+    }\r
+\r
+  // some digits must be discarded ...\r
+  dn->exponent+=discard;      // maintain numerical value\r
+  *status|=DEC_Rounded;       // accumulate Rounded status\r
+  if (*residue>1) *residue=1; // previous residue now to right, so reduce\r
+\r
+  if (discard>len) {          // everything, +1, is being discarded\r
+    // guard digit is 0\r
+    // residue is all the number [NB could be all 0s]\r
+    if (*residue<=0) {        // not already positive\r
+      count=len;              // avoids D2U\r
+      for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { // found non-0\r
+        *residue=1;\r
+        break;                // no need to check any others\r
+        }\r
+      }\r
+    if (*residue!=0) *status|=DEC_Inexact; // record inexactitude\r
+    *dn->lsu=0;               // coefficient will now be 0\r
+    dn->digits=1;             // ..\r
+    return;\r
+    } // total discard\r
+\r
+  // partial discard [most common case]\r
+  // here, at least the first (most significant) discarded digit exists\r
+\r
+  // spin up the number, noting residue during the spin, until get to\r
+  // the Unit with the first discarded digit.  When reach it, extract\r
+  // it and remember its position\r
+  count=0;\r
+  for (up=lsu;; up++) {\r
+    count+=DECDPUN;\r
+    if (count>=discard) break; // full ones all checked\r
+    if (*up!=0) *residue=1;\r
+    } // up\r
+\r
+  // here up -> Unit with first discarded digit\r
+  cut=discard-(count-DECDPUN)-1;\r
+  if (cut==DECDPUN-1) {       // unit-boundary case (fast)\r
+    Unit half=(Unit)powers[DECDPUN]>>1;\r
+    // set residue directly\r
+    if (*up>=half) {\r
+      if (*up>half) *residue=7;\r
+      else *residue+=5;       // add sticky bit\r
+      }\r
+     else { // <half\r
+      if (*up!=0) *residue=3; // [else is 0, leave as sticky bit]\r
+      }\r
+    if (set->digits<=0) {     // special for Quantize/Subnormal :-(\r
+      *dn->lsu=0;             // .. result is 0\r
+      dn->digits=1;           // ..\r
+      }\r
+     else {                   // shift to least\r
+      count=set->digits;      // now digits to end up with\r
+      dn->digits=count;       // set the new length\r
+      up++;                   // move to next\r
+      // on unit boundary, so shift-down copy loop is simple\r
+      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)\r
+        *target=*up;\r
+      }\r
+    } // unit-boundary case\r
+\r
+   else { // discard digit is in low digit(s), and not top digit\r
+    uInt  discard1;                // first discarded digit\r
+    uInt  quot, rem;               // for divisions\r
+    if (cut==0) quot=*up;          // is at bottom of unit\r
+     else /* cut>0 */ {            // it's not at bottom of unit\r
+      #if DECDPUN<=4\r
+        quot=QUOT10(*up, cut);\r
+        rem=*up-quot*powers[cut];\r
+      #else\r
+        rem=*up%powers[cut];\r
+        quot=*up/powers[cut];\r
+      #endif\r
+      if (rem!=0) *residue=1;\r
+      }\r
+    // discard digit is now at bottom of quot\r
+    #if DECDPUN<=4\r
+      temp=(quot*6554)>>16;        // fast /10\r
+      // Vowels algorithm here not a win (9 instructions)\r
+      discard1=quot-X10(temp);\r
+      quot=temp;\r
+    #else\r
+      discard1=quot%10;\r
+      quot=quot/10;\r
+    #endif\r
+    // here, discard1 is the guard digit, and residue is everything\r
+    // else [use mapping array to accumulate residue safely]\r
+    *residue+=resmap[discard1];\r
+    cut++;                         // update cut\r
+    // here: up -> Unit of the array with bottom digit\r
+    //       cut is the division point for each Unit\r
+    //       quot holds the uncut high-order digits for the current unit\r
+    if (set->digits<=0) {          // special for Quantize/Subnormal :-(\r
+      *dn->lsu=0;                  // .. result is 0\r
+      dn->digits=1;                // ..\r
+      }\r
+     else {                        // shift to least needed\r
+      count=set->digits;           // now digits to end up with\r
+      dn->digits=count;            // set the new length\r
+      // shift-copy the coefficient array to the result number\r
+      for (target=dn->lsu; ; target++) {\r
+        *target=(Unit)quot;\r
+        count-=(DECDPUN-cut);\r
+        if (count<=0) break;\r
+        up++;\r
+        quot=*up;\r
+        #if DECDPUN<=4\r
+          quot=QUOT10(quot, cut);\r
+          rem=*up-quot*powers[cut];\r
+        #else\r
+          rem=quot%powers[cut];\r
+          quot=quot/powers[cut];\r
+        #endif\r
+        *target=(Unit)(*target+rem*powers[DECDPUN-cut]);\r
+        count-=cut;\r
+        if (count<=0) break;\r
+        } // shift-copy loop\r
+      } // shift to least\r
+    } // not unit boundary\r
+\r
+  if (*residue!=0) *status|=DEC_Inexact; // record inexactitude\r
+  return;\r
+  } // decSetCoeff\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decApplyRound -- apply pending rounding to a number                */\r
+/*                                                                    */\r
+/*   dn    is the number, with space for set->digits digits           */\r
+/*   set   is the context [for size and rounding mode]                */\r
+/*   residue indicates pending rounding, being any accumulated        */\r
+/*         guard and sticky information.  It may be:                  */\r
+/*         6-9: rounding digit is >5                                  */\r
+/*         5:   rounding digit is exactly half-way                    */\r
+/*         1-4: rounding digit is <5 and >0                           */\r
+/*         0:   the coefficient is exact                              */\r
+/*        -1:   as 1, but the hidden digits are subtractive, that     */\r
+/*              is, of the opposite sign to dn.  In this case the     */\r
+/*              coefficient must be non-0.  This case occurs when     */\r
+/*              subtracting a small number (which can be reduced to   */\r
+/*              a sticky bit); see decAddOp.                          */\r
+/*   status is the status accumulator, as usual                       */\r
+/*                                                                    */\r
+/* This routine applies rounding while keeping the length of the      */\r
+/* coefficient constant.  The exponent and status are unchanged       */\r
+/* except if:                                                         */\r
+/*                                                                    */\r
+/*   -- the coefficient was increased and is all nines (in which      */\r
+/*      case Overflow could occur, and is handled directly here so    */\r
+/*      the caller does not need to re-test for overflow)             */\r
+/*                                                                    */\r
+/*   -- the coefficient was decreased and becomes all nines (in which */\r
+/*      case Underflow could occur, and is also handled directly).    */\r
+/*                                                                    */\r
+/* All fields in dn are updated as required.                          */\r
+/*                                                                    */\r
+/* ------------------------------------------------------------------ */\r
+static void decApplyRound(decNumber *dn, decContext *set, Int residue,\r
+                          uInt *status) {\r
+  Int  bump;                  // 1 if coefficient needs to be incremented\r
+                              // -1 if coefficient needs to be decremented\r
+\r
+  if (residue==0) return;     // nothing to apply\r
+\r
+  bump=0;                     // assume a smooth ride\r
+\r
+  // now decide whether, and how, to round, depending on mode\r
+  switch (set->round) {\r
+    case DEC_ROUND_05UP: {    // round zero or five up (for reround)\r
+      // This is the same as DEC_ROUND_DOWN unless there is a\r
+      // positive residue and the lsd of dn is 0 or 5, in which case\r
+      // it is bumped; when residue is <0, the number is therefore\r
+      // bumped down unless the final digit was 1 or 6 (in which\r
+      // case it is bumped down and then up -- a no-op)\r
+      Int lsd5=*dn->lsu%5;     // get lsd and quintate\r
+      if (residue<0 && lsd5!=1) bump=-1;\r
+       else if (residue>0 && lsd5==0) bump=1;\r
+      // [bump==1 could be applied directly; use common path for clarity]\r
+      break;} // r-05\r
+\r
+    case DEC_ROUND_DOWN: {\r
+      // no change, except if negative residue\r
+      if (residue<0) bump=-1;\r
+      break;} // r-d\r
+\r
+    case DEC_ROUND_HALF_DOWN: {\r
+      if (residue>5) bump=1;\r
+      break;} // r-h-d\r
+\r
+    case DEC_ROUND_HALF_EVEN: {\r
+      if (residue>5) bump=1;            // >0.5 goes up\r
+       else if (residue==5) {           // exactly 0.5000...\r
+        // 0.5 goes up iff [new] lsd is odd\r
+        if (*dn->lsu & 0x01) bump=1;\r
+        }\r
+      break;} // r-h-e\r
+\r
+    case DEC_ROUND_HALF_UP: {\r
+      if (residue>=5) bump=1;\r
+      break;} // r-h-u\r
+\r
+    case DEC_ROUND_UP: {\r
+      if (residue>0) bump=1;\r
+      break;} // r-u\r
+\r
+    case DEC_ROUND_CEILING: {\r
+      // same as _UP for positive numbers, and as _DOWN for negatives\r
+      // [negative residue cannot occur on 0]\r
+      if (decNumberIsNegative(dn)) {\r
+        if (residue<0) bump=-1;\r
+        }\r
+       else {\r
+        if (residue>0) bump=1;\r
+        }\r
+      break;} // r-c\r
+\r
+    case DEC_ROUND_FLOOR: {\r
+      // same as _UP for negative numbers, and as _DOWN for positive\r
+      // [negative residue cannot occur on 0]\r
+      if (!decNumberIsNegative(dn)) {\r
+        if (residue<0) bump=-1;\r
+        }\r
+       else {\r
+        if (residue>0) bump=1;\r
+        }\r
+      break;} // r-f\r
+\r
+    default: {      // e.g., DEC_ROUND_MAX\r
+      *status|=DEC_Invalid_context;\r
+      #if DECTRACE || (DECCHECK && DECVERB)\r
+      printf("Unknown rounding mode: %d\n", set->round);\r
+      #endif\r
+      break;}\r
+    } // switch\r
+\r
+  // now bump the number, up or down, if need be\r
+  if (bump==0) return;                       // no action required\r
+\r
+  // Simply use decUnitAddSub unless bumping up and the number is\r
+  // all nines.  In this special case set to 100... explicitly\r
+  // and adjust the exponent by one (as otherwise could overflow\r
+  // the array)\r
+  // Similarly handle all-nines result if bumping down.\r
+  if (bump>0) {\r
+    Unit *up;                                // work\r
+    uInt count=dn->digits;                   // digits to be checked\r
+    for (up=dn->lsu; ; up++) {\r
+      if (count<=DECDPUN) {\r
+        // this is the last Unit (the msu)\r
+        if (*up!=powers[count]-1) break;     // not still 9s\r
+        // here if it, too, is all nines\r
+        *up=(Unit)powers[count-1];           // here 999 -> 100 etc.\r
+        for (up=up-1; up>=dn->lsu; up--) *up=0; // others all to 0\r
+        dn->exponent++;                      // and bump exponent\r
+        // [which, very rarely, could cause Overflow...]\r
+        if ((dn->exponent+dn->digits)>set->emax+1) {\r
+          decSetOverflow(dn, set, status);\r
+          }\r
+        return;                              // done\r
+        }\r
+      // a full unit to check, with more to come\r
+      if (*up!=DECDPUNMAX) break;            // not still 9s\r
+      count-=DECDPUN;\r
+      } // up\r
+    } // bump>0\r
+   else {                                    // -1\r
+    // here checking for a pre-bump of 1000... (leading 1, all\r
+    // other digits zero)\r
+    Unit *up, *sup;                          // work\r
+    uInt count=dn->digits;                   // digits to be checked\r
+    for (up=dn->lsu; ; up++) {\r
+      if (count<=DECDPUN) {\r
+        // this is the last Unit (the msu)\r
+        if (*up!=powers[count-1]) break;     // not 100..\r
+        // here if have the 1000... case\r
+        sup=up;                              // save msu pointer\r
+        *up=(Unit)powers[count]-1;           // here 100 in msu -> 999\r
+        // others all to all-nines, too\r
+        for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;\r
+        dn->exponent--;                      // and bump exponent\r
+\r
+        // iff the number was at the subnormal boundary (exponent=etiny)\r
+        // then the exponent is now out of range, so it will in fact get\r
+        // clamped to etiny and the final 9 dropped.\r
+        // printf(">> emin=%d exp=%d sdig=%d\n", set->emin,\r
+        //        dn->exponent, set->digits);\r
+        if (dn->exponent+1==set->emin-set->digits+1) {\r
+          if (count==1 && dn->digits==1) *sup=0;  // here 9 -> 0[.9]\r
+           else {\r
+            *sup=(Unit)powers[count-1]-1;    // here 999.. in msu -> 99..\r
+            dn->digits--;\r
+            }\r
+          dn->exponent++;\r
+          *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;\r
+          }\r
+        return;                              // done\r
+        }\r
+\r
+      // a full unit to check, with more to come\r
+      if (*up!=0) break;                     // not still 0s\r
+      count-=DECDPUN;\r
+      } // up\r
+\r
+    } // bump<0\r
+\r
+  // Actual bump needed.  Do it.\r
+  decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);\r
+  } // decApplyRound\r
+\r
+#if DECSUBSET\r
+/* ------------------------------------------------------------------ */\r
+/* decFinish -- finish processing a number                            */\r
+/*                                                                    */\r
+/*   dn is the number                                                 */\r
+/*   set is the context                                               */\r
+/*   residue is the rounding accumulator (as in decApplyRound)        */\r
+/*   status is the accumulator                                        */\r
+/*                                                                    */\r
+/* This finishes off the current number by:                           */\r
+/*    1. If not extended:                                             */\r
+/*       a. Converting a zero result to clean '0'                     */\r
+/*       b. Reducing positive exponents to 0, if would fit in digits  */\r
+/*    2. Checking for overflow and subnormals (always)                */\r
+/* Note this is just Finalize when no subset arithmetic.              */\r
+/* All fields are updated as required.                                */\r
+/* ------------------------------------------------------------------ */\r
+static void decFinish(decNumber *dn, decContext *set, Int *residue,\r
+                      uInt *status) {\r
+  if (!set->extended) {\r
+    if ISZERO(dn) {                // value is zero\r
+      dn->exponent=0;              // clean exponent ..\r
+      dn->bits=0;                  // .. and sign\r
+      return;                      // no error possible\r
+      }\r
+    if (dn->exponent>=0) {         // non-negative exponent\r
+      // >0; reduce to integer if possible\r
+      if (set->digits >= (dn->exponent+dn->digits)) {\r
+        dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);\r
+        dn->exponent=0;\r
+        }\r
+      }\r
+    } // !extended\r
+\r
+  decFinalize(dn, set, residue, status);\r
+  } // decFinish\r
+#endif\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFinalize -- final check, clamp, and round of a number           */\r
+/*                                                                    */\r
+/*   dn is the number                                                 */\r
+/*   set is the context                                               */\r
+/*   residue is the rounding accumulator (as in decApplyRound)        */\r
+/*   status is the status accumulator                                 */\r
+/*                                                                    */\r
+/* This finishes off the current number by checking for subnormal     */\r
+/* results, applying any pending rounding, checking for overflow,     */\r
+/* and applying any clamping.                                         */\r
+/* Underflow and overflow conditions are raised as appropriate.       */\r
+/* All fields are updated as required.                                */\r
+/* ------------------------------------------------------------------ */\r
+static void decFinalize(decNumber *dn, decContext *set, Int *residue,\r
+                        uInt *status) {\r
+  Int shift;                            // shift needed if clamping\r
+  Int tinyexp=set->emin-dn->digits+1;   // precalculate subnormal boundary\r
+\r
+  // Must be careful, here, when checking the exponent as the\r
+  // adjusted exponent could overflow 31 bits [because it may already\r
+  // be up to twice the expected].\r
+\r
+  // First test for subnormal.  This must be done before any final\r
+  // round as the result could be rounded to Nmin or 0.\r
+  if (dn->exponent<=tinyexp) {          // prefilter\r
+    Int comp;\r
+    decNumber nmin;\r
+    // A very nasty case here is dn == Nmin and residue<0\r
+    if (dn->exponent<tinyexp) {\r
+      // Go handle subnormals; this will apply round if needed.\r
+      decSetSubnormal(dn, set, residue, status);\r
+      return;\r
+      }\r
+    // Equals case: only subnormal if dn=Nmin and negative residue\r
+    decNumberZero(&nmin);\r
+    nmin.lsu[0]=1;\r
+    nmin.exponent=set->emin;\r
+    comp=decCompare(dn, &nmin, 1);                // (signless compare)\r
+    if (comp==BADINT) {                           // oops\r
+      *status|=DEC_Insufficient_storage;          // abandon...\r
+      return;\r
+      }\r
+    if (*residue<0 && comp==0) {                  // neg residue and dn==Nmin\r
+      decApplyRound(dn, set, *residue, status);   // might force down\r
+      decSetSubnormal(dn, set, residue, status);\r
+      return;\r
+      }\r
+    }\r
+\r
+  // now apply any pending round (this could raise overflow).\r
+  if (*residue!=0) decApplyRound(dn, set, *residue, status);\r
+\r
+  // Check for overflow [redundant in the 'rare' case] or clamp\r
+  if (dn->exponent<=set->emax-set->digits+1) return;   // neither needed\r
+\r
+\r
+  // here when might have an overflow or clamp to do\r
+  if (dn->exponent>set->emax-dn->digits+1) {           // too big\r
+    decSetOverflow(dn, set, status);\r
+    return;\r
+    }\r
+  // here when the result is normal but in clamp range\r
+  if (!set->clamp) return;\r
+\r
+  // here when need to apply the IEEE exponent clamp (fold-down)\r
+  shift=dn->exponent-(set->emax-set->digits+1);\r
+\r
+  // shift coefficient (if non-zero)\r
+  if (!ISZERO(dn)) {\r
+    dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);\r
+    }\r
+  dn->exponent-=shift;   // adjust the exponent to match\r
+  *status|=DEC_Clamped;  // and record the dirty deed\r
+  return;\r
+  } // decFinalize\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decSetOverflow -- set number to proper overflow value              */\r
+/*                                                                    */\r
+/*   dn is the number (used for sign [only] and result)               */\r
+/*   set is the context [used for the rounding mode, etc.]            */\r
+/*   status contains the current status to be updated                 */\r
+/*                                                                    */\r
+/* This sets the sign of a number and sets its value to either        */\r
+/* Infinity or the maximum finite value, depending on the sign of     */\r
+/* dn and the rounding mode, following IEEE 754 rules.                */\r
+/* ------------------------------------------------------------------ */\r
+static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {\r
+  Flag needmax=0;                  // result is maximum finite value\r
+  uByte sign=dn->bits&DECNEG;      // clean and save sign bit\r
+\r
+  if (ISZERO(dn)) {                // zero does not overflow magnitude\r
+    Int emax=set->emax;                      // limit value\r
+    if (set->clamp) emax-=set->digits-1;     // lower if clamping\r
+    if (dn->exponent>emax) {                 // clamp required\r
+      dn->exponent=emax;\r
+      *status|=DEC_Clamped;\r
+      }\r
+    return;\r
+    }\r
+\r
+  decNumberZero(dn);\r
+  switch (set->round) {\r
+    case DEC_ROUND_DOWN: {\r
+      needmax=1;                   // never Infinity\r
+      break;} // r-d\r
+    case DEC_ROUND_05UP: {\r
+      needmax=1;                   // never Infinity\r
+      break;} // r-05\r
+    case DEC_ROUND_CEILING: {\r
+      if (sign) needmax=1;         // Infinity if non-negative\r
+      break;} // r-c\r
+    case DEC_ROUND_FLOOR: {\r
+      if (!sign) needmax=1;        // Infinity if negative\r
+      break;} // r-f\r
+    default: break;                // Infinity in all other cases\r
+    }\r
+  if (needmax) {\r
+    decSetMaxValue(dn, set);\r
+    dn->bits=sign;                 // set sign\r
+    }\r
+   else dn->bits=sign|DECINF;      // Value is +/-Infinity\r
+  *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;\r
+  } // decSetOverflow\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decSetMaxValue -- set number to +Nmax (maximum normal value)       */\r
+/*                                                                    */\r
+/*   dn is the number to set                                          */\r
+/*   set is the context [used for digits and emax]                    */\r
+/*                                                                    */\r
+/* This sets the number to the maximum positive value.                */\r
+/* ------------------------------------------------------------------ */\r
+static void decSetMaxValue(decNumber *dn, decContext *set) {\r
+  Unit *up;                        // work\r
+  Int count=set->digits;           // nines to add\r
+  dn->digits=count;\r
+  // fill in all nines to set maximum value\r
+  for (up=dn->lsu; ; up++) {\r
+    if (count>DECDPUN) *up=DECDPUNMAX;  // unit full o'nines\r
+     else {                             // this is the msu\r
+      *up=(Unit)(powers[count]-1);\r
+      break;\r
+      }\r
+    count-=DECDPUN;                // filled those digits\r
+    } // up\r
+  dn->bits=0;                      // + sign\r
+  dn->exponent=set->emax-set->digits+1;\r
+  } // decSetMaxValue\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decSetSubnormal -- process value whose exponent is <Emin           */\r
+/*                                                                    */\r
+/*   dn is the number (used as input as well as output; it may have   */\r
+/*         an allowed subnormal value, which may need to be rounded)  */\r
+/*   set is the context [used for the rounding mode]                  */\r
+/*   residue is any pending residue                                   */\r
+/*   status contains the current status to be updated                 */\r
+/*                                                                    */\r
+/* If subset mode, set result to zero and set Underflow flags.        */\r
+/*                                                                    */\r
+/* Value may be zero with a low exponent; this does not set Subnormal */\r
+/* but the exponent will be clamped to Etiny.                         */\r
+/*                                                                    */\r
+/* Otherwise ensure exponent is not out of range, and round as        */\r
+/* necessary.  Underflow is set if the result is Inexact.             */\r
+/* ------------------------------------------------------------------ */\r
+static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,\r
+                            uInt *status) {\r
+  decContext workset;         // work\r
+  Int        etiny, adjust;   // ..\r
+\r
+  #if DECSUBSET\r
+  // simple set to zero and 'hard underflow' for subset\r
+  if (!set->extended) {\r
+    decNumberZero(dn);\r
+    // always full overflow\r
+    *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;\r
+    return;\r
+    }\r
+  #endif\r
+\r
+  // Full arithmetic -- allow subnormals, rounded to minimum exponent\r
+  // (Etiny) if needed\r
+  etiny=set->emin-(set->digits-1);      // smallest allowed exponent\r
+\r
+  if ISZERO(dn) {                       // value is zero\r
+    // residue can never be non-zero here\r
+    #if DECCHECK\r
+      if (*residue!=0) {\r
+        printf("++ Subnormal 0 residue %ld\n", (LI)*residue);\r
+        *status|=DEC_Invalid_operation;\r
+        }\r
+    #endif\r
+    if (dn->exponent<etiny) {           // clamp required\r
+      dn->exponent=etiny;\r
+      *status|=DEC_Clamped;\r
+      }\r
+    return;\r
+    }\r
+\r
+  *status|=DEC_Subnormal;               // have a non-zero subnormal\r
+  adjust=etiny-dn->exponent;            // calculate digits to remove\r
+  if (adjust<=0) {                      // not out of range; unrounded\r
+    // residue can never be non-zero here, except in the Nmin-residue\r
+    // case (which is a subnormal result), so can take fast-path here\r
+    // it may already be inexact (from setting the coefficient)\r
+    if (*status&DEC_Inexact) *status|=DEC_Underflow;\r
+    return;\r
+    }\r
+\r
+  // adjust>0, so need to rescale the result so exponent becomes Etiny\r
+  // [this code is similar to that in rescale]\r
+  workset=*set;                         // clone rounding, etc.\r
+  workset.digits=dn->digits-adjust;     // set requested length\r
+  workset.emin-=adjust;                 // and adjust emin to match\r
+  // [note that the latter can be <1, here, similar to Rescale case]\r
+  decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);\r
+  decApplyRound(dn, &workset, *residue, status);\r
+\r
+  // Use 754 default rule: Underflow is set iff Inexact\r
+  // [independent of whether trapped]\r
+  if (*status&DEC_Inexact) *status|=DEC_Underflow;\r
+\r
+  // if rounded up a 999s case, exponent will be off by one; adjust\r
+  // back if so [it will fit, because it was shortened earlier]\r
+  if (dn->exponent>etiny) {\r
+    dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);\r
+    dn->exponent--;                     // (re)adjust the exponent.\r
+    }\r
+\r
+  // if rounded to zero, it is by definition clamped...\r
+  if (ISZERO(dn)) *status|=DEC_Clamped;\r
+  } // decSetSubnormal\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decCheckMath - check entry conditions for a math function          */\r
+/*                                                                    */\r
+/*   This checks the context and the operand                          */\r
+/*                                                                    */\r
+/*   rhs is the operand to check                                      */\r
+/*   set is the context to check                                      */\r
+/*   status is unchanged if both are good                             */\r
+/*                                                                    */\r
+/* returns non-zero if status is changed, 0 otherwise                 */\r
+/*                                                                    */\r
+/* Restrictions enforced:                                             */\r
+/*                                                                    */\r
+/*   digits, emax, and -emin in the context must be less than         */\r
+/*   DEC_MAX_MATH (999999), and A must be within these bounds if      */\r
+/*   non-zero.  Invalid_operation is set in the status if a           */\r
+/*   restriction is violated.                                         */\r
+/* ------------------------------------------------------------------ */\r
+static uInt decCheckMath(const decNumber *rhs, decContext *set,\r
+                         uInt *status) {\r
+  uInt save=*status;                         // record\r
+  if (set->digits>DEC_MAX_MATH\r
+   || set->emax>DEC_MAX_MATH\r
+   || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;\r
+   else if ((rhs->digits>DEC_MAX_MATH\r
+     || rhs->exponent+rhs->digits>DEC_MAX_MATH+1\r
+     || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))\r
+     && !ISZERO(rhs)) *status|=DEC_Invalid_operation;\r
+  return (*status!=save);\r
+  } // decCheckMath\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decGetInt -- get integer from a number                             */\r
+/*                                                                    */\r
+/*   dn is the number [which will not be altered]                     */\r
+/*                                                                    */\r
+/*   returns one of:                                                  */\r
+/*     BADINT if there is a non-zero fraction                         */\r
+/*     the converted integer                                          */\r
+/*     BIGEVEN if the integer is even and magnitude > 2*10**9         */\r
+/*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */\r
+/*                                                                    */\r
+/* This checks and gets a whole number from the input decNumber.      */\r
+/* The sign can be determined from dn by the caller when BIGEVEN or   */\r
+/* BIGODD is returned.                                                */\r
+/* ------------------------------------------------------------------ */\r
+static Int decGetInt(const decNumber *dn) {\r
+  Int  theInt;                          // result accumulator\r
+  const Unit *up;                       // work\r
+  Int  got;                             // digits (real or not) processed\r
+  Int  ilength=dn->digits+dn->exponent; // integral length\r
+  Flag neg=decNumberIsNegative(dn);     // 1 if -ve\r
+\r
+  // The number must be an integer that fits in 10 digits\r
+  // Assert, here, that 10 is enough for any rescale Etiny\r
+  #if DEC_MAX_EMAX > 999999999\r
+    #error GetInt may need updating [for Emax]\r
+  #endif\r
+  #if DEC_MIN_EMIN < -999999999\r
+    #error GetInt may need updating [for Emin]\r
+  #endif\r
+  if (ISZERO(dn)) return 0;             // zeros are OK, with any exponent\r
+\r
+  up=dn->lsu;                           // ready for lsu\r
+  theInt=0;                             // ready to accumulate\r
+  if (dn->exponent>=0) {                // relatively easy\r
+    // no fractional part [usual]; allow for positive exponent\r
+    got=dn->exponent;\r
+    }\r
+   else { // -ve exponent; some fractional part to check and discard\r
+    Int count=-dn->exponent;            // digits to discard\r
+    // spin up whole units until reach the Unit with the unit digit\r
+    for (; count>=DECDPUN; up++) {\r
+      if (*up!=0) return BADINT;        // non-zero Unit to discard\r
+      count-=DECDPUN;\r
+      }\r
+    if (count==0) got=0;                // [a multiple of DECDPUN]\r
+     else {                             // [not multiple of DECDPUN]\r
+      Int rem;                          // work\r
+      // slice off fraction digits and check for non-zero\r
+      #if DECDPUN<=4\r
+        theInt=QUOT10(*up, count);\r
+        rem=*up-theInt*powers[count];\r
+      #else\r
+        rem=*up%powers[count];          // slice off discards\r
+        theInt=*up/powers[count];\r
+      #endif\r
+      if (rem!=0) return BADINT;        // non-zero fraction\r
+      // it looks good\r
+      got=DECDPUN-count;                // number of digits so far\r
+      up++;                             // ready for next\r
+      }\r
+    }\r
+  // now it's known there's no fractional part\r
+\r
+  // tricky code now, to accumulate up to 9.3 digits\r
+  if (got==0) {theInt=*up; got+=DECDPUN; up++;} // ensure lsu is there\r
+\r
+  if (ilength<11) {\r
+    Int save=theInt;\r
+    // collect any remaining unit(s)\r
+    for (; got<ilength; up++) {\r
+      theInt+=*up*powers[got];\r
+      got+=DECDPUN;\r
+      }\r
+    if (ilength==10) {                  // need to check for wrap\r
+      if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;\r
+         // [that test also disallows the BADINT result case]\r
+       else if (neg && theInt>1999999997) ilength=11;\r
+       else if (!neg && theInt>999999999) ilength=11;\r
+      if (ilength==11) theInt=save;     // restore correct low bit\r
+      }\r
+    }\r
+\r
+  if (ilength>10) {                     // too big\r
+    if (theInt&1) return BIGODD;        // bottom bit 1\r
+    return BIGEVEN;                     // bottom bit 0\r
+    }\r
+\r
+  if (neg) theInt=-theInt;              // apply sign\r
+  return theInt;\r
+  } // decGetInt\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decDecap -- decapitate the coefficient of a number                 */\r
+/*                                                                    */\r
+/*   dn   is the number to be decapitated                             */\r
+/*   drop is the number of digits to be removed from the left of dn;  */\r
+/*     this must be <= dn->digits (if equal, the coefficient is       */\r
+/*     set to 0)                                                      */\r
+/*                                                                    */\r
+/* Returns dn; dn->digits will be <= the initial digits less drop     */\r
+/* (after removing drop digits there may be leading zero digits       */\r
+/* which will also be removed).  Only dn->lsu and dn->digits change.  */\r
+/* ------------------------------------------------------------------ */\r
+static decNumber *decDecap(decNumber *dn, Int drop) {\r
+  Unit *msu;                            // -> target cut point\r
+  Int cut;                              // work\r
+  if (drop>=dn->digits) {               // losing the whole thing\r
+    #if DECCHECK\r
+    if (drop>dn->digits)\r
+      printf("decDecap called with drop>digits [%ld>%ld]\n",\r
+             (LI)drop, (LI)dn->digits);\r
+    #endif\r
+    dn->lsu[0]=0;\r
+    dn->digits=1;\r
+    return dn;\r
+    }\r
+  msu=dn->lsu+D2U(dn->digits-drop)-1;   // -> likely msu\r
+  cut=MSUDIGITS(dn->digits-drop);       // digits to be in use in msu\r
+  if (cut!=DECDPUN) *msu%=powers[cut];  // clear left digits\r
+  // that may have left leading zero digits, so do a proper count...\r
+  dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);\r
+  return dn;\r
+  } // decDecap\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decBiStr -- compare string with pairwise options                   */\r
+/*                                                                    */\r
+/*   targ is the string to compare                                    */\r
+/*   str1 is one of the strings to compare against (length may be 0)  */\r
+/*   str2 is the other; it must be the same length as str1            */\r
+/*                                                                    */\r
+/*   returns 1 if strings compare equal, (that is, it is the same     */\r
+/*   length as str1 and str2, and each character of targ is in either */\r
+/*   str1 or str2 in the corresponding position), or 0 otherwise      */\r
+/*                                                                    */\r
+/* This is used for generic caseless compare, including the awkward   */\r
+/* case of the Turkish dotted and dotless Is.  Use as (for example):  */\r
+/*   if (decBiStr(test, "mike", "MIKE")) ...                          */\r
+/* ------------------------------------------------------------------ */\r
+static Flag decBiStr(const char *targ, const char *str1, const char *str2) {\r
+  for (;;targ++, str1++, str2++) {\r
+    if (*targ!=*str1 && *targ!=*str2) return 0;\r
+    // *targ has a match in one (or both, if terminator)\r
+    if (*targ=='\0') break;\r
+    } // forever\r
+  return 1;\r
+  } // decBiStr\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decNaNs -- handle NaN operand or operands                          */\r
+/*                                                                    */\r
+/*   res     is the result number                                     */\r
+/*   lhs     is the first operand                                     */\r
+/*   rhs     is the second operand, or NULL if none                   */\r
+/*   context is used to limit payload length                          */\r
+/*   status  contains the current status                              */\r
+/*   returns res in case convenient                                   */\r
+/*                                                                    */\r
+/* Called when one or both operands is a NaN, and propagates the      */\r
+/* appropriate result to res.  When an sNaN is found, it is changed   */\r
+/* to a qNaN and Invalid operation is set.                            */\r
+/* ------------------------------------------------------------------ */\r
+static decNumber * decNaNs(decNumber *res, const decNumber *lhs,\r
+                           const decNumber *rhs, decContext *set,\r
+                           uInt *status) {\r
+  // This decision tree ends up with LHS being the source pointer,\r
+  // and status updated if need be\r
+  if (lhs->bits & DECSNAN)\r
+    *status|=DEC_Invalid_operation | DEC_sNaN;\r
+   else if (rhs==NULL);\r
+   else if (rhs->bits & DECSNAN) {\r
+    lhs=rhs;\r
+    *status|=DEC_Invalid_operation | DEC_sNaN;\r
+    }\r
+   else if (lhs->bits & DECNAN);\r
+   else lhs=rhs;\r
+\r
+  // propagate the payload\r
+  if (lhs->digits<=set->digits) decNumberCopy(res, lhs); // easy\r
+   else { // too long\r
+    const Unit *ul;\r
+    Unit *ur, *uresp1;\r
+    // copy safe number of units, then decapitate\r
+    res->bits=lhs->bits;                // need sign etc.\r
+    uresp1=res->lsu+D2U(set->digits);\r
+    for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;\r
+    res->digits=D2U(set->digits)*DECDPUN;\r
+    // maybe still too long\r
+    if (res->digits>set->digits) decDecap(res, res->digits-set->digits);\r
+    }\r
+\r
+  res->bits&=~DECSNAN;        // convert any sNaN to NaN, while\r
+  res->bits|=DECNAN;          // .. preserving sign\r
+  res->exponent=0;            // clean exponent\r
+                              // [coefficient was copied/decapitated]\r
+  return res;\r
+  } // decNaNs\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decStatus -- apply non-zero status                                 */\r
+/*                                                                    */\r
+/*   dn     is the number to set if error                             */\r
+/*   status contains the current status (not yet in context)          */\r
+/*   set    is the context                                            */\r
+/*                                                                    */\r
+/* If the status is an error status, the number is set to a NaN,      */\r
+/* unless the error was an overflow, divide-by-zero, or underflow,    */\r
+/* in which case the number will have already been set.               */\r
+/*                                                                    */\r
+/* The context status is then updated with the new status.  Note that */\r
+/* this may raise a signal, so control may never return from this     */\r
+/* routine (hence resources must be recovered before it is called).   */\r
+/* ------------------------------------------------------------------ */\r
+static void decStatus(decNumber *dn, uInt status, decContext *set) {\r
+  if (status & DEC_NaNs) {              // error status -> NaN\r
+    // if cause was an sNaN, clear and propagate [NaN is already set up]\r
+    if (status & DEC_sNaN) status&=~DEC_sNaN;\r
+     else {\r
+      decNumberZero(dn);                // other error: clean throughout\r
+      dn->bits=DECNAN;                  // and make a quiet NaN\r
+      }\r
+    }\r
+  decContextSetStatus(set, status);     // [may not return]\r
+  return;\r
+  } // decStatus\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decGetDigits -- count digits in a Units array                      */\r
+/*                                                                    */\r
+/*   uar is the Unit array holding the number (this is often an       */\r
+/*          accumulator of some sort)                                 */\r
+/*   len is the length of the array in units [>=1]                    */\r
+/*                                                                    */\r
+/*   returns the number of (significant) digits in the array          */\r
+/*                                                                    */\r
+/* All leading zeros are excluded, except the last if the array has   */\r
+/* only zero Units.                                                   */\r
+/* ------------------------------------------------------------------ */\r
+// This may be called twice during some operations.\r
+static Int decGetDigits(Unit *uar, Int len) {\r
+  Unit *up=uar+(len-1);            // -> msu\r
+  Int  digits=(len-1)*DECDPUN+1;   // possible digits excluding msu\r
+  #if DECDPUN>4\r
+  uInt const *pow;                 // work\r
+  #endif\r
+                                   // (at least 1 in final msu)\r
+  #if DECCHECK\r
+  if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);\r
+  #endif\r
+\r
+  for (; up>=uar; up--) {\r
+    if (*up==0) {                  // unit is all 0s\r
+      if (digits==1) break;        // a zero has one digit\r
+      digits-=DECDPUN;             // adjust for 0 unit\r
+      continue;}\r
+    // found the first (most significant) non-zero Unit\r
+    #if DECDPUN>1                  // not done yet\r
+    if (*up<10) break;             // is 1-9\r
+    digits++;\r
+    #if DECDPUN>2                  // not done yet\r
+    if (*up<100) break;            // is 10-99\r
+    digits++;\r
+    #if DECDPUN>3                  // not done yet\r
+    if (*up<1000) break;           // is 100-999\r
+    digits++;\r
+    #if DECDPUN>4                  // count the rest ...\r
+    for (pow=&powers[4]; *up>=*pow; pow++) digits++;\r
+    #endif\r
+    #endif\r
+    #endif\r
+    #endif\r
+    break;\r
+    } // up\r
+  return digits;\r
+  } // decGetDigits\r
+\r
+#if DECTRACE | DECCHECK\r
+/* ------------------------------------------------------------------ */\r
+/* decNumberShow -- display a number [debug aid]                      */\r
+/*   dn is the number to show                                         */\r
+/*                                                                    */\r
+/* Shows: sign, exponent, coefficient (msu first), digits             */\r
+/*    or: sign, special-value                                         */\r
+/* ------------------------------------------------------------------ */\r
+// this is public so other modules can use it\r
+void decNumberShow(const decNumber *dn) {\r
+  const Unit *up;                  // work\r
+  uInt u, d;                       // ..\r
+  Int cut;                         // ..\r
+  char isign='+';                  // main sign\r
+  if (dn==NULL) {\r
+    printf("NULL\n");\r
+    return;}\r
+  if (decNumberIsNegative(dn)) isign='-';\r
+  printf(" >> %c ", isign);\r
+  if (dn->bits&DECSPECIAL) {       // Is a special value\r
+    if (decNumberIsInfinite(dn)) printf("Infinity");\r
+     else {                                  // a NaN\r
+      if (dn->bits&DECSNAN) printf("sNaN");  // signalling NaN\r
+       else printf("NaN");\r
+      }\r
+    // if coefficient and exponent are 0, no more to do\r
+    if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {\r
+      printf("\n");\r
+      return;}\r
+    // drop through to report other information\r
+    printf(" ");\r
+    }\r
+\r
+  // now carefully display the coefficient\r
+  up=dn->lsu+D2U(dn->digits)-1;         // msu\r
+  printf("%ld", (LI)*up);\r
+  for (up=up-1; up>=dn->lsu; up--) {\r
+    u=*up;\r
+    printf(":");\r
+    for (cut=DECDPUN-1; cut>=0; cut--) {\r
+      d=u/powers[cut];\r
+      u-=d*powers[cut];\r
+      printf("%ld", (LI)d);\r
+      } // cut\r
+    } // up\r
+  if (dn->exponent!=0) {\r
+    char esign='+';\r
+    if (dn->exponent<0) esign='-';\r
+    printf(" E%c%ld", esign, (LI)abs(dn->exponent));\r
+    }\r
+  printf(" [%ld]\n", (LI)dn->digits);\r
+  } // decNumberShow\r
+#endif\r
+\r
+#if DECTRACE || DECCHECK\r
+/* ------------------------------------------------------------------ */\r
+/* decDumpAr -- display a unit array [debug/check aid]                */\r
+/*   name is a single-character tag name                              */\r
+/*   ar   is the array to display                                     */\r
+/*   len  is the length of the array in Units                         */\r
+/* ------------------------------------------------------------------ */\r
+static void decDumpAr(char name, const Unit *ar, Int len) {\r
+  Int i;\r
+  const char *spec;\r
+  #if DECDPUN==9\r
+    spec="%09d ";\r
+  #elif DECDPUN==8\r
+    spec="%08d ";\r
+  #elif DECDPUN==7\r
+    spec="%07d ";\r
+  #elif DECDPUN==6\r
+    spec="%06d ";\r
+  #elif DECDPUN==5\r
+    spec="%05d ";\r
+  #elif DECDPUN==4\r
+    spec="%04d ";\r
+  #elif DECDPUN==3\r
+    spec="%03d ";\r
+  #elif DECDPUN==2\r
+    spec="%02d ";\r
+  #else\r
+    spec="%d ";\r
+  #endif\r
+  printf("  :%c: ", name);\r
+  for (i=len-1; i>=0; i--) {\r
+    if (i==len-1) printf("%ld ", (LI)ar[i]);\r
+     else printf(spec, ar[i]);\r
+    }\r
+  printf("\n");\r
+  return;}\r
+#endif\r
+\r
+#if DECCHECK\r
+/* ------------------------------------------------------------------ */\r
+/* decCheckOperands -- check operand(s) to a routine                  */\r
+/*   res is the result structure (not checked; it will be set to      */\r
+/*          quiet NaN if error found (and it is not NULL))            */\r
+/*   lhs is the first operand (may be DECUNRESU)                      */\r
+/*   rhs is the second (may be DECUNUSED)                             */\r
+/*   set is the context (may be DECUNCONT)                            */\r
+/*   returns 0 if both operands, and the context are clean, or 1      */\r
+/*     otherwise (in which case the context will show an error,       */\r
+/*     unless NULL).  Note that res is not cleaned; caller should     */\r
+/*     handle this so res=NULL case is safe.                          */\r
+/* The caller is expected to abandon immediately if 1 is returned.    */\r
+/* ------------------------------------------------------------------ */\r
+static Flag decCheckOperands(decNumber *res, const decNumber *lhs,\r
+                             const decNumber *rhs, decContext *set) {\r
+  Flag bad=0;\r
+  if (set==NULL) {                 // oops; hopeless\r
+    #if DECTRACE || DECVERB\r
+    printf("Reference to context is NULL.\n");\r
+    #endif\r
+    bad=1;\r
+    return 1;}\r
+   else if (set!=DECUNCONT\r
+     && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {\r
+    bad=1;\r
+    #if DECTRACE || DECVERB\r
+    printf("Bad context [digits=%ld round=%ld].\n",\r
+           (LI)set->digits, (LI)set->round);\r
+    #endif\r
+    }\r
+   else {\r
+    if (res==NULL) {\r
+      bad=1;\r
+      #if DECTRACE\r
+      // this one not DECVERB as standard tests include NULL\r
+      printf("Reference to result is NULL.\n");\r
+      #endif\r
+      }\r
+    if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));\r
+    if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));\r
+    }\r
+  if (bad) {\r
+    if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);\r
+    if (res!=DECUNRESU && res!=NULL) {\r
+      decNumberZero(res);\r
+      res->bits=DECNAN;       // qNaN\r
+      }\r
+    }\r
+  return bad;\r
+  } // decCheckOperands\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decCheckNumber -- check a number                                   */\r
+/*   dn is the number to check                                        */\r
+/*   returns 0 if the number is clean, or 1 otherwise                 */\r
+/*                                                                    */\r
+/* The number is considered valid if it could be a result from some   */\r
+/* operation in some valid context.                                   */\r
+/* ------------------------------------------------------------------ */\r
+static Flag decCheckNumber(const decNumber *dn) {\r
+  const Unit *up;             // work\r
+  uInt maxuint;               // ..\r
+  Int ae, d, digits;          // ..\r
+  Int emin, emax;             // ..\r
+\r
+  if (dn==NULL) {             // hopeless\r
+    #if DECTRACE\r
+    // this one not DECVERB as standard tests include NULL\r
+    printf("Reference to decNumber is NULL.\n");\r
+    #endif\r
+    return 1;}\r
+\r
+  // check special values\r
+  if (dn->bits & DECSPECIAL) {\r
+    if (dn->exponent!=0) {\r
+      #if DECTRACE || DECVERB\r
+      printf("Exponent %ld (not 0) for a special value [%02x].\n",\r
+             (LI)dn->exponent, dn->bits);\r
+      #endif\r
+      return 1;}\r
+\r
+    // 2003.09.08: NaNs may now have coefficients, so next tests Inf only\r
+    if (decNumberIsInfinite(dn)) {\r
+      if (dn->digits!=1) {\r
+        #if DECTRACE || DECVERB\r
+        printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);\r
+        #endif\r
+        return 1;}\r
+      if (*dn->lsu!=0) {\r
+        #if DECTRACE || DECVERB\r
+        printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);\r
+        #endif\r
+        decDumpAr('I', dn->lsu, D2U(dn->digits));\r
+        return 1;}\r
+      } // Inf\r
+    // 2002.12.26: negative NaNs can now appear through proposed IEEE\r
+    //             concrete formats (decimal64, etc.).\r
+    return 0;\r
+    }\r
+\r
+  // check the coefficient\r
+  if (dn->digits<1 || dn->digits>DECNUMMAXP) {\r
+    #if DECTRACE || DECVERB\r
+    printf("Digits %ld in number.\n", (LI)dn->digits);\r
+    #endif\r
+    return 1;}\r
+\r
+  d=dn->digits;\r
+\r
+  for (up=dn->lsu; d>0; up++) {\r
+    if (d>DECDPUN) maxuint=DECDPUNMAX;\r
+     else {                   // reached the msu\r
+      maxuint=powers[d]-1;\r
+      if (dn->digits>1 && *up<powers[d-1]) {\r
+        #if DECTRACE || DECVERB\r
+        printf("Leading 0 in number.\n");\r
+        decNumberShow(dn);\r
+        #endif\r
+        return 1;}\r
+      }\r
+    if (*up>maxuint) {\r
+      #if DECTRACE || DECVERB\r
+      printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",\r
+              (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);\r
+      #endif\r
+      return 1;}\r
+    d-=DECDPUN;\r
+    }\r
+\r
+  // check the exponent.  Note that input operands can have exponents\r
+  // which are out of the set->emin/set->emax and set->digits range\r
+  // (just as they can have more digits than set->digits).\r
+  ae=dn->exponent+dn->digits-1;    // adjusted exponent\r
+  emax=DECNUMMAXE;\r
+  emin=DECNUMMINE;\r
+  digits=DECNUMMAXP;\r
+  if (ae<emin-(digits-1)) {\r
+    #if DECTRACE || DECVERB\r
+    printf("Adjusted exponent underflow [%ld].\n", (LI)ae);\r
+    decNumberShow(dn);\r
+    #endif\r
+    return 1;}\r
+  if (ae>+emax) {\r
+    #if DECTRACE || DECVERB\r
+    printf("Adjusted exponent overflow [%ld].\n", (LI)ae);\r
+    decNumberShow(dn);\r
+    #endif\r
+    return 1;}\r
+\r
+  return 0;              // it's OK\r
+  } // decCheckNumber\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decCheckInexact -- check a normal finite inexact result has digits */\r
+/*   dn is the number to check                                        */\r
+/*   set is the context (for status and precision)                    */\r
+/*   sets Invalid operation, etc., if some digits are missing         */\r
+/* [this check is not made for DECSUBSET compilation or when          */\r
+/* subnormal is not set]                                              */\r
+/* ------------------------------------------------------------------ */\r
+static void decCheckInexact(const decNumber *dn, decContext *set) {\r
+  #if !DECSUBSET && DECEXTFLAG\r
+    if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact\r
+     && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {\r
+      #if DECTRACE || DECVERB\r
+      printf("Insufficient digits [%ld] on normal Inexact result.\n",\r
+             (LI)dn->digits);\r
+      decNumberShow(dn);\r
+      #endif\r
+      decContextSetStatus(set, DEC_Invalid_operation);\r
+      }\r
+  #else\r
+    // next is a noop for quiet compiler\r
+    if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;\r
+  #endif\r
+  return;\r
+  } // decCheckInexact\r
+#endif\r
+\r
+#if DECALLOC\r
+#undef malloc\r
+#undef free\r
+/* ------------------------------------------------------------------ */\r
+/* decMalloc -- accountable allocation routine                        */\r
+/*   n is the number of bytes to allocate                             */\r
+/*                                                                    */\r
+/* Semantics is the same as the stdlib malloc routine, but bytes      */\r
+/* allocated are accounted for globally, and corruption fences are    */\r
+/* added before and after the 'actual' storage.                       */\r
+/* ------------------------------------------------------------------ */\r
+/* This routine allocates storage with an extra twelve bytes; 8 are   */\r
+/* at the start and hold:                                             */\r
+/*   0-3 the original length requested                                */\r
+/*   4-7 buffer corruption detection fence (DECFENCE, x4)             */\r
+/* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */\r
+/* ------------------------------------------------------------------ */\r
+static void *decMalloc(size_t n) {\r
+  uInt  size=n+12;                 // true size\r
+  void  *alloc;                    // -> allocated storage\r
+  uByte *b, *b0;                   // work\r
+  uInt  uiwork;                    // for macros\r
+\r
+  alloc=malloc(size);              // -> allocated storage\r
+  if (alloc==NULL) return NULL;    // out of strorage\r
+  b0=(uByte *)alloc;               // as bytes\r
+  decAllocBytes+=n;                // account for storage\r
+  UBFROMUI(alloc, n);              // save n\r
+  // printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);\r
+  for (b=b0+4; b<b0+8; b++) *b=DECFENCE;\r
+  for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;\r
+  return b0+8;                     // -> play area\r
+  } // decMalloc\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decFree -- accountable free routine                                */\r
+/*   alloc is the storage to free                                     */\r
+/*                                                                    */\r
+/* Semantics is the same as the stdlib malloc routine, except that    */\r
+/* the global storage accounting is updated and the fences are        */\r
+/* checked to ensure that no routine has written 'out of bounds'.     */\r
+/* ------------------------------------------------------------------ */\r
+/* This routine first checks that the fences have not been corrupted. */\r
+/* It then frees the storage using the 'truw' storage address (that   */\r
+/* is, offset by 8).                                                  */\r
+/* ------------------------------------------------------------------ */\r
+static void decFree(void *alloc) {\r
+  uInt  n;                         // original length\r
+  uByte *b, *b0;                   // work\r
+  uInt  uiwork;                    // for macros\r
+\r
+  if (alloc==NULL) return;         // allowed; it's a nop\r
+  b0=(uByte *)alloc;               // as bytes\r
+  b0-=8;                           // -> true start of storage\r
+  n=UBTOUI(b0);                    // lift length\r
+  for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)\r
+    printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,\r
+           b-b0-8, (LI)b0);\r
+  for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)\r
+    printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,\r
+           b-b0-8, (LI)b0, (LI)n);\r
+  free(b0);                        // drop the storage\r
+  decAllocBytes-=n;                // account for storage\r
+  // printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);\r
+  } // decFree\r
+#define malloc(a) decMalloc(a)\r
+#define free(a) decFree(a)\r
+#endif\r
diff --git a/src/decNumber/decNumber.h b/src/decNumber/decNumber.h
new file mode 100644 (file)
index 0000000..6f8a5a3
--- /dev/null
@@ -0,0 +1,182 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number arithmetic module header                            */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2010.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#if !defined(DECNUMBER)\r
+  #define DECNUMBER\r
+  #define DECNAME     "decNumber"                       /* Short name */\r
+  #define DECFULLNAME "Decimal Number Module"         /* Verbose name */\r
+  #define DECAUTHOR   "Mike Cowlishaw"                /* Who to blame */\r
+\r
+  #if !defined(DECCONTEXT)\r
+    #include "decContext.h"\r
+  #endif\r
+\r
+  /* Bit settings for decNumber.bits                                  */\r
+  #define DECNEG    0x80      /* Sign; 1=negative, 0=positive or zero */\r
+  #define DECINF    0x40      /* 1=Infinity                           */\r
+  #define DECNAN    0x20      /* 1=NaN                                */\r
+  #define DECSNAN   0x10      /* 1=sNaN                               */\r
+  /* The remaining bits are reserved; they must be 0                  */\r
+  #define DECSPECIAL (DECINF|DECNAN|DECSNAN) /* any special value     */\r
+\r
+  /* Define the decNumber data structure.  The size and shape of the  */\r
+  /* units array in the structure is determined by the following      */\r
+  /* constant.  This must not be changed without recompiling the      */\r
+  /* decNumber library modules. */\r
+\r
+  #define DECDPUN 3           /* DECimal Digits Per UNit [must be >0  */\r
+                              /* and <10; 3 or powers of 2 are best]. */\r
+\r
+  /* DECNUMDIGITS is the default number of digits that can be held in */\r
+  /* the structure.  If undefined, 1 is assumed and it is assumed     */\r
+  /* that the structure will be immediately followed by extra space,  */\r
+  /* as required.  DECNUMDIGITS is always >0.                         */\r
+  #if !defined(DECNUMDIGITS)\r
+    #define DECNUMDIGITS 1\r
+  #endif\r
+\r
+  /* The size (integer data type) of each unit is determined by the   */\r
+  /* number of digits it will hold.                                   */\r
+  #if   DECDPUN<=2\r
+    #define decNumberUnit uint8_t\r
+  #elif DECDPUN<=4\r
+    #define decNumberUnit uint16_t\r
+  #else\r
+    #define decNumberUnit uint32_t\r
+  #endif\r
+  /* The number of units needed is ceil(DECNUMDIGITS/DECDPUN)         */\r
+  #define DECNUMUNITS ((DECNUMDIGITS+DECDPUN-1)/DECDPUN)\r
+\r
+  /* The data structure... */\r
+  typedef struct {\r
+    int32_t digits;      /* Count of digits in the coefficient; >0    */\r
+    int32_t exponent;    /* Unadjusted exponent, unbiased, in         */\r
+                         /* range: -1999999997 through 999999999      */\r
+    uint8_t bits;        /* Indicator bits (see above)                */\r
+                         /* Coefficient, from least significant unit  */\r
+    decNumberUnit lsu[DECNUMUNITS];\r
+    } decNumber;\r
+\r
+  /* Notes:                                                           */\r
+  /* 1. If digits is > DECDPUN then there will one or more            */\r
+  /*    decNumberUnits immediately following the first element of lsu.*/\r
+  /*    These contain the remaining (more significant) digits of the  */\r
+  /*    number, and may be in the lsu array, or may be guaranteed by  */\r
+  /*    some other mechanism (such as being contained in another      */\r
+  /*    structure, or being overlaid on dynamically allocated         */\r
+  /*    storage).                                                     */\r
+  /*                                                                  */\r
+  /*    Each integer of the coefficient (except potentially the last) */\r
+  /*    contains DECDPUN digits (e.g., a value in the range 0 through */\r
+  /*    99999999 if DECDPUN is 8, or 0 through 999 if DECDPUN is 3).  */\r
+  /*                                                                  */\r
+  /* 2. A decNumber converted to a string may need up to digits+14    */\r
+  /*    characters.  The worst cases (non-exponential and exponential */\r
+  /*    formats) are -0.00000{9...}# and -9.{9...}E+999999999#        */\r
+  /*    (where # is '\0')                                             */\r
+\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* decNumber public functions and macros                            */\r
+  /* ---------------------------------------------------------------- */\r
+  /* Conversions                                                      */\r
+  decNumber * decNumberFromInt32(decNumber *, int32_t);\r
+  decNumber * decNumberFromUInt32(decNumber *, uint32_t);\r
+  decNumber * decNumberFromString(decNumber *, const char *, decContext *);\r
+  char      * decNumberToString(const decNumber *, char *);\r
+  char      * decNumberToEngString(const decNumber *, char *);\r
+  uint32_t    decNumberToUInt32(const decNumber *, decContext *);\r
+  int32_t     decNumberToInt32(const decNumber *, decContext *);\r
+  uint8_t   * decNumberGetBCD(const decNumber *, uint8_t *);\r
+  decNumber * decNumberSetBCD(decNumber *, const uint8_t *, uint32_t);\r
+\r
+  /* Operators and elementary functions                               */\r
+  decNumber * decNumberAbs(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberAdd(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberAnd(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberCompare(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberCompareSignal(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberCompareTotal(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberCompareTotalMag(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberDivide(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberDivideInteger(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberExp(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberFMA(decNumber *, const decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberInvert(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberLn(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberLogB(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberLog10(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberMax(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberMaxMag(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberMin(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberMinMag(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberMinus(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberMultiply(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberNormalize(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberOr(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberPlus(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberPower(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberQuantize(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberReduce(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberRemainder(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberRemainderNear(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberRescale(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberRotate(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberSameQuantum(decNumber *, const decNumber *, const decNumber *);\r
+  decNumber * decNumberScaleB(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberShift(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberSquareRoot(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberSubtract(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberToIntegralExact(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberToIntegralValue(decNumber *, const decNumber *, decContext *);\r
+  decNumber * decNumberXor(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+\r
+  /* Utilities                                                        */\r
+  enum decClass decNumberClass(const decNumber *, decContext *);\r
+  const char * decNumberClassToString(enum decClass);\r
+  decNumber  * decNumberCopy(decNumber *, const decNumber *);\r
+  decNumber  * decNumberCopyAbs(decNumber *, const decNumber *);\r
+  decNumber  * decNumberCopyNegate(decNumber *, const decNumber *);\r
+  decNumber  * decNumberCopySign(decNumber *, const decNumber *, const decNumber *);\r
+  decNumber  * decNumberNextMinus(decNumber *, const decNumber *, decContext *);\r
+  decNumber  * decNumberNextPlus(decNumber *, const decNumber *, decContext *);\r
+  decNumber  * decNumberNextToward(decNumber *, const decNumber *, const decNumber *, decContext *);\r
+  decNumber  * decNumberTrim(decNumber *);\r
+  const char * decNumberVersion(void);\r
+  decNumber  * decNumberZero(decNumber *);\r
+\r
+  /* Functions for testing decNumbers (normality depends on context)  */\r
+  int32_t decNumberIsNormal(const decNumber *, decContext *);\r
+  int32_t decNumberIsSubnormal(const decNumber *, decContext *);\r
+\r
+  /* Macros for testing decNumber *dn                                 */\r
+  #define decNumberIsCanonical(dn) (1)  /* All decNumbers are saintly */\r
+  #define decNumberIsFinite(dn)    (((dn)->bits&DECSPECIAL)==0)\r
+  #define decNumberIsInfinite(dn)  (((dn)->bits&DECINF)!=0)\r
+  #define decNumberIsNaN(dn)       (((dn)->bits&(DECNAN|DECSNAN))!=0)\r
+  #define decNumberIsNegative(dn)  (((dn)->bits&DECNEG)!=0)\r
+  #define decNumberIsQNaN(dn)      (((dn)->bits&(DECNAN))!=0)\r
+  #define decNumberIsSNaN(dn)      (((dn)->bits&(DECSNAN))!=0)\r
+  #define decNumberIsSpecial(dn)   (((dn)->bits&DECSPECIAL)!=0)\r
+  #define decNumberIsZero(dn)      (*(dn)->lsu==0 \\r
+                                    && (dn)->digits==1 \\r
+                                    && (((dn)->bits&DECSPECIAL)==0))\r
+  #define decNumberRadix(dn)       (10)\r
+\r
+#endif\r
diff --git a/src/decNumber/decNumberLocal.h b/src/decNumber/decNumberLocal.h
new file mode 100644 (file)
index 0000000..5c88a5e
--- /dev/null
@@ -0,0 +1,757 @@
+/* ------------------------------------------------------------------ */\r
+/* decNumber package local type, tuning, and macro definitions        */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2010.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This header file is included by all modules in the decNumber       */\r
+/* library, and contains local type definitions, tuning parameters,   */\r
+/* etc.  It should not need to be used by application programs.       */\r
+/* decNumber.h or one of decDouble (etc.) must be included first.     */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#if !defined(DECNUMBERLOC)\r
+  #define DECNUMBERLOC\r
+  #define DECVERSION    "decNumber 3.68" /* Package Version [16 max.] */\r
+  #define DECNLAUTHOR   "Mike Cowlishaw"              /* Who to blame */\r
+\r
+  #include <stdlib.h>         /* for abs                              */\r
+  #include <string.h>         /* for memset, strcpy                   */\r
+\r
+  /* Conditional code flag -- set this to match hardware platform     */\r
+  #if !defined(DECLITEND)\r
+  #define DECLITEND 1         /* 1=little-endian, 0=big-endian        */\r
+  #endif\r
+\r
+  /* Conditional code flag -- set this to 1 for best performance      */\r
+  #if !defined(DECUSE64)\r
+  #define DECUSE64  1         /* 1=use int64s, 0=int32 & smaller only */\r
+  #endif\r
+\r
+  /* Conditional code flag -- set this to 0 to exclude printf calls   */\r
+  #if !defined(DECPRINT)\r
+  #define DECPRINT  1         /* 1=allow printf calls; 0=no printf    */\r
+  #endif\r
+\r
+  /* Conditional check flags -- set these to 0 for best performance   */\r
+  #if !defined(DECCHECK)\r
+  #define DECCHECK  0         /* 1 to enable robust checking          */\r
+  #endif\r
+  #if !defined(DECALLOC)\r
+  #define DECALLOC  0         /* 1 to enable memory accounting        */\r
+  #endif\r
+  #if !defined(DECTRACE)\r
+  #define DECTRACE  0         /* 1 to trace certain internals, etc.   */\r
+  #endif\r
+\r
+  /* Tuning parameter for decNumber (arbitrary precision) module      */\r
+  #if !defined(DECBUFFER)\r
+  #define DECBUFFER 36        /* Size basis for local buffers.  This  */\r
+                              /* should be a common maximum precision */\r
+                              /* rounded up to a multiple of 4; must  */\r
+                              /* be zero or positive.                 */\r
+  #endif\r
+\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Check parameter dependencies                                     */\r
+  /* ---------------------------------------------------------------- */\r
+  #if DECCHECK & !DECPRINT\r
+    #error DECCHECK needs DECPRINT to be useful\r
+  #endif\r
+  #if DECALLOC & !DECPRINT\r
+    #error DECALLOC needs DECPRINT to be useful\r
+  #endif\r
+  #if DECTRACE & !DECPRINT\r
+    #error DECTRACE needs DECPRINT to be useful\r
+  #endif\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Definitions for all modules (general-purpose)                    */\r
+  /* ---------------------------------------------------------------- */\r
+\r
+  /* Local names for common types -- for safety, decNumber modules do */\r
+  /* not use int or long directly.                                    */\r
+  #define Flag   uint8_t\r
+  #define Byte   int8_t\r
+  #define uByte  uint8_t\r
+  #define Short  int16_t\r
+  #define uShort uint16_t\r
+  #define Int    int32_t\r
+  #define uInt   uint32_t\r
+  #define Unit   decNumberUnit\r
+  #if DECUSE64\r
+  #define Long   int64_t\r
+  #define uLong  uint64_t\r
+  #endif\r
+\r
+  /* Development-use definitions                                      */\r
+  typedef long int LI;        /* for printf arguments only            */\r
+  #define DECNOINT  0         /* 1 to check no internal use of 'int'  */\r
+                              /*   or stdint types                    */\r
+  #if DECNOINT\r
+    /* if these interfere with your C includes, do not set DECNOINT   */\r
+    #define int     ?         /* enable to ensure that plain C 'int'  */\r
+    #define long    ??        /* .. or 'long' types are not used      */\r
+  #endif\r
+\r
+  /* Shared lookup tables                                             */\r
+  extern const uByte  DECSTICKYTAB[10]; /* re-round digits if sticky  */\r
+  extern const uInt   DECPOWERS[10];    /* powers of ten table        */\r
+  /* The following are included from decDPD.h                         */\r
+  extern const uShort DPD2BIN[1024];    /* DPD -> 0-999               */\r
+  extern const uShort BIN2DPD[1000];    /* 0-999 -> DPD               */\r
+  extern const uInt   DPD2BINK[1024];   /* DPD -> 0-999000            */\r
+  extern const uInt   DPD2BINM[1024];   /* DPD -> 0-999000000         */\r
+  extern const uByte  DPD2BCD8[4096];   /* DPD -> ddd + len           */\r
+  extern const uByte  BIN2BCD8[4000];   /* 0-999 -> ddd + len         */\r
+  extern const uShort BCD2DPD[2458];    /* 0-0x999 -> DPD (0x999=2457)*/\r
+\r
+  /* LONGMUL32HI -- set w=(u*v)>>32, where w, u, and v are uInts      */\r
+  /* (that is, sets w to be the high-order word of the 64-bit result; */\r
+  /* the low-order word is simply u*v.)                               */\r
+  /* This version is derived from Knuth via Hacker's Delight;         */\r
+  /* it seems to optimize better than some others tried               */\r
+  #define LONGMUL32HI(w, u, v) {             \\r
+    uInt u0, u1, v0, v1, w0, w1, w2, t;      \\r
+    u0=u & 0xffff; u1=u>>16;                 \\r
+    v0=v & 0xffff; v1=v>>16;                 \\r
+    w0=u0*v0;                                \\r
+    t=u1*v0 + (w0>>16);                      \\r
+    w1=t & 0xffff; w2=t>>16;                 \\r
+    w1=u0*v1 + w1;                           \\r
+    (w)=u1*v1 + w2 + (w1>>16);}\r
+\r
+  /* ROUNDUP -- round an integer up to a multiple of n                */\r
+  #define ROUNDUP(i, n) ((((i)+(n)-1)/n)*n)\r
+  #define ROUNDUP4(i)   (((i)+3)&~3)    /* special for n=4            */\r
+\r
+  /* ROUNDDOWN -- round an integer down to a multiple of n            */\r
+  #define ROUNDDOWN(i, n) (((i)/n)*n)\r
+  #define ROUNDDOWN4(i)   ((i)&~3)      /* special for n=4            */\r
+\r
+  /* References to multi-byte sequences under different sizes; these  */\r
+  /* require locally declared variables, but do not violate strict    */\r
+  /* aliasing or alignment (as did the UINTAT simple cast to uInt).   */\r
+  /* Variables needed are uswork, uiwork, etc. [so do not use at same */\r
+  /* level in an expression, e.g., UBTOUI(x)==UBTOUI(y) may fail].    */\r
+\r
+  /* Return a uInt, etc., from bytes starting at a char* or uByte*    */\r
+  #define UBTOUS(b)  (memcpy((void *)&uswork, b, 2), uswork)\r
+  #define UBTOUI(b)  (memcpy((void *)&uiwork, b, 4), uiwork)\r
+\r
+  /* Store a uInt, etc., into bytes starting at a char* or uByte*.    */\r
+  /* Returns i, evaluated, for convenience; has to use uiwork because */\r
+  /* i may be an expression.                                          */\r
+  #define UBFROMUS(b, i)  (uswork=(i), memcpy(b, (void *)&uswork, 2), uswork)\r
+  #define UBFROMUI(b, i)  (uiwork=(i), memcpy(b, (void *)&uiwork, 4), uiwork)\r
+\r
+  /* X10 and X100 -- multiply integer i by 10 or 100                  */\r
+  /* [shifts are usually faster than multiply; could be conditional]  */\r
+  #define X10(i)  (((i)<<1)+((i)<<3))\r
+  #define X100(i) (((i)<<2)+((i)<<5)+((i)<<6))\r
+\r
+  /* MAXI and MINI -- general max & min (not in ANSI) for integers    */\r
+  #define MAXI(x,y) ((x)<(y)?(y):(x))\r
+  #define MINI(x,y) ((x)>(y)?(y):(x))\r
+\r
+  /* Useful constants                                                 */\r
+  #define BILLION      1000000000            /* 10**9                 */\r
+  /* CHARMASK: 0x30303030 for ASCII/UTF8; 0xF0F0F0F0 for EBCDIC       */\r
+  #define CHARMASK ((((((((uInt)'0')<<8)+'0')<<8)+'0')<<8)+'0')\r
+\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Definitions for arbitary-precision modules (only valid after     */\r
+  /* decNumber.h has been included)                                   */\r
+  /* ---------------------------------------------------------------- */\r
+\r
+  /* Limits and constants                                             */\r
+  #define DECNUMMAXP 999999999  /* maximum precision code can handle  */\r
+  #define DECNUMMAXE 999999999  /* maximum adjusted exponent ditto    */\r
+  #define DECNUMMINE -999999999 /* minimum adjusted exponent ditto    */\r
+  #if (DECNUMMAXP != DEC_MAX_DIGITS)\r
+    #error Maximum digits mismatch\r
+  #endif\r
+  #if (DECNUMMAXE != DEC_MAX_EMAX)\r
+    #error Maximum exponent mismatch\r
+  #endif\r
+  #if (DECNUMMINE != DEC_MIN_EMIN)\r
+    #error Minimum exponent mismatch\r
+  #endif\r
+\r
+  /* Set DECDPUNMAX -- the maximum integer that fits in DECDPUN       */\r
+  /* digits, and D2UTABLE -- the initializer for the D2U table        */\r
+  #if   DECDPUN==1\r
+    #define DECDPUNMAX 9\r
+    #define D2UTABLE {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,  \\r
+                      18,19,20,21,22,23,24,25,26,27,28,29,30,31,32, \\r
+                      33,34,35,36,37,38,39,40,41,42,43,44,45,46,47, \\r
+                      48,49}\r
+  #elif DECDPUN==2\r
+    #define DECDPUNMAX 99\r
+    #define D2UTABLE {0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,  \\r
+                      11,11,12,12,13,13,14,14,15,15,16,16,17,17,18, \\r
+                      18,19,19,20,20,21,21,22,22,23,23,24,24,25}\r
+  #elif DECDPUN==3\r
+    #define DECDPUNMAX 999\r
+    #define D2UTABLE {0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,  \\r
+                      8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13, \\r
+                      13,14,14,14,15,15,15,16,16,16,17}\r
+  #elif DECDPUN==4\r
+    #define DECDPUNMAX 9999\r
+    #define D2UTABLE {0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,  \\r
+                      6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11, \\r
+                      11,11,11,12,12,12,12,13}\r
+  #elif DECDPUN==5\r
+    #define DECDPUNMAX 99999\r
+    #define D2UTABLE {0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,  \\r
+                      5,5,5,5,6,6,6,6,6,7,7,7,7,7,8,8,8,8,8,9,9,9,  \\r
+                      9,9,10,10,10,10}\r
+  #elif DECDPUN==6\r
+    #define DECDPUNMAX 999999\r
+    #define D2UTABLE {0,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,  \\r
+                      4,4,4,5,5,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,8,  \\r
+                      8,8,8,8,8,9}\r
+  #elif DECDPUN==7\r
+    #define DECDPUNMAX 9999999\r
+    #define D2UTABLE {0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3,  \\r
+                      4,4,4,4,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,6,7,  \\r
+                      7,7,7,7,7,7}\r
+  #elif DECDPUN==8\r
+    #define DECDPUNMAX 99999999\r
+    #define D2UTABLE {0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,  \\r
+                      3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6,  \\r
+                      6,6,6,6,6,7}\r
+  #elif DECDPUN==9\r
+    #define DECDPUNMAX 999999999\r
+    #define D2UTABLE {0,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,3,  \\r
+                      3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,  \\r
+                      5,5,6,6,6,6}\r
+  #elif defined(DECDPUN)\r
+    #error DECDPUN must be in the range 1-9\r
+  #endif\r
+\r
+  /* ----- Shared data (in decNumber.c) ----- */\r
+  /* Public lookup table used by the D2U macro (see below)            */\r
+  #define DECMAXD2U 49\r
+  extern const uByte d2utable[DECMAXD2U+1];\r
+\r
+  /* ----- Macros ----- */\r
+  /* ISZERO -- return true if decNumber dn is a zero                  */\r
+  /* [performance-critical in some situations]                        */\r
+  #define ISZERO(dn) decNumberIsZero(dn)     /* now just a local name */\r
+\r
+  /* D2U -- return the number of Units needed to hold d digits        */\r
+  /* (runtime version, with table lookaside for small d)              */\r
+  #if DECDPUN==8\r
+    #define D2U(d) ((unsigned)((d)<=DECMAXD2U?d2utable[d]:((d)+7)>>3))\r
+  #elif DECDPUN==4\r
+    #define D2U(d) ((unsigned)((d)<=DECMAXD2U?d2utable[d]:((d)+3)>>2))\r
+  #else\r
+    #define D2U(d) ((d)<=DECMAXD2U?d2utable[d]:((d)+DECDPUN-1)/DECDPUN)\r
+  #endif\r
+  /* SD2U -- static D2U macro (for compile-time calculation)          */\r
+  #define SD2U(d) (((d)+DECDPUN-1)/DECDPUN)\r
+\r
+  /* MSUDIGITS -- returns digits in msu, from digits, calculated      */\r
+  /* using D2U                                                        */\r
+  #define MSUDIGITS(d) ((d)-(D2U(d)-1)*DECDPUN)\r
+\r
+  /* D2N -- return the number of decNumber structs that would be      */\r
+  /* needed to contain that number of digits (and the initial         */\r
+  /* decNumber struct) safely.  Note that one Unit is included in the */\r
+  /* initial structure.  Used for allocating space that is aligned on */\r
+  /* a decNumber struct boundary. */\r
+  #define D2N(d) \\r
+    ((((SD2U(d)-1)*sizeof(Unit))+sizeof(decNumber)*2-1)/sizeof(decNumber))\r
+\r
+  /* TODIGIT -- macro to remove the leading digit from the unsigned   */\r
+  /* integer u at column cut (counting from the right, LSD=0) and     */\r
+  /* place it as an ASCII character into the character pointed to by  */\r
+  /* c.  Note that cut must be <= 9, and the maximum value for u is   */\r
+  /* 2,000,000,000 (as is needed for negative exponents of            */\r
+  /* subnormals).  The unsigned integer pow is used as a temporary    */\r
+  /* variable. */\r
+  #define TODIGIT(u, cut, c, pow) {       \\r
+    *(c)='0';                             \\r
+    pow=DECPOWERS[cut]*2;                 \\r
+    if ((u)>pow) {                        \\r
+      pow*=4;                             \\r
+      if ((u)>=pow) {(u)-=pow; *(c)+=8;}  \\r
+      pow/=2;                             \\r
+      if ((u)>=pow) {(u)-=pow; *(c)+=4;}  \\r
+      pow/=2;                             \\r
+      }                                   \\r
+    if ((u)>=pow) {(u)-=pow; *(c)+=2;}    \\r
+    pow/=2;                               \\r
+    if ((u)>=pow) {(u)-=pow; *(c)+=1;}    \\r
+    }\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Definitions for fixed-precision modules (only valid after        */\r
+  /* decSingle.h, decDouble.h, or decQuad.h has been included)        */\r
+  /* ---------------------------------------------------------------- */\r
+\r
+  /* bcdnum -- a structure describing a format-independent finite     */\r
+  /* number, whose coefficient is a string of bcd8 uBytes             */\r
+  typedef struct {\r
+    uByte   *msd;             /* -> most significant digit            */\r
+    uByte   *lsd;             /* -> least ditto                       */\r
+    uInt     sign;            /* 0=positive, DECFLOAT_Sign=negative   */\r
+    Int      exponent;        /* Unadjusted signed exponent (q), or   */\r
+                              /* DECFLOAT_NaN etc. for a special      */\r
+    } bcdnum;\r
+\r
+  /* Test if exponent or bcdnum exponent must be a special, etc.      */\r
+  #define EXPISSPECIAL(exp) ((exp)>=DECFLOAT_MinSp)\r
+  #define EXPISINF(exp) (exp==DECFLOAT_Inf)\r
+  #define EXPISNAN(exp) (exp==DECFLOAT_qNaN || exp==DECFLOAT_sNaN)\r
+  #define NUMISSPECIAL(num) (EXPISSPECIAL((num)->exponent))\r
+\r
+  /* Refer to a 32-bit word or byte in a decFloat (df) by big-endian  */\r
+  /* (array) notation (the 0 word or byte contains the sign bit),     */\r
+  /* automatically adjusting for endianness; similarly address a word */\r
+  /* in the next-wider format (decFloatWider, or dfw)                 */\r
+  #define DECWORDS  (DECBYTES/4)\r
+  #define DECWWORDS (DECWBYTES/4)\r
+  #if DECLITEND\r
+    #define DFBYTE(df, off)   ((df)->bytes[DECBYTES-1-(off)])\r
+    #define DFWORD(df, off)   ((df)->words[DECWORDS-1-(off)])\r
+    #define DFWWORD(dfw, off) ((dfw)->words[DECWWORDS-1-(off)])\r
+  #else\r
+    #define DFBYTE(df, off)   ((df)->bytes[off])\r
+    #define DFWORD(df, off)   ((df)->words[off])\r
+    #define DFWWORD(dfw, off) ((dfw)->words[off])\r
+  #endif\r
+\r
+  /* Tests for sign or specials, directly on DECFLOATs                */\r
+  #define DFISSIGNED(df)  ((DFWORD(df, 0)&0x80000000)!=0)\r
+  #define DFISSPECIAL(df) ((DFWORD(df, 0)&0x78000000)==0x78000000)\r
+  #define DFISINF(df)     ((DFWORD(df, 0)&0x7c000000)==0x78000000)\r
+  #define DFISNAN(df)     ((DFWORD(df, 0)&0x7c000000)==0x7c000000)\r
+  #define DFISQNAN(df)    ((DFWORD(df, 0)&0x7e000000)==0x7c000000)\r
+  #define DFISSNAN(df)    ((DFWORD(df, 0)&0x7e000000)==0x7e000000)\r
+\r
+  /* Shared lookup tables                                             */\r
+  extern const uInt   DECCOMBMSD[64];   /* Combination field -> MSD   */\r
+  extern const uInt   DECCOMBFROM[48];  /* exp+msd -> Combination     */\r
+\r
+  /* Private generic (utility) routine                                */\r
+  #if DECCHECK || DECTRACE\r
+    extern void decShowNum(const bcdnum *, const char *);\r
+  #endif\r
+\r
+  /* Format-dependent macros and constants                            */\r
+  #if defined(DECPMAX)\r
+\r
+    /* Useful constants                                               */\r
+    #define DECPMAX9  (ROUNDUP(DECPMAX, 9)/9)  /* 'Pmax' in 10**9s    */\r
+    /* Top words for a zero                                           */\r
+    #define SINGLEZERO   0x22500000\r
+    #define DOUBLEZERO   0x22380000\r
+    #define QUADZERO     0x22080000\r
+    /* [ZEROWORD is defined to be one of these in the DFISZERO macro] */\r
+\r
+    /* Format-dependent common tests:                                 */\r
+    /*   DFISZERO   -- test for (any) zero                            */\r
+    /*   DFISCCZERO -- test for coefficient continuation being zero   */\r
+    /*   DFISCC01   -- test for coefficient contains only 0s and 1s   */\r
+    /*   DFISINT    -- test for finite and exponent q=0               */\r
+    /*   DFISUINT01 -- test for sign=0, finite, exponent q=0, and     */\r
+    /*                 MSD=0 or 1                                     */\r
+    /*   ZEROWORD is also defined here.                               */\r
+    /*                                                                */\r
+    /* In DFISZERO the first test checks the least-significant word   */\r
+    /* (most likely to be non-zero); the penultimate tests MSD and    */\r
+    /* DPDs in the signword, and the final test excludes specials and */\r
+    /* MSD>7.  DFISINT similarly has to allow for the two forms of    */\r
+    /* MSD codes.  DFISUINT01 only has to allow for one form of MSD   */\r
+    /* code.                                                          */\r
+    #if DECPMAX==7\r
+      #define ZEROWORD SINGLEZERO\r
+      /* [test macros not needed except for Zero]                     */\r
+      #define DFISZERO(df)  ((DFWORD(df, 0)&0x1c0fffff)==0         \\r
+                          && (DFWORD(df, 0)&0x60000000)!=0x60000000)\r
+    #elif DECPMAX==16\r
+      #define ZEROWORD DOUBLEZERO\r
+      #define DFISZERO(df)  ((DFWORD(df, 1)==0                     \\r
+                          && (DFWORD(df, 0)&0x1c03ffff)==0         \\r
+                          && (DFWORD(df, 0)&0x60000000)!=0x60000000))\r
+      #define DFISINT(df) ((DFWORD(df, 0)&0x63fc0000)==0x22380000  \\r
+                         ||(DFWORD(df, 0)&0x7bfc0000)==0x6a380000)\r
+      #define DFISUINT01(df) ((DFWORD(df, 0)&0xfbfc0000)==0x22380000)\r
+      #define DFISCCZERO(df) (DFWORD(df, 1)==0                     \\r
+                          && (DFWORD(df, 0)&0x0003ffff)==0)\r
+      #define DFISCC01(df)  ((DFWORD(df, 0)&~0xfffc9124)==0        \\r
+                          && (DFWORD(df, 1)&~0x49124491)==0)\r
+    #elif DECPMAX==34\r
+      #define ZEROWORD QUADZERO\r
+      #define DFISZERO(df)  ((DFWORD(df, 3)==0                     \\r
+                          &&  DFWORD(df, 2)==0                     \\r
+                          &&  DFWORD(df, 1)==0                     \\r
+                          && (DFWORD(df, 0)&0x1c003fff)==0         \\r
+                          && (DFWORD(df, 0)&0x60000000)!=0x60000000))\r
+      #define DFISINT(df) ((DFWORD(df, 0)&0x63ffc000)==0x22080000  \\r
+                         ||(DFWORD(df, 0)&0x7bffc000)==0x6a080000)\r
+      #define DFISUINT01(df) ((DFWORD(df, 0)&0xfbffc000)==0x22080000)\r
+      #define DFISCCZERO(df) (DFWORD(df, 3)==0                     \\r
+                          &&  DFWORD(df, 2)==0                     \\r
+                          &&  DFWORD(df, 1)==0                     \\r
+                          && (DFWORD(df, 0)&0x00003fff)==0)\r
+\r
+      #define DFISCC01(df)   ((DFWORD(df, 0)&~0xffffc912)==0       \\r
+                          &&  (DFWORD(df, 1)&~0x44912449)==0       \\r
+                          &&  (DFWORD(df, 2)&~0x12449124)==0       \\r
+                          &&  (DFWORD(df, 3)&~0x49124491)==0)\r
+    #endif\r
+\r
+    /* Macros to test if a certain 10 bits of a uInt or pair of uInts */\r
+    /* are a canonical declet [higher or lower bits are ignored].     */\r
+    /* declet is at offset 0 (from the right) in a uInt:              */\r
+    #define CANONDPD(dpd) (((dpd)&0x300)==0 || ((dpd)&0x6e)!=0x6e)\r
+    /* declet is at offset k (a multiple of 2) in a uInt:             */\r
+    #define CANONDPDOFF(dpd, k) (((dpd)&(0x300<<(k)))==0            \\r
+      || ((dpd)&(((uInt)0x6e)<<(k)))!=(((uInt)0x6e)<<(k)))\r
+    /* declet is at offset k (a multiple of 2) in a pair of uInts:    */\r
+    /* [the top 2 bits will always be in the more-significant uInt]   */\r
+    #define CANONDPDTWO(hi, lo, k) (((hi)&(0x300>>(32-(k))))==0     \\r
+      || ((hi)&(0x6e>>(32-(k))))!=(0x6e>>(32-(k)))                  \\r
+      || ((lo)&(((uInt)0x6e)<<(k)))!=(((uInt)0x6e)<<(k)))\r
+\r
+    /* Macro to test whether a full-length (length DECPMAX) BCD8      */\r
+    /* coefficient, starting at uByte u, is all zeros                 */\r
+    /* Test just the LSWord first, then the remainder as a sequence   */\r
+    /* of tests in order to avoid same-level use of UBTOUI            */\r
+    #if DECPMAX==7\r
+      #define ISCOEFFZERO(u) (                                      \\r
+           UBTOUI((u)+DECPMAX-4)==0                                 \\r
+        && UBTOUS((u)+DECPMAX-6)==0                                 \\r
+        && *(u)==0)\r
+    #elif DECPMAX==16\r
+      #define ISCOEFFZERO(u) (                                      \\r
+           UBTOUI((u)+DECPMAX-4)==0                                 \\r
+        && UBTOUI((u)+DECPMAX-8)==0                                 \\r
+        && UBTOUI((u)+DECPMAX-12)==0                                \\r
+        && UBTOUI(u)==0)\r
+    #elif DECPMAX==34\r
+      #define ISCOEFFZERO(u) (                                      \\r
+           UBTOUI((u)+DECPMAX-4)==0                                 \\r
+        && UBTOUI((u)+DECPMAX-8)==0                                 \\r
+        && UBTOUI((u)+DECPMAX-12)==0                                \\r
+        && UBTOUI((u)+DECPMAX-16)==0                                \\r
+        && UBTOUI((u)+DECPMAX-20)==0                                \\r
+        && UBTOUI((u)+DECPMAX-24)==0                                \\r
+        && UBTOUI((u)+DECPMAX-28)==0                                \\r
+        && UBTOUI((u)+DECPMAX-32)==0                                \\r
+        && UBTOUS(u)==0)\r
+    #endif\r
+\r
+    /* Macros and masks for the sign, exponent continuation, and MSD  */\r
+    /* Get the sign as DECFLOAT_Sign or 0                             */\r
+    #define GETSIGN(df) (DFWORD(df, 0)&0x80000000)\r
+    /* Get the exponent continuation from a decFloat *df as an Int    */\r
+    #define GETECON(df) ((Int)((DFWORD((df), 0)&0x03ffffff)>>(32-6-DECECONL)))\r
+    /* Ditto, from the next-wider format                              */\r
+    #define GETWECON(df) ((Int)((DFWWORD((df), 0)&0x03ffffff)>>(32-6-DECWECONL)))\r
+    /* Get the biased exponent similarly                              */\r
+    #define GETEXP(df)  ((Int)(DECCOMBEXP[DFWORD((df), 0)>>26]+GETECON(df)))\r
+    /* Get the unbiased exponent similarly                            */\r
+    #define GETEXPUN(df) ((Int)GETEXP(df)-DECBIAS)\r
+    /* Get the MSD similarly (as uInt)                                */\r
+    #define GETMSD(df)   (DECCOMBMSD[DFWORD((df), 0)>>26])\r
+\r
+    /* Compile-time computes of the exponent continuation field masks */\r
+    /* full exponent continuation field:                              */\r
+    #define ECONMASK ((0x03ffffff>>(32-6-DECECONL))<<(32-6-DECECONL))\r
+    /* same, not including its first digit (the qNaN/sNaN selector):  */\r
+    #define ECONNANMASK ((0x01ffffff>>(32-6-DECECONL))<<(32-6-DECECONL))\r
+\r
+    /* Macros to decode the coefficient in a finite decFloat *df into */\r
+    /* a BCD string (uByte *bcdin) of length DECPMAX uBytes.          */\r
+\r
+    /* In-line sequence to convert least significant 10 bits of uInt  */\r
+    /* dpd to three BCD8 digits starting at uByte u.  Note that an    */\r
+    /* extra byte is written to the right of the three digits because */\r
+    /* four bytes are moved at a time for speed; the alternative      */\r
+    /* macro moves exactly three bytes (usually slower).              */\r
+    #define dpd2bcd8(u, dpd)  memcpy(u, &DPD2BCD8[((dpd)&0x3ff)*4], 4)\r
+    #define dpd2bcd83(u, dpd) memcpy(u, &DPD2BCD8[((dpd)&0x3ff)*4], 3)\r
+\r
+    /* Decode the declets.  After extracting each one, it is decoded  */\r
+    /* to BCD8 using a table lookup (also used for variable-length    */\r
+    /* decode).  Each DPD decode is 3 bytes BCD8 plus a one-byte      */\r
+    /* length which is not used, here).  Fixed-length 4-byte moves    */\r
+    /* are fast, however, almost everywhere, and so are used except   */\r
+    /* for the final three bytes (to avoid overrun).  The code below  */\r
+    /* is 36 instructions for Doubles and about 70 for Quads, even    */\r
+    /* on IA32.                                                       */\r
+\r
+    /* Two macros are defined for each format:                        */\r
+    /*   GETCOEFF extracts the coefficient of the current format      */\r
+    /*   GETWCOEFF extracts the coefficient of the next-wider format. */\r
+    /* The latter is a copy of the next-wider GETCOEFF using DFWWORD. */\r
+\r
+    #if DECPMAX==7\r
+    #define GETCOEFF(df, bcd) {                          \\r
+      uInt sourhi=DFWORD(df, 0);                         \\r
+      *(bcd)=(uByte)DECCOMBMSD[sourhi>>26];              \\r
+      dpd2bcd8(bcd+1, sourhi>>10);                       \\r
+      dpd2bcd83(bcd+4, sourhi);}\r
+    #define GETWCOEFF(df, bcd) {                         \\r
+      uInt sourhi=DFWWORD(df, 0);                        \\r
+      uInt sourlo=DFWWORD(df, 1);                        \\r
+      *(bcd)=(uByte)DECCOMBMSD[sourhi>>26];              \\r
+      dpd2bcd8(bcd+1, sourhi>>8);                        \\r
+      dpd2bcd8(bcd+4, (sourhi<<2) | (sourlo>>30));       \\r
+      dpd2bcd8(bcd+7, sourlo>>20);                       \\r
+      dpd2bcd8(bcd+10, sourlo>>10);                      \\r
+      dpd2bcd83(bcd+13, sourlo);}\r
+\r
+    #elif DECPMAX==16\r
+    #define GETCOEFF(df, bcd) {                          \\r
+      uInt sourhi=DFWORD(df, 0);                         \\r
+      uInt sourlo=DFWORD(df, 1);                         \\r
+      *(bcd)=(uByte)DECCOMBMSD[sourhi>>26];              \\r
+      dpd2bcd8(bcd+1, sourhi>>8);                        \\r
+      dpd2bcd8(bcd+4, (sourhi<<2) | (sourlo>>30));       \\r
+      dpd2bcd8(bcd+7, sourlo>>20);                       \\r
+      dpd2bcd8(bcd+10, sourlo>>10);                      \\r
+      dpd2bcd83(bcd+13, sourlo);}\r
+    #define GETWCOEFF(df, bcd) {                         \\r
+      uInt sourhi=DFWWORD(df, 0);                        \\r
+      uInt sourmh=DFWWORD(df, 1);                        \\r
+      uInt sourml=DFWWORD(df, 2);                        \\r
+      uInt sourlo=DFWWORD(df, 3);                        \\r
+      *(bcd)=(uByte)DECCOMBMSD[sourhi>>26];              \\r
+      dpd2bcd8(bcd+1, sourhi>>4);                        \\r
+      dpd2bcd8(bcd+4, ((sourhi)<<6) | (sourmh>>26));     \\r
+      dpd2bcd8(bcd+7, sourmh>>16);                       \\r
+      dpd2bcd8(bcd+10, sourmh>>6);                       \\r
+      dpd2bcd8(bcd+13, ((sourmh)<<4) | (sourml>>28));    \\r
+      dpd2bcd8(bcd+16, sourml>>18);                      \\r
+      dpd2bcd8(bcd+19, sourml>>8);                       \\r
+      dpd2bcd8(bcd+22, ((sourml)<<2) | (sourlo>>30));    \\r
+      dpd2bcd8(bcd+25, sourlo>>20);                      \\r
+      dpd2bcd8(bcd+28, sourlo>>10);                      \\r
+      dpd2bcd83(bcd+31, sourlo);}\r
+\r
+    #elif DECPMAX==34\r
+    #define GETCOEFF(df, bcd) {                          \\r
+      uInt sourhi=DFWORD(df, 0);                         \\r
+      uInt sourmh=DFWORD(df, 1);                         \\r
+      uInt sourml=DFWORD(df, 2);                         \\r
+      uInt sourlo=DFWORD(df, 3);                         \\r
+      *(bcd)=(uByte)DECCOMBMSD[sourhi>>26];              \\r
+      dpd2bcd8(bcd+1, sourhi>>4);                        \\r
+      dpd2bcd8(bcd+4, ((sourhi)<<6) | (sourmh>>26));     \\r
+      dpd2bcd8(bcd+7, sourmh>>16);                       \\r
+      dpd2bcd8(bcd+10, sourmh>>6);                       \\r
+      dpd2bcd8(bcd+13, ((sourmh)<<4) | (sourml>>28));    \\r
+      dpd2bcd8(bcd+16, sourml>>18);                      \\r
+      dpd2bcd8(bcd+19, sourml>>8);                       \\r
+      dpd2bcd8(bcd+22, ((sourml)<<2) | (sourlo>>30));    \\r
+      dpd2bcd8(bcd+25, sourlo>>20);                      \\r
+      dpd2bcd8(bcd+28, sourlo>>10);                      \\r
+      dpd2bcd83(bcd+31, sourlo);}\r
+\r
+      #define GETWCOEFF(df, bcd) {??} /* [should never be used]       */\r
+    #endif\r
+\r
+    /* Macros to decode the coefficient in a finite decFloat *df into */\r
+    /* a base-billion uInt array, with the least-significant          */\r
+    /* 0-999999999 'digit' at offset 0.                               */\r
+\r
+    /* Decode the declets.  After extracting each one, it is decoded  */\r
+    /* to binary using a table lookup.  Three tables are used; one    */\r
+    /* the usual DPD to binary, the other two pre-multiplied by 1000  */\r
+    /* and 1000000 to avoid multiplication during decode.  These      */\r
+    /* tables can also be used for multiplying up the MSD as the DPD  */\r
+    /* code for 0 through 9 is the identity.                          */\r
+    #define DPD2BIN0 DPD2BIN         /* for prettier code             */\r
+\r
+    #if DECPMAX==7\r
+    #define GETCOEFFBILL(df, buf) {                           \\r
+      uInt sourhi=DFWORD(df, 0);                              \\r
+      (buf)[0]=DPD2BIN0[sourhi&0x3ff]                         \\r
+              +DPD2BINK[(sourhi>>10)&0x3ff]                   \\r
+              +DPD2BINM[DECCOMBMSD[sourhi>>26]];}\r
+\r
+    #elif DECPMAX==16\r
+    #define GETCOEFFBILL(df, buf) {                           \\r
+      uInt sourhi, sourlo;                                    \\r
+      sourlo=DFWORD(df, 1);                                   \\r
+      (buf)[0]=DPD2BIN0[sourlo&0x3ff]                         \\r
+              +DPD2BINK[(sourlo>>10)&0x3ff]                   \\r
+              +DPD2BINM[(sourlo>>20)&0x3ff];                  \\r
+      sourhi=DFWORD(df, 0);                                   \\r
+      (buf)[1]=DPD2BIN0[((sourhi<<2) | (sourlo>>30))&0x3ff]   \\r
+              +DPD2BINK[(sourhi>>8)&0x3ff]                    \\r
+              +DPD2BINM[DECCOMBMSD[sourhi>>26]];}\r
+\r
+    #elif DECPMAX==34\r
+    #define GETCOEFFBILL(df, buf) {                           \\r
+      uInt sourhi, sourmh, sourml, sourlo;                    \\r
+      sourlo=DFWORD(df, 3);                                   \\r
+      (buf)[0]=DPD2BIN0[sourlo&0x3ff]                         \\r
+              +DPD2BINK[(sourlo>>10)&0x3ff]                   \\r
+              +DPD2BINM[(sourlo>>20)&0x3ff];                  \\r
+      sourml=DFWORD(df, 2);                                   \\r
+      (buf)[1]=DPD2BIN0[((sourml<<2) | (sourlo>>30))&0x3ff]   \\r
+              +DPD2BINK[(sourml>>8)&0x3ff]                    \\r
+              +DPD2BINM[(sourml>>18)&0x3ff];                  \\r
+      sourmh=DFWORD(df, 1);                                   \\r
+      (buf)[2]=DPD2BIN0[((sourmh<<4) | (sourml>>28))&0x3ff]   \\r
+              +DPD2BINK[(sourmh>>6)&0x3ff]                    \\r
+              +DPD2BINM[(sourmh>>16)&0x3ff];                  \\r
+      sourhi=DFWORD(df, 0);                                   \\r
+      (buf)[3]=DPD2BIN0[((sourhi<<6) | (sourmh>>26))&0x3ff]   \\r
+              +DPD2BINK[(sourhi>>4)&0x3ff]                    \\r
+              +DPD2BINM[DECCOMBMSD[sourhi>>26]];}\r
+\r
+    #endif\r
+\r
+    /* Macros to decode the coefficient in a finite decFloat *df into */\r
+    /* a base-thousand uInt array (of size DECLETS+1, to allow for    */\r
+    /* the MSD), with the least-significant 0-999 'digit' at offset 0.*/\r
+\r
+    /* Decode the declets.  After extracting each one, it is decoded  */\r
+    /* to binary using a table lookup.                                */\r
+    #if DECPMAX==7\r
+    #define GETCOEFFTHOU(df, buf) {                           \\r
+      uInt sourhi=DFWORD(df, 0);                              \\r
+      (buf)[0]=DPD2BIN[sourhi&0x3ff];                         \\r
+      (buf)[1]=DPD2BIN[(sourhi>>10)&0x3ff];                   \\r
+      (buf)[2]=DECCOMBMSD[sourhi>>26];}\r
+\r
+    #elif DECPMAX==16\r
+    #define GETCOEFFTHOU(df, buf) {                           \\r
+      uInt sourhi, sourlo;                                    \\r
+      sourlo=DFWORD(df, 1);                                   \\r
+      (buf)[0]=DPD2BIN[sourlo&0x3ff];                         \\r
+      (buf)[1]=DPD2BIN[(sourlo>>10)&0x3ff];                   \\r
+      (buf)[2]=DPD2BIN[(sourlo>>20)&0x3ff];                   \\r
+      sourhi=DFWORD(df, 0);                                   \\r
+      (buf)[3]=DPD2BIN[((sourhi<<2) | (sourlo>>30))&0x3ff];   \\r
+      (buf)[4]=DPD2BIN[(sourhi>>8)&0x3ff];                    \\r
+      (buf)[5]=DECCOMBMSD[sourhi>>26];}\r
+\r
+    #elif DECPMAX==34\r
+    #define GETCOEFFTHOU(df, buf) {                           \\r
+      uInt sourhi, sourmh, sourml, sourlo;                    \\r
+      sourlo=DFWORD(df, 3);                                   \\r
+      (buf)[0]=DPD2BIN[sourlo&0x3ff];                         \\r
+      (buf)[1]=DPD2BIN[(sourlo>>10)&0x3ff];                   \\r
+      (buf)[2]=DPD2BIN[(sourlo>>20)&0x3ff];                   \\r
+      sourml=DFWORD(df, 2);                                   \\r
+      (buf)[3]=DPD2BIN[((sourml<<2) | (sourlo>>30))&0x3ff];   \\r
+      (buf)[4]=DPD2BIN[(sourml>>8)&0x3ff];                    \\r
+      (buf)[5]=DPD2BIN[(sourml>>18)&0x3ff];                   \\r
+      sourmh=DFWORD(df, 1);                                   \\r
+      (buf)[6]=DPD2BIN[((sourmh<<4) | (sourml>>28))&0x3ff];   \\r
+      (buf)[7]=DPD2BIN[(sourmh>>6)&0x3ff];                    \\r
+      (buf)[8]=DPD2BIN[(sourmh>>16)&0x3ff];                   \\r
+      sourhi=DFWORD(df, 0);                                   \\r
+      (buf)[9]=DPD2BIN[((sourhi<<6) | (sourmh>>26))&0x3ff];   \\r
+      (buf)[10]=DPD2BIN[(sourhi>>4)&0x3ff];                   \\r
+      (buf)[11]=DECCOMBMSD[sourhi>>26];}\r
+    #endif\r
+\r
+\r
+    /* Macros to decode the coefficient in a finite decFloat *df and  */\r
+    /* add to a base-thousand uInt array (as for GETCOEFFTHOU).       */\r
+    /* After the addition then most significant 'digit' in the array  */\r
+    /* might have a value larger then 10 (with a maximum of 19).      */\r
+    #if DECPMAX==7\r
+    #define ADDCOEFFTHOU(df, buf) {                           \\r
+      uInt sourhi=DFWORD(df, 0);                              \\r
+      (buf)[0]+=DPD2BIN[sourhi&0x3ff];                        \\r
+      if (buf[0]>999) {buf[0]-=1000; buf[1]++;}               \\r
+      (buf)[1]+=DPD2BIN[(sourhi>>10)&0x3ff];                  \\r
+      if (buf[1]>999) {buf[1]-=1000; buf[2]++;}               \\r
+      (buf)[2]+=DECCOMBMSD[sourhi>>26];}\r
+\r
+    #elif DECPMAX==16\r
+    #define ADDCOEFFTHOU(df, buf) {                           \\r
+      uInt sourhi, sourlo;                                    \\r
+      sourlo=DFWORD(df, 1);                                   \\r
+      (buf)[0]+=DPD2BIN[sourlo&0x3ff];                        \\r
+      if (buf[0]>999) {buf[0]-=1000; buf[1]++;}               \\r
+      (buf)[1]+=DPD2BIN[(sourlo>>10)&0x3ff];                  \\r
+      if (buf[1]>999) {buf[1]-=1000; buf[2]++;}               \\r
+      (buf)[2]+=DPD2BIN[(sourlo>>20)&0x3ff];                  \\r
+      if (buf[2]>999) {buf[2]-=1000; buf[3]++;}               \\r
+      sourhi=DFWORD(df, 0);                                   \\r
+      (buf)[3]+=DPD2BIN[((sourhi<<2) | (sourlo>>30))&0x3ff];  \\r
+      if (buf[3]>999) {buf[3]-=1000; buf[4]++;}               \\r
+      (buf)[4]+=DPD2BIN[(sourhi>>8)&0x3ff];                   \\r
+      if (buf[4]>999) {buf[4]-=1000; buf[5]++;}               \\r
+      (buf)[5]+=DECCOMBMSD[sourhi>>26];}\r
+\r
+    #elif DECPMAX==34\r
+    #define ADDCOEFFTHOU(df, buf) {                           \\r
+      uInt sourhi, sourmh, sourml, sourlo;                    \\r
+      sourlo=DFWORD(df, 3);                                   \\r
+      (buf)[0]+=DPD2BIN[sourlo&0x3ff];                        \\r
+      if (buf[0]>999) {buf[0]-=1000; buf[1]++;}               \\r
+      (buf)[1]+=DPD2BIN[(sourlo>>10)&0x3ff];                  \\r
+      if (buf[1]>999) {buf[1]-=1000; buf[2]++;}               \\r
+      (buf)[2]+=DPD2BIN[(sourlo>>20)&0x3ff];                  \\r
+      if (buf[2]>999) {buf[2]-=1000; buf[3]++;}               \\r
+      sourml=DFWORD(df, 2);                                   \\r
+      (buf)[3]+=DPD2BIN[((sourml<<2) | (sourlo>>30))&0x3ff];  \\r
+      if (buf[3]>999) {buf[3]-=1000; buf[4]++;}               \\r
+      (buf)[4]+=DPD2BIN[(sourml>>8)&0x3ff];                   \\r
+      if (buf[4]>999) {buf[4]-=1000; buf[5]++;}               \\r
+      (buf)[5]+=DPD2BIN[(sourml>>18)&0x3ff];                  \\r
+      if (buf[5]>999) {buf[5]-=1000; buf[6]++;}               \\r
+      sourmh=DFWORD(df, 1);                                   \\r
+      (buf)[6]+=DPD2BIN[((sourmh<<4) | (sourml>>28))&0x3ff];  \\r
+      if (buf[6]>999) {buf[6]-=1000; buf[7]++;}               \\r
+      (buf)[7]+=DPD2BIN[(sourmh>>6)&0x3ff];                   \\r
+      if (buf[7]>999) {buf[7]-=1000; buf[8]++;}               \\r
+      (buf)[8]+=DPD2BIN[(sourmh>>16)&0x3ff];                  \\r
+      if (buf[8]>999) {buf[8]-=1000; buf[9]++;}               \\r
+      sourhi=DFWORD(df, 0);                                   \\r
+      (buf)[9]+=DPD2BIN[((sourhi<<6) | (sourmh>>26))&0x3ff];  \\r
+      if (buf[9]>999) {buf[9]-=1000; buf[10]++;}              \\r
+      (buf)[10]+=DPD2BIN[(sourhi>>4)&0x3ff];                  \\r
+      if (buf[10]>999) {buf[10]-=1000; buf[11]++;}            \\r
+      (buf)[11]+=DECCOMBMSD[sourhi>>26];}\r
+    #endif\r
+\r
+\r
+    /* Set a decFloat to the maximum positive finite number (Nmax)    */\r
+    #if DECPMAX==7\r
+    #define DFSETNMAX(df)            \\r
+      {DFWORD(df, 0)=0x77f3fcff;}\r
+    #elif DECPMAX==16\r
+    #define DFSETNMAX(df)            \\r
+      {DFWORD(df, 0)=0x77fcff3f;     \\r
+       DFWORD(df, 1)=0xcff3fcff;}\r
+    #elif DECPMAX==34\r
+    #define DFSETNMAX(df)            \\r
+      {DFWORD(df, 0)=0x77ffcff3;     \\r
+       DFWORD(df, 1)=0xfcff3fcf;     \\r
+       DFWORD(df, 2)=0xf3fcff3f;     \\r
+       DFWORD(df, 3)=0xcff3fcff;}\r
+    #endif\r
+\r
+  /* [end of format-dependent macros and constants]                   */\r
+  #endif\r
+\r
+#else\r
+  #error decNumberLocal included more than once\r
+#endif\r
diff --git a/src/decNumber/decPacked.c b/src/decNumber/decPacked.c
new file mode 100644 (file)
index 0000000..9881139
--- /dev/null
@@ -0,0 +1,220 @@
+/* ------------------------------------------------------------------ */\r
+/* Packed Decimal conversion module                                   */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2002.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises the routines for Packed Decimal format       */\r
+/* numbers.  Conversions are supplied to and from decNumber, which in */\r
+/* turn supports:                                                     */\r
+/*   conversions to and from string                                   */\r
+/*   arithmetic routines                                              */\r
+/*   utilities.                                                       */\r
+/* Conversions from decNumber to and from densely packed decimal      */\r
+/* formats are provided by the decimal32 through decimal128 modules.  */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#include <string.h>           // for NULL\r
+#include "decNumber.h"        // base number library\r
+#include "decPacked.h"        // packed decimal\r
+#include "decNumberLocal.h"   // decNumber local types, etc.\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decPackedFromNumber -- convert decNumber to BCD Packed Decimal     */\r
+/*                                                                    */\r
+/*   bcd    is the BCD bytes                                          */\r
+/*   length is the length of the BCD array                            */\r
+/*   scale  is the scale result                                       */\r
+/*   dn     is the decNumber                                          */\r
+/*   returns bcd, or NULL if error                                    */\r
+/*                                                                    */\r
+/* The number is converted to a BCD packed decimal byte array,        */\r
+/* right aligned in the bcd array, whose length is indicated by the   */\r
+/* second parameter.  The final 4-bit nibble in the array will be a   */\r
+/* sign nibble, C (1100) for + and D (1101) for -.  Unused bytes and  */\r
+/* nibbles to the left of the number are set to 0.                    */\r
+/*                                                                    */\r
+/* scale is set to the scale of the number (this is the exponent,     */\r
+/* negated).  To force the number to a specified scale, first use the */\r
+/* decNumberRescale routine, which will round and change the exponent */\r
+/* as necessary.                                                      */\r
+/*                                                                    */\r
+/* If there is an error (that is, the decNumber has too many digits   */\r
+/* to fit in length bytes, or it is a NaN or Infinity), NULL is       */\r
+/* returned and the bcd and scale results are unchanged.  Otherwise   */\r
+/* bcd is returned.                                                   */\r
+/* ------------------------------------------------------------------ */\r
+uByte * decPackedFromNumber(uByte *bcd, Int length, Int *scale,\r
+                            const decNumber *dn) {\r
+  const Unit *up=dn->lsu;     // Unit array pointer\r
+  uByte obyte, *out;          // current output byte, and where it goes\r
+  Int indigs=dn->digits;      // digits processed\r
+  uInt cut=DECDPUN;           // downcounter per Unit\r
+  uInt u=*up;                 // work\r
+  uInt nib;                   // ..\r
+  #if DECDPUN<=4\r
+  uInt temp;                  // ..\r
+  #endif\r
+\r
+  if (dn->digits>length*2-1                  // too long ..\r
+   ||(dn->bits & DECSPECIAL)) return NULL;   // .. or special -- hopeless\r
+\r
+  if (dn->bits&DECNEG) obyte=DECPMINUS;      // set the sign ..\r
+   else                obyte=DECPPLUS;\r
+  *scale=-dn->exponent;                      // .. and scale\r
+\r
+  // loop from lowest (rightmost) byte\r
+  out=bcd+length-1;                          // -> final byte\r
+  for (; out>=bcd; out--) {\r
+    if (indigs>0) {\r
+      if (cut==0) {\r
+        up++;\r
+        u=*up;\r
+        cut=DECDPUN;\r
+        }\r
+      #if DECDPUN<=4\r
+        temp=(u*6554)>>16;         // fast /10\r
+        nib=u-X10(temp);\r
+        u=temp;\r
+      #else\r
+        nib=u%10;                  // cannot use *6554 trick :-(\r
+        u=u/10;\r
+      #endif\r
+      obyte|=(nib<<4);\r
+      indigs--;\r
+      cut--;\r
+      }\r
+    *out=obyte;\r
+    obyte=0;                       // assume 0\r
+    if (indigs>0) {\r
+      if (cut==0) {\r
+        up++;\r
+        u=*up;\r
+        cut=DECDPUN;\r
+        }\r
+      #if DECDPUN<=4\r
+        temp=(u*6554)>>16;         // as above\r
+        obyte=(uByte)(u-X10(temp));\r
+        u=temp;\r
+      #else\r
+        obyte=(uByte)(u%10);\r
+        u=u/10;\r
+      #endif\r
+      indigs--;\r
+      cut--;\r
+      }\r
+    } // loop\r
+\r
+  return bcd;\r
+  } // decPackedFromNumber\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decPackedToNumber -- convert BCD Packed Decimal to a decNumber     */\r
+/*                                                                    */\r
+/*   bcd    is the BCD bytes                                          */\r
+/*   length is the length of the BCD array                            */\r
+/*   scale  is the scale associated with the BCD integer              */\r
+/*   dn     is the decNumber [with space for length*2 digits]         */\r
+/*   returns dn, or NULL if error                                     */\r
+/*                                                                    */\r
+/* The BCD packed decimal byte array, together with an associated     */\r
+/* scale, is converted to a decNumber.  The BCD array is assumed full */\r
+/* of digits, and must be ended by a 4-bit sign nibble in the least   */\r
+/* significant four bits of the final byte.                           */\r
+/*                                                                    */\r
+/* The scale is used (negated) as the exponent of the decNumber.      */\r
+/* Note that zeros may have a sign and/or a scale.                    */\r
+/*                                                                    */\r
+/* The decNumber structure is assumed to have sufficient space to     */\r
+/* hold the converted number (that is, up to length*2-1 digits), so   */\r
+/* no error is possible unless the adjusted exponent is out of range, */\r
+/* no sign nibble was found, or a sign nibble was found before the    */\r
+/* final nibble.  In these error cases, NULL is returned and the      */\r
+/* decNumber will be 0.                                               */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decPackedToNumber(const uByte *bcd, Int length,\r
+                              const Int *scale, decNumber *dn) {\r
+  const uByte *last=bcd+length-1;  // -> last byte\r
+  const uByte *first;              // -> first non-zero byte\r
+  uInt  nib;                       // work nibble\r
+  Unit  *up=dn->lsu;               // output pointer\r
+  Int   digits;                    // digits count\r
+  Int   cut=0;                     // phase of output\r
+\r
+  decNumberZero(dn);               // default result\r
+  last=&bcd[length-1];\r
+  nib=*last & 0x0f;                // get the sign\r
+  if (nib==DECPMINUS || nib==DECPMINUSALT) dn->bits=DECNEG;\r
+   else if (nib<=9) return NULL;   // not a sign nibble\r
+\r
+  // skip leading zero bytes [final byte is always non-zero, due to sign]\r
+  for (first=bcd; *first==0;) first++;\r
+  digits=(last-first)*2+1;              // calculate digits ..\r
+  if ((*first & 0xf0)==0) digits--;     // adjust for leading zero nibble\r
+  if (digits!=0) dn->digits=digits;     // count of actual digits [if 0,\r
+                                        // leave as 1]\r
+\r
+  // check the adjusted exponent; note that scale could be unbounded\r
+  dn->exponent=-*scale;                 // set the exponent\r
+  if (*scale>=0) {                      // usual case\r
+    if ((dn->digits-*scale-1)<-DECNUMMAXE) {      // underflow\r
+      decNumberZero(dn);\r
+      return NULL;}\r
+    }\r
+   else { // -ve scale; +ve exponent\r
+    // need to be careful to avoid wrap, here, also BADINT case\r
+    if ((*scale<-DECNUMMAXE)            // overflow even without digits\r
+         || ((dn->digits-*scale-1)>DECNUMMAXE)) { // overflow\r
+      decNumberZero(dn);\r
+      return NULL;}\r
+    }\r
+  if (digits==0) return dn;             // result was zero\r
+\r
+  // copy the digits to the number's units, starting at the lsu\r
+  // [unrolled]\r
+  for (;;) {                            // forever\r
+    // left nibble first\r
+    nib=(unsigned)(*last & 0xf0)>>4;\r
+    // got a digit, in nib\r
+    if (nib>9) {decNumberZero(dn); return NULL;}\r
+\r
+    if (cut==0) *up=(Unit)nib;\r
+     else *up=(Unit)(*up+nib*DECPOWERS[cut]);\r
+    digits--;\r
+    if (digits==0) break;               // got them all\r
+    cut++;\r
+    if (cut==DECDPUN) {\r
+      up++;\r
+      cut=0;\r
+      }\r
+    last--;                             // ready for next\r
+    nib=*last & 0x0f;                   // get right nibble\r
+    if (nib>9) {decNumberZero(dn); return NULL;}\r
+\r
+    // got a digit, in nib\r
+    if (cut==0) *up=(Unit)nib;\r
+     else *up=(Unit)(*up+nib*DECPOWERS[cut]);\r
+    digits--;\r
+    if (digits==0) break;               // got them all\r
+    cut++;\r
+    if (cut==DECDPUN) {\r
+      up++;\r
+      cut=0;\r
+      }\r
+    } // forever\r
+\r
+  return dn;\r
+  } // decPackedToNumber\r
+\r
diff --git a/src/decNumber/decPacked.h b/src/decNumber/decPacked.h
new file mode 100644 (file)
index 0000000..320d53f
--- /dev/null
@@ -0,0 +1,52 @@
+/* ------------------------------------------------------------------ */\r
+/* Packed Decimal conversion module header                            */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2005.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#if !defined(DECPACKED)\r
+  #define DECPACKED\r
+  #define DECPNAME     "decPacked"                      /* Short name */\r
+  #define DECPFULLNAME "Packed Decimal conversions"   /* Verbose name */\r
+  #define DECPAUTHOR   "Mike Cowlishaw"               /* Who to blame */\r
+\r
+  #define DECPACKED_DefP 32             /* default precision          */\r
+\r
+  #ifndef  DECNUMDIGITS\r
+    #define DECNUMDIGITS DECPACKED_DefP /* size if not already defined*/\r
+  #endif\r
+  #include "decNumber.h"                /* context and number library */\r
+\r
+  /* Sign nibble constants                                            */\r
+  #if !defined(DECPPLUSALT)\r
+    #define DECPPLUSALT  0x0A /* alternate plus  nibble               */\r
+    #define DECPMINUSALT 0x0B /* alternate minus nibble               */\r
+    #define DECPPLUS     0x0C /* preferred plus  nibble               */\r
+    #define DECPMINUS    0x0D /* preferred minus nibble               */\r
+    #define DECPPLUSALT2 0x0E /* alternate plus  nibble               */\r
+    #define DECPUNSIGNED 0x0F /* alternate plus  nibble (unsigned)    */\r
+  #endif\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* decPacked public routines                                        */\r
+  /* ---------------------------------------------------------------- */\r
+  /* Conversions                                                      */\r
+  uint8_t * decPackedFromNumber(uint8_t *, int32_t, int32_t *,\r
+                                const decNumber *);\r
+  decNumber * decPackedToNumber(const uint8_t *, int32_t, const int32_t *,\r
+                                decNumber *);\r
+\r
+#endif\r
diff --git a/src/decNumber/decQuad.c b/src/decNumber/decQuad.c
new file mode 100644 (file)
index 0000000..ba0fd0a
--- /dev/null
@@ -0,0 +1,135 @@
+/* ------------------------------------------------------------------ */\r
+/* decQuad.c -- decQuad operations module                             */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2010.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is included in the package as decNumber.pdf.  This   */\r
+/* document is also available in HTML, together with specifications,  */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises decQuad operations (including conversions)   */\r
+/* ------------------------------------------------------------------ */\r
+\r
+\r
+/* Constant mappings for shared code */\r
+#define DECPMAX     DECQUAD_Pmax\r
+#define DECEMIN     DECQUAD_Emin\r
+#define DECEMAX     DECQUAD_Emax\r
+#define DECEMAXD    DECQUAD_EmaxD\r
+#define DECBYTES    DECQUAD_Bytes\r
+#define DECSTRING   DECQUAD_String\r
+#define DECECONL    DECQUAD_EconL\r
+#define DECBIAS     DECQUAD_Bias\r
+#define DECLETS     DECQUAD_Declets\r
+#define DECQTINY   (-DECQUAD_Bias)\r
+\r
+/* Type and function mappings for shared code */\r
+#define decFloat                   decQuad        // Type name\r
+\r
+// Utilities and conversions (binary results, extractors, etc.)\r
+#define decFloatFromBCD            decQuadFromBCD\r
+#define decFloatFromInt32          decQuadFromInt32\r
+#define decFloatFromPacked         decQuadFromPacked\r
+#define decFloatFromPackedChecked  decQuadFromPackedChecked\r
+#define decFloatFromString         decQuadFromString\r
+#define decFloatFromUInt32         decQuadFromUInt32\r
+#define decFloatFromWider          decQuadFromWider\r
+#define decFloatGetCoefficient     decQuadGetCoefficient\r
+#define decFloatGetExponent        decQuadGetExponent\r
+#define decFloatSetCoefficient     decQuadSetCoefficient\r
+#define decFloatSetExponent        decQuadSetExponent\r
+#define decFloatShow               decQuadShow\r
+#define decFloatToBCD              decQuadToBCD\r
+#define decFloatToEngString        decQuadToEngString\r
+#define decFloatToInt32            decQuadToInt32\r
+#define decFloatToInt32Exact       decQuadToInt32Exact\r
+#define decFloatToPacked           decQuadToPacked\r
+#define decFloatToString           decQuadToString\r
+#define decFloatToUInt32           decQuadToUInt32\r
+#define decFloatToUInt32Exact      decQuadToUInt32Exact\r
+#define decFloatToWider            decQuadToWider\r
+#define decFloatZero               decQuadZero\r
+\r
+// Computational (result is a decFloat)\r
+#define decFloatAbs                decQuadAbs\r
+#define decFloatAdd                decQuadAdd\r
+#define decFloatAnd                decQuadAnd\r
+#define decFloatDivide             decQuadDivide\r
+#define decFloatDivideInteger      decQuadDivideInteger\r
+#define decFloatFMA                decQuadFMA\r
+#define decFloatInvert             decQuadInvert\r
+#define decFloatLogB               decQuadLogB\r
+#define decFloatMax                decQuadMax\r
+#define decFloatMaxMag             decQuadMaxMag\r
+#define decFloatMin                decQuadMin\r
+#define decFloatMinMag             decQuadMinMag\r
+#define decFloatMinus              decQuadMinus\r
+#define decFloatMultiply           decQuadMultiply\r
+#define decFloatNextMinus          decQuadNextMinus\r
+#define decFloatNextPlus           decQuadNextPlus\r
+#define decFloatNextToward         decQuadNextToward\r
+#define decFloatOr                 decQuadOr\r
+#define decFloatPlus               decQuadPlus\r
+#define decFloatQuantize           decQuadQuantize\r
+#define decFloatReduce             decQuadReduce\r
+#define decFloatRemainder          decQuadRemainder\r
+#define decFloatRemainderNear      decQuadRemainderNear\r
+#define decFloatRotate             decQuadRotate\r
+#define decFloatScaleB             decQuadScaleB\r
+#define decFloatShift              decQuadShift\r
+#define decFloatSubtract           decQuadSubtract\r
+#define decFloatToIntegralValue    decQuadToIntegralValue\r
+#define decFloatToIntegralExact    decQuadToIntegralExact\r
+#define decFloatXor                decQuadXor\r
+\r
+// Comparisons\r
+#define decFloatCompare            decQuadCompare\r
+#define decFloatCompareSignal      decQuadCompareSignal\r
+#define decFloatCompareTotal       decQuadCompareTotal\r
+#define decFloatCompareTotalMag    decQuadCompareTotalMag\r
+\r
+// Copies\r
+#define decFloatCanonical          decQuadCanonical\r
+#define decFloatCopy               decQuadCopy\r
+#define decFloatCopyAbs            decQuadCopyAbs\r
+#define decFloatCopyNegate         decQuadCopyNegate\r
+#define decFloatCopySign           decQuadCopySign\r
+\r
+// Non-computational\r
+#define decFloatClass              decQuadClass\r
+#define decFloatClassString        decQuadClassString\r
+#define decFloatDigits             decQuadDigits\r
+#define decFloatIsCanonical        decQuadIsCanonical\r
+#define decFloatIsFinite           decQuadIsFinite\r
+#define decFloatIsInfinite         decQuadIsInfinite\r
+#define decFloatIsInteger          decQuadIsInteger\r
+#define decFloatIsLogical          decQuadIsLogical\r
+#define decFloatIsNaN              decQuadIsNaN\r
+#define decFloatIsNegative         decQuadIsNegative\r
+#define decFloatIsNormal           decQuadIsNormal\r
+#define decFloatIsPositive         decQuadIsPositive\r
+#define decFloatIsSignaling        decQuadIsSignaling\r
+#define decFloatIsSignalling       decQuadIsSignalling\r
+#define decFloatIsSigned           decQuadIsSigned\r
+#define decFloatIsSubnormal        decQuadIsSubnormal\r
+#define decFloatIsZero             decQuadIsZero\r
+#define decFloatRadix              decQuadRadix\r
+#define decFloatSameQuantum        decQuadSameQuantum\r
+#define decFloatVersion            decQuadVersion\r
+\r
+/* And now the code itself */\r
+#include "decContext.h"       // public includes\r
+#include "decQuad.h"          // ..\r
+#include "decNumberLocal.h"   // local includes (need DECPMAX)\r
+#include "decCommon.c"        // non-arithmetic decFloat routines\r
+#include "decBasic.c"         // basic formats routines\r
+\r
diff --git a/src/decNumber/decQuad.h b/src/decNumber/decQuad.h
new file mode 100644 (file)
index 0000000..4eb7017
--- /dev/null
@@ -0,0 +1,177 @@
+/* ------------------------------------------------------------------ */\r
+/* decQuad.h -- Decimal 128-bit format module header                  */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2010.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is included in the package as decNumber.pdf.  This   */\r
+/* document is also available in HTML, together with specifications,  */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This include file is always included by decSingle and decDouble,   */\r
+/* and therefore also holds useful constants used by all three.       */\r
+\r
+#if !defined(DECQUAD)\r
+  #define DECQUAD\r
+\r
+  #define DECQUADNAME         "decimalQuad"           /* Short name   */\r
+  #define DECQUADTITLE        "Decimal 128-bit datum" /* Verbose name */\r
+  #define DECQUADAUTHOR       "Mike Cowlishaw"        /* Who to blame */\r
+\r
+  /* parameters for decQuads */\r
+  #define DECQUAD_Bytes    16      /* length                          */\r
+  #define DECQUAD_Pmax     34      /* maximum precision (digits)      */\r
+  #define DECQUAD_Emin  -6143      /* minimum adjusted exponent       */\r
+  #define DECQUAD_Emax   6144      /* maximum adjusted exponent       */\r
+  #define DECQUAD_EmaxD     4      /* maximum exponent digits         */\r
+  #define DECQUAD_Bias   6176      /* bias for the exponent           */\r
+  #define DECQUAD_String   43      /* maximum string length, +1       */\r
+  #define DECQUAD_EconL    12      /* exponent continuation length    */\r
+  #define DECQUAD_Declets  11      /* count of declets                */\r
+  /* highest biased exponent (Elimit-1) */\r
+  #define DECQUAD_Ehigh (DECQUAD_Emax + DECQUAD_Bias - (DECQUAD_Pmax-1))\r
+\r
+  /* Required include                                                 */\r
+  #include "decContext.h"\r
+\r
+  /* The decQuad decimal 128-bit type, accessible by all sizes */\r
+  typedef union {\r
+    uint8_t   bytes[DECQUAD_Bytes];     /* fields: 1, 5, 12, 110 bits */\r
+    uint16_t shorts[DECQUAD_Bytes/2];\r
+    uint32_t  words[DECQUAD_Bytes/4];\r
+    #if DECUSE64\r
+    uint64_t  longs[DECQUAD_Bytes/8];\r
+    #endif\r
+    } decQuad;\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Shared constants                                                 */\r
+  /* ---------------------------------------------------------------- */\r
+\r
+  /* sign and special values [top 32-bits; last two bits are don't-care\r
+     for Infinity on input, last bit don't-care for NaNs] */\r
+  #define DECFLOAT_Sign  0x80000000     /* 1 00000 00 Sign */\r
+  #define DECFLOAT_NaN   0x7c000000     /* 0 11111 00 NaN generic */\r
+  #define DECFLOAT_qNaN  0x7c000000     /* 0 11111 00 qNaN */\r
+  #define DECFLOAT_sNaN  0x7e000000     /* 0 11111 10 sNaN */\r
+  #define DECFLOAT_Inf   0x78000000     /* 0 11110 00 Infinity */\r
+  #define DECFLOAT_MinSp 0x78000000     /* minimum special value */\r
+                                        /* [specials are all >=MinSp] */\r
+  /* Sign nibble constants                                            */\r
+  #if !defined(DECPPLUSALT)\r
+    #define DECPPLUSALT  0x0A /* alternate plus  nibble               */\r
+    #define DECPMINUSALT 0x0B /* alternate minus nibble               */\r
+    #define DECPPLUS     0x0C /* preferred plus  nibble               */\r
+    #define DECPMINUS    0x0D /* preferred minus nibble               */\r
+    #define DECPPLUSALT2 0x0E /* alternate plus  nibble               */\r
+    #define DECPUNSIGNED 0x0F /* alternate plus  nibble (unsigned)    */\r
+  #endif\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Routines -- implemented as decFloat routines in common files     */\r
+  /* ---------------------------------------------------------------- */\r
+\r
+  /* Utilities and conversions, extractors, etc.) */\r
+  extern decQuad * decQuadFromBCD(decQuad *, int32_t, const uint8_t *, int32_t);\r
+  extern decQuad * decQuadFromInt32(decQuad *, int32_t);\r
+  extern decQuad * decQuadFromPacked(decQuad *, int32_t, const uint8_t *);\r
+  extern decQuad * decQuadFromPackedChecked(decQuad *, int32_t, const uint8_t *);\r
+  extern decQuad * decQuadFromString(decQuad *, const char *, decContext *);\r
+  extern decQuad * decQuadFromUInt32(decQuad *, uint32_t);\r
+  extern int32_t   decQuadGetCoefficient(const decQuad *, uint8_t *);\r
+  extern int32_t   decQuadGetExponent(const decQuad *);\r
+  extern decQuad * decQuadSetCoefficient(decQuad *, const uint8_t *, int32_t);\r
+  extern decQuad * decQuadSetExponent(decQuad *, decContext *, int32_t);\r
+  extern void      decQuadShow(const decQuad *, const char *);\r
+  extern int32_t   decQuadToBCD(const decQuad *, int32_t *, uint8_t *);\r
+  extern char    * decQuadToEngString(const decQuad *, char *);\r
+  extern int32_t   decQuadToInt32(const decQuad *, decContext *, enum rounding);\r
+  extern int32_t   decQuadToInt32Exact(const decQuad *, decContext *, enum rounding);\r
+  extern int32_t   decQuadToPacked(const decQuad *, int32_t *, uint8_t *);\r
+  extern char    * decQuadToString(const decQuad *, char *);\r
+  extern uint32_t  decQuadToUInt32(const decQuad *, decContext *, enum rounding);\r
+  extern uint32_t  decQuadToUInt32Exact(const decQuad *, decContext *, enum rounding);\r
+  extern decQuad * decQuadZero(decQuad *);\r
+\r
+  /* Computational (result is a decQuad) */\r
+  extern decQuad * decQuadAbs(decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadAdd(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadAnd(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadDivide(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadDivideInteger(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadFMA(decQuad *, const decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadInvert(decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadLogB(decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadMax(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadMaxMag(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadMin(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadMinMag(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadMinus(decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadMultiply(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadNextMinus(decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadNextPlus(decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadNextToward(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadOr(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadPlus(decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadQuantize(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadReduce(decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadRemainder(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadRemainderNear(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadRotate(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadScaleB(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadShift(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadSubtract(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadToIntegralValue(decQuad *, const decQuad *, decContext *, enum rounding);\r
+  extern decQuad * decQuadToIntegralExact(decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadXor(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+\r
+  /* Comparisons */\r
+  extern decQuad * decQuadCompare(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadCompareSignal(decQuad *, const decQuad *, const decQuad *, decContext *);\r
+  extern decQuad * decQuadCompareTotal(decQuad *, const decQuad *, const decQuad *);\r
+  extern decQuad * decQuadCompareTotalMag(decQuad *, const decQuad *, const decQuad *);\r
+\r
+  /* Copies */\r
+  extern decQuad * decQuadCanonical(decQuad *, const decQuad *);\r
+  extern decQuad * decQuadCopy(decQuad *, const decQuad *);\r
+  extern decQuad * decQuadCopyAbs(decQuad *, const decQuad *);\r
+  extern decQuad * decQuadCopyNegate(decQuad *, const decQuad *);\r
+  extern decQuad * decQuadCopySign(decQuad *, const decQuad *, const decQuad *);\r
+\r
+  /* Non-computational */\r
+  extern enum decClass decQuadClass(const decQuad *);\r
+  extern const char *  decQuadClassString(const decQuad *);\r
+  extern uint32_t      decQuadDigits(const decQuad *);\r
+  extern uint32_t      decQuadIsCanonical(const decQuad *);\r
+  extern uint32_t      decQuadIsFinite(const decQuad *);\r
+  extern uint32_t      decQuadIsInteger(const decQuad *);\r
+  extern uint32_t      decQuadIsLogical(const decQuad *);\r
+  extern uint32_t      decQuadIsInfinite(const decQuad *);\r
+  extern uint32_t      decQuadIsNaN(const decQuad *);\r
+  extern uint32_t      decQuadIsNegative(const decQuad *);\r
+  extern uint32_t      decQuadIsNormal(const decQuad *);\r
+  extern uint32_t      decQuadIsPositive(const decQuad *);\r
+  extern uint32_t      decQuadIsSignaling(const decQuad *);\r
+  extern uint32_t      decQuadIsSignalling(const decQuad *);\r
+  extern uint32_t      decQuadIsSigned(const decQuad *);\r
+  extern uint32_t      decQuadIsSubnormal(const decQuad *);\r
+  extern uint32_t      decQuadIsZero(const decQuad *);\r
+  extern uint32_t      decQuadRadix(const decQuad *);\r
+  extern uint32_t      decQuadSameQuantum(const decQuad *, const decQuad *);\r
+  extern const char *  decQuadVersion(void);\r
+\r
+  /* decNumber conversions; these are implemented as macros so as not  */\r
+  /* to force a dependency on decimal128 and decNumber in decQuad.     */\r
+  /* decQuadFromNumber returns a decimal128 * to avoid warnings.       */\r
+  #define decQuadToNumber(dq, dn) decimal128ToNumber((decimal128 *)(dq), dn)\r
+  #define decQuadFromNumber(dq, dn, set) decimal128FromNumber((decimal128 *)(dq), dn, set)\r
+\r
+#endif\r
diff --git a/src/decNumber/decSingle.c b/src/decNumber/decSingle.c
new file mode 100644 (file)
index 0000000..bb69970
--- /dev/null
@@ -0,0 +1,71 @@
+/* ------------------------------------------------------------------ */\r
+/* decSingle.c -- decSingle operations module                         */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2008.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is included in the package as decNumber.pdf.  This   */\r
+/* document is also available in HTML, together with specifications,  */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises decSingle operations (including conversions) */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#include "decContext.h"       // public includes\r
+#include "decSingle.h"        // public includes\r
+\r
+/* Constant mappings for shared code */\r
+#define DECPMAX     DECSINGLE_Pmax\r
+#define DECEMIN     DECSINGLE_Emin\r
+#define DECEMAX     DECSINGLE_Emax\r
+#define DECEMAXD    DECSINGLE_EmaxD\r
+#define DECBYTES    DECSINGLE_Bytes\r
+#define DECSTRING   DECSINGLE_String\r
+#define DECECONL    DECSINGLE_EconL\r
+#define DECBIAS     DECSINGLE_Bias\r
+#define DECLETS     DECSINGLE_Declets\r
+#define DECQTINY    (-DECSINGLE_Bias)\r
+// parameters of next-wider format\r
+#define DECWBYTES   DECDOUBLE_Bytes\r
+#define DECWPMAX    DECDOUBLE_Pmax\r
+#define DECWECONL   DECDOUBLE_EconL\r
+#define DECWBIAS    DECDOUBLE_Bias\r
+\r
+/* Type and function mappings for shared code */\r
+#define decFloat                   decSingle      // Type name\r
+#define decFloatWider              decDouble      // Type name\r
+\r
+// Utility (binary results, extractors, etc.)\r
+#define decFloatFromBCD            decSingleFromBCD\r
+#define decFloatFromPacked         decSingleFromPacked\r
+#define decFloatFromPackedChecked  decSingleFromPackedChecked\r
+#define decFloatFromString         decSingleFromString\r
+#define decFloatFromWider          decSingleFromWider\r
+#define decFloatGetCoefficient     decSingleGetCoefficient\r
+#define decFloatGetExponent        decSingleGetExponent\r
+#define decFloatSetCoefficient     decSingleSetCoefficient\r
+#define decFloatSetExponent        decSingleSetExponent\r
+#define decFloatShow               decSingleShow\r
+#define decFloatToBCD              decSingleToBCD\r
+#define decFloatToEngString        decSingleToEngString\r
+#define decFloatToPacked           decSingleToPacked\r
+#define decFloatToString           decSingleToString\r
+#define decFloatToWider            decSingleToWider\r
+#define decFloatZero               decSingleZero\r
+\r
+// Non-computational\r
+#define decFloatRadix              decSingleRadix\r
+#define decFloatVersion            decSingleVersion\r
+\r
+#include "decNumberLocal.h"   // local includes (need DECPMAX)\r
+#include "decCommon.c"        // non-basic decFloat routines\r
+// [Do not include decBasic.c for decimal32]\r
+\r
diff --git a/src/decNumber/decSingle.h b/src/decNumber/decSingle.h
new file mode 100644 (file)
index 0000000..0691f7a
--- /dev/null
@@ -0,0 +1,86 @@
+/* ------------------------------------------------------------------ */\r
+/* decSingle.h -- Decimal 32-bit format module header                 */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2008.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is included in the package as decNumber.pdf.  This   */\r
+/* document is also available in HTML, together with specifications,  */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#if !defined(DECSINGLE)\r
+  #define DECSINGLE\r
+\r
+  #define DECSINGLENAME       "decSingle"             /* Short name   */\r
+  #define DECSINGLETITLE      "Decimal 32-bit datum"  /* Verbose name */\r
+  #define DECSINGLEAUTHOR     "Mike Cowlishaw"        /* Who to blame */\r
+\r
+  /* parameters for decSingles */\r
+  #define DECSINGLE_Bytes    4     /* length                          */\r
+  #define DECSINGLE_Pmax     7     /* maximum precision (digits)      */\r
+  #define DECSINGLE_Emin   -95     /* minimum adjusted exponent       */\r
+  #define DECSINGLE_Emax    96     /* maximum adjusted exponent       */\r
+  #define DECSINGLE_EmaxD    3     /* maximum exponent digits         */\r
+  #define DECSINGLE_Bias   101     /* bias for the exponent           */\r
+  #define DECSINGLE_String  16     /* maximum string length, +1       */\r
+  #define DECSINGLE_EconL    6     /* exponent continuation length    */\r
+  #define DECSINGLE_Declets  2     /* count of declets                */\r
+  /* highest biased exponent (Elimit-1) */\r
+  #define DECSINGLE_Ehigh (DECSINGLE_Emax + DECSINGLE_Bias - (DECSINGLE_Pmax-1))\r
+\r
+  /* Required includes                                                */\r
+  #include "decContext.h"\r
+  #include "decQuad.h"\r
+  #include "decDouble.h"\r
+\r
+  /* The decSingle decimal 32-bit type, accessible by all sizes */\r
+  typedef union {\r
+    uint8_t   bytes[DECSINGLE_Bytes];   /* fields: 1, 5, 6, 20 bits */\r
+    uint16_t shorts[DECSINGLE_Bytes/2];\r
+    uint32_t  words[DECSINGLE_Bytes/4];\r
+    } decSingle;\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Routines -- implemented as decFloat routines in common files     */\r
+  /* ---------------------------------------------------------------- */\r
+\r
+  /* Utilities (binary argument(s) or result, extractors, etc.) */\r
+  extern decSingle * decSingleFromBCD(decSingle *, int32_t, const uint8_t *, int32_t);\r
+  extern decSingle * decSingleFromPacked(decSingle *, int32_t, const uint8_t *);\r
+  extern decSingle * decSingleFromPackedChecked(decSingle *, int32_t, const uint8_t *);\r
+  extern decSingle * decSingleFromString(decSingle *, const char *, decContext *);\r
+  extern decSingle * decSingleFromWider(decSingle *, const decDouble *, decContext *);\r
+  extern int32_t     decSingleGetCoefficient(const decSingle *, uint8_t *);\r
+  extern int32_t     decSingleGetExponent(const decSingle *);\r
+  extern decSingle * decSingleSetCoefficient(decSingle *, const uint8_t *, int32_t);\r
+  extern decSingle * decSingleSetExponent(decSingle *, decContext *, int32_t);\r
+  extern void        decSingleShow(const decSingle *, const char *);\r
+  extern int32_t     decSingleToBCD(const decSingle *, int32_t *, uint8_t *);\r
+  extern char      * decSingleToEngString(const decSingle *, char *);\r
+  extern int32_t     decSingleToPacked(const decSingle *, int32_t *, uint8_t *);\r
+  extern char      * decSingleToString(const decSingle *, char *);\r
+  extern decDouble * decSingleToWider(const decSingle *, decDouble *);\r
+  extern decSingle * decSingleZero(decSingle *);\r
+\r
+  /* (No Arithmetic routines for decSingle) */\r
+\r
+  /* Non-computational */\r
+  extern uint32_t     decSingleRadix(const decSingle *);\r
+  extern const char * decSingleVersion(void);\r
+\r
+  /* decNumber conversions; these are implemented as macros so as not  */\r
+  /* to force a dependency on decimal32 and decNumber in decSingle.    */\r
+  /* decSingleFromNumber returns a decimal32 * to avoid warnings.      */\r
+  #define decSingleToNumber(dq, dn) decimal32ToNumber((decimal32 *)(dq), dn)\r
+  #define decSingleFromNumber(dq, dn, set) decimal32FromNumber((decimal32 *)(dq), dn, set)\r
+\r
+#endif\r
diff --git a/src/decNumber/decimal128.c b/src/decNumber/decimal128.c
new file mode 100644 (file)
index 0000000..e5fa45b
--- /dev/null
@@ -0,0 +1,553 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal 128-bit format module                                      */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2008.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises the routines for decimal128 format numbers.  */\r
+/* Conversions are supplied to and from decNumber and String.         */\r
+/*                                                                    */\r
+/* This is used when decNumber provides operations, either for all    */\r
+/* operations or as a proxy between decNumber and decSingle.          */\r
+/*                                                                    */\r
+/* Error handling is the same as decNumber (qv.).                     */\r
+/* ------------------------------------------------------------------ */\r
+#include <string.h>           // [for memset/memcpy]\r
+#include <stdio.h>            // [for printf]\r
+\r
+#define  DECNUMDIGITS 34      // make decNumbers with space for 34\r
+#include "decNumber.h"        // base number library\r
+#include "decNumberLocal.h"   // decNumber local types, etc.\r
+#include "decimal128.h"       // our primary include\r
+\r
+/* Utility routines and tables [in decimal64.c] */\r
+// DPD2BIN and the reverse are renamed to prevent link-time conflict\r
+// if decQuad is also built in the same executable\r
+#define DPD2BIN DPD2BINx\r
+#define BIN2DPD BIN2DPDx\r
+extern const uInt   COMBEXP[32], COMBMSD[32];\r
+extern const uShort DPD2BIN[1024];\r
+extern const uShort BIN2DPD[1000];      // [not used]\r
+extern const uByte  BIN2CHAR[4001];\r
+\r
+extern void decDigitsFromDPD(decNumber *, const uInt *, Int);\r
+extern void decDigitsToDPD(const decNumber *, uInt *, Int);\r
+\r
+#if DECTRACE || DECCHECK\r
+void decimal128Show(const decimal128 *);          // for debug\r
+extern void decNumberShow(const decNumber *);     // ..\r
+#endif\r
+\r
+/* Useful macro */\r
+// Clear a structure (e.g., a decNumber)\r
+#define DEC_clear(d) memset(d, 0, sizeof(*d))\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal128FromNumber -- convert decNumber to decimal128            */\r
+/*                                                                    */\r
+/*   ds is the target decimal128                                      */\r
+/*   dn is the source number (assumed valid)                          */\r
+/*   set is the context, used only for reporting errors               */\r
+/*                                                                    */\r
+/* The set argument is used only for status reporting and for the     */\r
+/* rounding mode (used if the coefficient is more than DECIMAL128_Pmax*/\r
+/* digits or an overflow is detected).  If the exponent is out of the */\r
+/* valid range then Overflow or Underflow will be raised.             */\r
+/* After Underflow a subnormal result is possible.                    */\r
+/*                                                                    */\r
+/* DEC_Clamped is set if the number has to be 'folded down' to fit,   */\r
+/* by reducing its exponent and multiplying the coefficient by a      */\r
+/* power of ten, or if the exponent on a zero had to be clamped.      */\r
+/* ------------------------------------------------------------------ */\r
+decimal128 * decimal128FromNumber(decimal128 *d128, const decNumber *dn,\r
+                                  decContext *set) {\r
+  uInt status=0;                   // status accumulator\r
+  Int ae;                          // adjusted exponent\r
+  decNumber  dw;                   // work\r
+  decContext dc;                   // ..\r
+  uInt comb, exp;                  // ..\r
+  uInt uiwork;                     // for macros\r
+  uInt targar[4]={0,0,0,0};        // target 128-bit\r
+  #define targhi targar[3]         // name the word with the sign\r
+  #define targmh targar[2]         // name the words\r
+  #define targml targar[1]         // ..\r
+  #define targlo targar[0]         // ..\r
+\r
+  // If the number has too many digits, or the exponent could be\r
+  // out of range then reduce the number under the appropriate\r
+  // constraints.  This could push the number to Infinity or zero,\r
+  // so this check and rounding must be done before generating the\r
+  // decimal128]\r
+  ae=dn->exponent+dn->digits-1;              // [0 if special]\r
+  if (dn->digits>DECIMAL128_Pmax             // too many digits\r
+   || ae>DECIMAL128_Emax                     // likely overflow\r
+   || ae<DECIMAL128_Emin) {                  // likely underflow\r
+    decContextDefault(&dc, DEC_INIT_DECIMAL128); // [no traps]\r
+    dc.round=set->round;                     // use supplied rounding\r
+    decNumberPlus(&dw, dn, &dc);             // (round and check)\r
+    // [this changes -0 to 0, so enforce the sign...]\r
+    dw.bits|=dn->bits&DECNEG;\r
+    status=dc.status;                        // save status\r
+    dn=&dw;                                  // use the work number\r
+    } // maybe out of range\r
+\r
+  if (dn->bits&DECSPECIAL) {                      // a special value\r
+    if (dn->bits&DECINF) targhi=DECIMAL_Inf<<24;\r
+     else {                                       // sNaN or qNaN\r
+      if ((*dn->lsu!=0 || dn->digits>1)           // non-zero coefficient\r
+       && (dn->digits<DECIMAL128_Pmax)) {         // coefficient fits\r
+        decDigitsToDPD(dn, targar, 0);\r
+        }\r
+      if (dn->bits&DECNAN) targhi|=DECIMAL_NaN<<24;\r
+       else targhi|=DECIMAL_sNaN<<24;\r
+      } // a NaN\r
+    } // special\r
+\r
+   else { // is finite\r
+    if (decNumberIsZero(dn)) {               // is a zero\r
+      // set and clamp exponent\r
+      if (dn->exponent<-DECIMAL128_Bias) {\r
+        exp=0;                               // low clamp\r
+        status|=DEC_Clamped;\r
+        }\r
+       else {\r
+        exp=dn->exponent+DECIMAL128_Bias;    // bias exponent\r
+        if (exp>DECIMAL128_Ehigh) {          // top clamp\r
+          exp=DECIMAL128_Ehigh;\r
+          status|=DEC_Clamped;\r
+          }\r
+        }\r
+      comb=(exp>>9) & 0x18;             // msd=0, exp top 2 bits ..\r
+      }\r
+     else {                             // non-zero finite number\r
+      uInt msd;                         // work\r
+      Int pad=0;                        // coefficient pad digits\r
+\r
+      // the dn is known to fit, but it may need to be padded\r
+      exp=(uInt)(dn->exponent+DECIMAL128_Bias);    // bias exponent\r
+      if (exp>DECIMAL128_Ehigh) {                  // fold-down case\r
+        pad=exp-DECIMAL128_Ehigh;\r
+        exp=DECIMAL128_Ehigh;                      // [to maximum]\r
+        status|=DEC_Clamped;\r
+        }\r
+\r
+      // [fastpath for common case is not a win, here]\r
+      decDigitsToDPD(dn, targar, pad);\r
+      // save and clear the top digit\r
+      msd=targhi>>14;\r
+      targhi&=0x00003fff;\r
+\r
+      // create the combination field\r
+      if (msd>=8) comb=0x18 | ((exp>>11) & 0x06) | (msd & 0x01);\r
+             else comb=((exp>>9) & 0x18) | msd;\r
+      }\r
+    targhi|=comb<<26;              // add combination field ..\r
+    targhi|=(exp&0xfff)<<14;       // .. and exponent continuation\r
+    } // finite\r
+\r
+  if (dn->bits&DECNEG) targhi|=0x80000000; // add sign bit\r
+\r
+  // now write to storage; this is endian\r
+  if (DECLITEND) {\r
+    // lo -> hi\r
+    UBFROMUI(d128->bytes,    targlo);\r
+    UBFROMUI(d128->bytes+4,  targml);\r
+    UBFROMUI(d128->bytes+8,  targmh);\r
+    UBFROMUI(d128->bytes+12, targhi);\r
+    }\r
+   else {\r
+    // hi -> lo\r
+    UBFROMUI(d128->bytes,    targhi);\r
+    UBFROMUI(d128->bytes+4,  targmh);\r
+    UBFROMUI(d128->bytes+8,  targml);\r
+    UBFROMUI(d128->bytes+12, targlo);\r
+    }\r
+\r
+  if (status!=0) decContextSetStatus(set, status); // pass on status\r
+  // decimal128Show(d128);\r
+  return d128;\r
+  } // decimal128FromNumber\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal128ToNumber -- convert decimal128 to decNumber              */\r
+/*   d128 is the source decimal128                                    */\r
+/*   dn is the target number, with appropriate space                  */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decimal128ToNumber(const decimal128 *d128, decNumber *dn) {\r
+  uInt msd;                        // coefficient MSD\r
+  uInt exp;                        // exponent top two bits\r
+  uInt comb;                       // combination field\r
+  Int  need;                       // work\r
+  uInt uiwork;                     // for macros\r
+  uInt sourar[4];                  // source 128-bit\r
+  #define sourhi sourar[3]         // name the word with the sign\r
+  #define sourmh sourar[2]         // and the mid-high word\r
+  #define sourml sourar[1]         // and the mod-low word\r
+  #define sourlo sourar[0]         // and the lowest word\r
+\r
+  // load source from storage; this is endian\r
+  if (DECLITEND) {\r
+    sourlo=UBTOUI(d128->bytes   ); // directly load the low int\r
+    sourml=UBTOUI(d128->bytes+4 ); // then the mid-low\r
+    sourmh=UBTOUI(d128->bytes+8 ); // then the mid-high\r
+    sourhi=UBTOUI(d128->bytes+12); // then the high int\r
+    }\r
+   else {\r
+    sourhi=UBTOUI(d128->bytes   ); // directly load the high int\r
+    sourmh=UBTOUI(d128->bytes+4 ); // then the mid-high\r
+    sourml=UBTOUI(d128->bytes+8 ); // then the mid-low\r
+    sourlo=UBTOUI(d128->bytes+12); // then the low int\r
+    }\r
+\r
+  comb=(sourhi>>26)&0x1f;          // combination field\r
+\r
+  decNumberZero(dn);               // clean number\r
+  if (sourhi&0x80000000) dn->bits=DECNEG; // set sign if negative\r
+\r
+  msd=COMBMSD[comb];               // decode the combination field\r
+  exp=COMBEXP[comb];               // ..\r
+\r
+  if (exp==3) {                    // is a special\r
+    if (msd==0) {\r
+      dn->bits|=DECINF;\r
+      return dn;                   // no coefficient needed\r
+      }\r
+    else if (sourhi&0x02000000) dn->bits|=DECSNAN;\r
+    else dn->bits|=DECNAN;\r
+    msd=0;                         // no top digit\r
+    }\r
+   else {                          // is a finite number\r
+    dn->exponent=(exp<<12)+((sourhi>>14)&0xfff)-DECIMAL128_Bias; // unbiased\r
+    }\r
+\r
+  // get the coefficient\r
+  sourhi&=0x00003fff;              // clean coefficient continuation\r
+  if (msd) {                       // non-zero msd\r
+    sourhi|=msd<<14;               // prefix to coefficient\r
+    need=12;                       // process 12 declets\r
+    }\r
+   else { // msd=0\r
+    if (sourhi) need=11;           // declets to process\r
+     else if (sourmh) need=10;\r
+     else if (sourml) need=7;\r
+     else if (sourlo) need=4;\r
+     else return dn;               // easy: coefficient is 0\r
+    } //msd=0\r
+\r
+  decDigitsFromDPD(dn, sourar, need);   // process declets\r
+  // decNumberShow(dn);\r
+  return dn;\r
+  } // decimal128ToNumber\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* to-scientific-string -- conversion to numeric string               */\r
+/* to-engineering-string -- conversion to numeric string              */\r
+/*                                                                    */\r
+/*   decimal128ToString(d128, string);                                */\r
+/*   decimal128ToEngString(d128, string);                             */\r
+/*                                                                    */\r
+/*  d128 is the decimal128 format number to convert                   */\r
+/*  string is the string where the result will be laid out            */\r
+/*                                                                    */\r
+/*  string must be at least 24 characters                             */\r
+/*                                                                    */\r
+/*  No error is possible, and no status can be set.                   */\r
+/* ------------------------------------------------------------------ */\r
+char * decimal128ToEngString(const decimal128 *d128, char *string){\r
+  decNumber dn;                         // work\r
+  decimal128ToNumber(d128, &dn);\r
+  decNumberToEngString(&dn, string);\r
+  return string;\r
+  } // decimal128ToEngString\r
+\r
+char * decimal128ToString(const decimal128 *d128, char *string){\r
+  uInt msd;                        // coefficient MSD\r
+  Int  exp;                        // exponent top two bits or full\r
+  uInt comb;                       // combination field\r
+  char *cstart;                    // coefficient start\r
+  char *c;                         // output pointer in string\r
+  const uByte *u;                  // work\r
+  char *s, *t;                     // .. (source, target)\r
+  Int  dpd;                        // ..\r
+  Int  pre, e;                     // ..\r
+  uInt uiwork;                     // for macros\r
+\r
+  uInt sourar[4];                  // source 128-bit\r
+  #define sourhi sourar[3]         // name the word with the sign\r
+  #define sourmh sourar[2]         // and the mid-high word\r
+  #define sourml sourar[1]         // and the mod-low word\r
+  #define sourlo sourar[0]         // and the lowest word\r
+\r
+  // load source from storage; this is endian\r
+  if (DECLITEND) {\r
+    sourlo=UBTOUI(d128->bytes   ); // directly load the low int\r
+    sourml=UBTOUI(d128->bytes+4 ); // then the mid-low\r
+    sourmh=UBTOUI(d128->bytes+8 ); // then the mid-high\r
+    sourhi=UBTOUI(d128->bytes+12); // then the high int\r
+    }\r
+   else {\r
+    sourhi=UBTOUI(d128->bytes   ); // directly load the high int\r
+    sourmh=UBTOUI(d128->bytes+4 ); // then the mid-high\r
+    sourml=UBTOUI(d128->bytes+8 ); // then the mid-low\r
+    sourlo=UBTOUI(d128->bytes+12); // then the low int\r
+    }\r
+\r
+  c=string;                        // where result will go\r
+  if (((Int)sourhi)<0) *c++='-';   // handle sign\r
+\r
+  comb=(sourhi>>26)&0x1f;          // combination field\r
+  msd=COMBMSD[comb];               // decode the combination field\r
+  exp=COMBEXP[comb];               // ..\r
+\r
+  if (exp==3) {\r
+    if (msd==0) {                  // infinity\r
+      strcpy(c,   "Inf");\r
+      strcpy(c+3, "inity");\r
+      return string;               // easy\r
+      }\r
+    if (sourhi&0x02000000) *c++='s'; // sNaN\r
+    strcpy(c, "NaN");              // complete word\r
+    c+=3;                          // step past\r
+    if (sourlo==0 && sourml==0 && sourmh==0\r
+     && (sourhi&0x0003ffff)==0) return string; // zero payload\r
+    // otherwise drop through to add integer; set correct exp\r
+    exp=0; msd=0;                  // setup for following code\r
+    }\r
+   else exp=(exp<<12)+((sourhi>>14)&0xfff)-DECIMAL128_Bias; // unbiased\r
+\r
+  // convert 34 digits of significand to characters\r
+  cstart=c;                        // save start of coefficient\r
+  if (msd) *c++='0'+(char)msd;     // non-zero most significant digit\r
+\r
+  // Now decode the declets.  After extracting each one, it is\r
+  // decoded to binary and then to a 4-char sequence by table lookup;\r
+  // the 4-chars are a 1-char length (significant digits, except 000\r
+  // has length 0).  This allows us to left-align the first declet\r
+  // with non-zero content, then remaining ones are full 3-char\r
+  // length.  We use fixed-length memcpys because variable-length\r
+  // causes a subroutine call in GCC.  (These are length 4 for speed\r
+  // and are safe because the array has an extra terminator byte.)\r
+  #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4];                   \\r
+                   if (c!=cstart) {memcpy(c, u+1, 4); c+=3;}      \\r
+                    else if (*u)  {memcpy(c, u+4-*u, 4); c+=*u;}\r
+  dpd=(sourhi>>4)&0x3ff;                     // declet 1\r
+  dpd2char;\r
+  dpd=((sourhi&0xf)<<6) | (sourmh>>26);      // declet 2\r
+  dpd2char;\r
+  dpd=(sourmh>>16)&0x3ff;                    // declet 3\r
+  dpd2char;\r
+  dpd=(sourmh>>6)&0x3ff;                     // declet 4\r
+  dpd2char;\r
+  dpd=((sourmh&0x3f)<<4) | (sourml>>28);     // declet 5\r
+  dpd2char;\r
+  dpd=(sourml>>18)&0x3ff;                    // declet 6\r
+  dpd2char;\r
+  dpd=(sourml>>8)&0x3ff;                     // declet 7\r
+  dpd2char;\r
+  dpd=((sourml&0xff)<<2) | (sourlo>>30);     // declet 8\r
+  dpd2char;\r
+  dpd=(sourlo>>20)&0x3ff;                    // declet 9\r
+  dpd2char;\r
+  dpd=(sourlo>>10)&0x3ff;                    // declet 10\r
+  dpd2char;\r
+  dpd=(sourlo)&0x3ff;                        // declet 11\r
+  dpd2char;\r
+\r
+  if (c==cstart) *c++='0';         // all zeros -- make 0\r
+\r
+  if (exp==0) {                    // integer or NaN case -- easy\r
+    *c='\0';                       // terminate\r
+    return string;\r
+    }\r
+\r
+  /* non-0 exponent */\r
+  e=0;                             // assume no E\r
+  pre=c-cstart+exp;\r
+  // [here, pre-exp is the digits count (==1 for zero)]\r
+  if (exp>0 || pre<-5) {           // need exponential form\r
+    e=pre-1;                       // calculate E value\r
+    pre=1;                         // assume one digit before '.'\r
+    } // exponential form\r
+\r
+  /* modify the coefficient, adding 0s, '.', and E+nn as needed */\r
+  s=c-1;                           // source (LSD)\r
+  if (pre>0) {                     // ddd.ddd (plain), perhaps with E\r
+    char *dotat=cstart+pre;\r
+    if (dotat<c) {                 // if embedded dot needed...\r
+      t=c;                              // target\r
+      for (; s>=dotat; s--, t--) *t=*s; // open the gap; leave t at gap\r
+      *t='.';                           // insert the dot\r
+      c++;                              // length increased by one\r
+      }\r
+\r
+    // finally add the E-part, if needed; it will never be 0, and has\r
+    // a maximum length of 4 digits\r
+    if (e!=0) {\r
+      *c++='E';                    // starts with E\r
+      *c++='+';                    // assume positive\r
+      if (e<0) {\r
+        *(c-1)='-';                // oops, need '-'\r
+        e=-e;                      // uInt, please\r
+        }\r
+      if (e<1000) {                // 3 (or fewer) digits case\r
+        u=&BIN2CHAR[e*4];          // -> length byte\r
+        memcpy(c, u+4-*u, 4);      // copy fixed 4 characters [is safe]\r
+        c+=*u;                     // bump pointer appropriately\r
+        }\r
+       else {                      // 4-digits\r
+        Int thou=((e>>3)*1049)>>17; // e/1000\r
+        Int rem=e-(1000*thou);      // e%1000\r
+        *c++='0'+(char)thou;\r
+        u=&BIN2CHAR[rem*4];        // -> length byte\r
+        memcpy(c, u+1, 4);         // copy fixed 3+1 characters [is safe]\r
+        c+=3;                      // bump pointer, always 3 digits\r
+        }\r
+      }\r
+    *c='\0';                       // add terminator\r
+    //printf("res %s\n", string);\r
+    return string;\r
+    } // pre>0\r
+\r
+  /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */\r
+  t=c+1-pre;\r
+  *(t+1)='\0';                          // can add terminator now\r
+  for (; s>=cstart; s--, t--) *t=*s;    // shift whole coefficient right\r
+  c=cstart;\r
+  *c++='0';                             // always starts with 0.\r
+  *c++='.';\r
+  for (; pre<0; pre++) *c++='0';        // add any 0's after '.'\r
+  //printf("res %s\n", string);\r
+  return string;\r
+  } // decimal128ToString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* to-number -- conversion from numeric string                        */\r
+/*                                                                    */\r
+/*   decimal128FromString(result, string, set);                       */\r
+/*                                                                    */\r
+/*  result  is the decimal128 format number which gets the result of  */\r
+/*          the conversion                                            */\r
+/*  *string is the character string which should contain a valid      */\r
+/*          number (which may be a special value)                     */\r
+/*  set     is the context                                            */\r
+/*                                                                    */\r
+/* The context is supplied to this routine is used for error handling */\r
+/* (setting of status and traps) and for the rounding mode, only.     */\r
+/* If an error occurs, the result will be a valid decimal128 NaN.     */\r
+/* ------------------------------------------------------------------ */\r
+decimal128 * decimal128FromString(decimal128 *result, const char *string,\r
+                                  decContext *set) {\r
+  decContext dc;                             // work\r
+  decNumber dn;                              // ..\r
+\r
+  decContextDefault(&dc, DEC_INIT_DECIMAL128); // no traps, please\r
+  dc.round=set->round;                         // use supplied rounding\r
+\r
+  decNumberFromString(&dn, string, &dc);     // will round if needed\r
+  decimal128FromNumber(result, &dn, &dc);\r
+  if (dc.status!=0) {                        // something happened\r
+    decContextSetStatus(set, dc.status);     // .. pass it on\r
+    }\r
+  return result;\r
+  } // decimal128FromString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal128IsCanonical -- test whether encoding is canonical        */\r
+/*   d128 is the source decimal128                                    */\r
+/*   returns 1 if the encoding of d128 is canonical, 0 otherwise      */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+uInt decimal128IsCanonical(const decimal128 *d128) {\r
+  decNumber dn;                         // work\r
+  decimal128 canon;                      // ..\r
+  decContext dc;                        // ..\r
+  decContextDefault(&dc, DEC_INIT_DECIMAL128);\r
+  decimal128ToNumber(d128, &dn);\r
+  decimal128FromNumber(&canon, &dn, &dc);// canon will now be canonical\r
+  return memcmp(d128, &canon, DECIMAL128_Bytes)==0;\r
+  } // decimal128IsCanonical\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal128Canonical -- copy an encoding, ensuring it is canonical  */\r
+/*   d128 is the source decimal128                                    */\r
+/*   result is the target (may be the same decimal128)                */\r
+/*   returns result                                                   */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decimal128 * decimal128Canonical(decimal128 *result, const decimal128 *d128) {\r
+  decNumber dn;                         // work\r
+  decContext dc;                        // ..\r
+  decContextDefault(&dc, DEC_INIT_DECIMAL128);\r
+  decimal128ToNumber(d128, &dn);\r
+  decimal128FromNumber(result, &dn, &dc);// result will now be canonical\r
+  return result;\r
+  } // decimal128Canonical\r
+\r
+#if DECTRACE || DECCHECK\r
+/* Macros for accessing decimal128 fields.  These assume the argument\r
+   is a reference (pointer) to the decimal128 structure, and the\r
+   decimal128 is in network byte order (big-endian) */\r
+// Get sign\r
+#define decimal128Sign(d)       ((unsigned)(d)->bytes[0]>>7)\r
+\r
+// Get combination field\r
+#define decimal128Comb(d)       (((d)->bytes[0] & 0x7c)>>2)\r
+\r
+// Get exponent continuation [does not remove bias]\r
+#define decimal128ExpCon(d)     ((((d)->bytes[0] & 0x03)<<10)         \\r
+                              | ((unsigned)(d)->bytes[1]<<2)          \\r
+                              | ((unsigned)(d)->bytes[2]>>6))\r
+\r
+// Set sign [this assumes sign previously 0]\r
+#define decimal128SetSign(d, b) {                                     \\r
+  (d)->bytes[0]|=((unsigned)(b)<<7);}\r
+\r
+// Set exponent continuation [does not apply bias]\r
+// This assumes range has been checked and exponent previously 0;\r
+// type of exponent must be unsigned\r
+#define decimal128SetExpCon(d, e) {                                   \\r
+  (d)->bytes[0]|=(uByte)((e)>>10);                                    \\r
+  (d)->bytes[1] =(uByte)(((e)&0x3fc)>>2);                             \\r
+  (d)->bytes[2]|=(uByte)(((e)&0x03)<<6);}\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal128Show -- display a decimal128 in hexadecimal [debug aid]  */\r
+/*   d128 -- the number to show                                       */\r
+/* ------------------------------------------------------------------ */\r
+// Also shows sign/cob/expconfields extracted\r
+void decimal128Show(const decimal128 *d128) {\r
+  char buf[DECIMAL128_Bytes*2+1];\r
+  Int i, j=0;\r
+\r
+  if (DECLITEND) {\r
+    for (i=0; i<DECIMAL128_Bytes; i++, j+=2) {\r
+      sprintf(&buf[j], "%02x", d128->bytes[15-i]);\r
+      }\r
+    printf(" D128> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,\r
+           d128->bytes[15]>>7, (d128->bytes[15]>>2)&0x1f,\r
+           ((d128->bytes[15]&0x3)<<10)|(d128->bytes[14]<<2)|\r
+           (d128->bytes[13]>>6));\r
+    }\r
+   else {\r
+    for (i=0; i<DECIMAL128_Bytes; i++, j+=2) {\r
+      sprintf(&buf[j], "%02x", d128->bytes[i]);\r
+      }\r
+    printf(" D128> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,\r
+           decimal128Sign(d128), decimal128Comb(d128),\r
+           decimal128ExpCon(d128));\r
+    }\r
+  } // decimal128Show\r
+#endif\r
diff --git a/src/decNumber/decimal128.h b/src/decNumber/decimal128.h
new file mode 100644 (file)
index 0000000..47d2f8e
--- /dev/null
@@ -0,0 +1,81 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal 128-bit format module header                               */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2005.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#if !defined(DECIMAL128)\r
+  #define DECIMAL128\r
+  #define DEC128NAME     "decimal128"                 /* Short name   */\r
+  #define DEC128FULLNAME "Decimal 128-bit Number"     /* Verbose name */\r
+  #define DEC128AUTHOR   "Mike Cowlishaw"             /* Who to blame */\r
+\r
+  /* parameters for decimal128s */\r
+  #define DECIMAL128_Bytes  16          /* length                     */\r
+  #define DECIMAL128_Pmax   34          /* maximum precision (digits) */\r
+  #define DECIMAL128_Emax   6144        /* maximum adjusted exponent  */\r
+  #define DECIMAL128_Emin  -6143        /* minimum adjusted exponent  */\r
+  #define DECIMAL128_Bias   6176        /* bias for the exponent      */\r
+  #define DECIMAL128_String 43          /* maximum string length, +1  */\r
+  #define DECIMAL128_EconL  12          /* exp. continuation length   */\r
+  /* highest biased exponent (Elimit-1)                               */\r
+  #define DECIMAL128_Ehigh  (DECIMAL128_Emax+DECIMAL128_Bias-DECIMAL128_Pmax+1)\r
+\r
+  /* check enough digits, if pre-defined                              */\r
+  #if defined(DECNUMDIGITS)\r
+    #if (DECNUMDIGITS<DECIMAL128_Pmax)\r
+      #error decimal128.h needs pre-defined DECNUMDIGITS>=34 for safe use\r
+    #endif\r
+  #endif\r
+\r
+  #ifndef DECNUMDIGITS\r
+    #define DECNUMDIGITS DECIMAL128_Pmax /* size if not already defined*/\r
+  #endif\r
+  #ifndef DECNUMBER\r
+    #include "decNumber.h"              /* context and number library */\r
+  #endif\r
+\r
+  /* Decimal 128-bit type, accessible by bytes                        */\r
+  typedef struct {\r
+    uint8_t bytes[DECIMAL128_Bytes]; /* decimal128: 1, 5, 12, 110 bits*/\r
+    } decimal128;\r
+\r
+  /* special values [top byte excluding sign bit; last two bits are   */\r
+  /* don't-care for Infinity on input, last bit don't-care for NaN]   */\r
+  #if !defined(DECIMAL_NaN)\r
+    #define DECIMAL_NaN     0x7c        /* 0 11111 00 NaN             */\r
+    #define DECIMAL_sNaN    0x7e        /* 0 11111 10 sNaN            */\r
+    #define DECIMAL_Inf     0x78        /* 0 11110 00 Infinity        */\r
+  #endif\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Routines                                                         */\r
+  /* ---------------------------------------------------------------- */\r
+  /* String conversions                                               */\r
+  decimal128 * decimal128FromString(decimal128 *, const char *, decContext *);\r
+  char * decimal128ToString(const decimal128 *, char *);\r
+  char * decimal128ToEngString(const decimal128 *, char *);\r
+\r
+  /* decNumber conversions                                            */\r
+  decimal128 * decimal128FromNumber(decimal128 *, const decNumber *,\r
+                                    decContext *);\r
+  decNumber * decimal128ToNumber(const decimal128 *, decNumber *);\r
+\r
+  /* Format-dependent utilities                                       */\r
+  uint32_t    decimal128IsCanonical(const decimal128 *);\r
+  decimal128 * decimal128Canonical(decimal128 *, const decimal128 *);\r
+\r
+#endif\r
diff --git a/src/decNumber/decimal32.c b/src/decNumber/decimal32.c
new file mode 100644 (file)
index 0000000..775cffd
--- /dev/null
@@ -0,0 +1,476 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal 32-bit format module                                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2008.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises the routines for decimal32 format numbers.   */\r
+/* Conversions are supplied to and from decNumber and String.         */\r
+/*                                                                    */\r
+/* This is used when decNumber provides operations, either for all    */\r
+/* operations or as a proxy between decNumber and decSingle.          */\r
+/*                                                                    */\r
+/* Error handling is the same as decNumber (qv.).                     */\r
+/* ------------------------------------------------------------------ */\r
+#include <string.h>           // [for memset/memcpy]\r
+#include <stdio.h>            // [for printf]\r
+\r
+#define  DECNUMDIGITS  7      // make decNumbers with space for 7\r
+#include "decNumber.h"        // base number library\r
+#include "decNumberLocal.h"   // decNumber local types, etc.\r
+#include "decimal32.h"        // our primary include\r
+\r
+/* Utility tables and routines [in decimal64.c] */\r
+// DPD2BIN and the reverse are renamed to prevent link-time conflict\r
+// if decQuad is also built in the same executable\r
+#define DPD2BIN DPD2BINx\r
+#define BIN2DPD BIN2DPDx\r
+extern const uInt   COMBEXP[32], COMBMSD[32];\r
+extern const uShort DPD2BIN[1024];\r
+extern const uShort BIN2DPD[1000];\r
+extern const uByte  BIN2CHAR[4001];\r
+\r
+extern void decDigitsToDPD(const decNumber *, uInt *, Int);\r
+extern void decDigitsFromDPD(decNumber *, const uInt *, Int);\r
+\r
+#if DECTRACE || DECCHECK\r
+void decimal32Show(const decimal32 *);            // for debug\r
+extern void decNumberShow(const decNumber *);     // ..\r
+#endif\r
+\r
+/* Useful macro */\r
+// Clear a structure (e.g., a decNumber)\r
+#define DEC_clear(d) memset(d, 0, sizeof(*d))\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal32FromNumber -- convert decNumber to decimal32              */\r
+/*                                                                    */\r
+/*   ds is the target decimal32                                       */\r
+/*   dn is the source number (assumed valid)                          */\r
+/*   set is the context, used only for reporting errors               */\r
+/*                                                                    */\r
+/* The set argument is used only for status reporting and for the     */\r
+/* rounding mode (used if the coefficient is more than DECIMAL32_Pmax */\r
+/* digits or an overflow is detected).  If the exponent is out of the */\r
+/* valid range then Overflow or Underflow will be raised.             */\r
+/* After Underflow a subnormal result is possible.                    */\r
+/*                                                                    */\r
+/* DEC_Clamped is set if the number has to be 'folded down' to fit,   */\r
+/* by reducing its exponent and multiplying the coefficient by a      */\r
+/* power of ten, or if the exponent on a zero had to be clamped.      */\r
+/* ------------------------------------------------------------------ */\r
+decimal32 * decimal32FromNumber(decimal32 *d32, const decNumber *dn,\r
+                              decContext *set) {\r
+  uInt status=0;                   // status accumulator\r
+  Int ae;                          // adjusted exponent\r
+  decNumber  dw;                   // work\r
+  decContext dc;                   // ..\r
+  uInt comb, exp;                  // ..\r
+  uInt uiwork;                     // for macros\r
+  uInt targ=0;                     // target 32-bit\r
+\r
+  // If the number has too many digits, or the exponent could be\r
+  // out of range then reduce the number under the appropriate\r
+  // constraints.  This could push the number to Infinity or zero,\r
+  // so this check and rounding must be done before generating the\r
+  // decimal32]\r
+  ae=dn->exponent+dn->digits-1;              // [0 if special]\r
+  if (dn->digits>DECIMAL32_Pmax              // too many digits\r
+   || ae>DECIMAL32_Emax                      // likely overflow\r
+   || ae<DECIMAL32_Emin) {                   // likely underflow\r
+    decContextDefault(&dc, DEC_INIT_DECIMAL32); // [no traps]\r
+    dc.round=set->round;                     // use supplied rounding\r
+    decNumberPlus(&dw, dn, &dc);             // (round and check)\r
+    // [this changes -0 to 0, so enforce the sign...]\r
+    dw.bits|=dn->bits&DECNEG;\r
+    status=dc.status;                        // save status\r
+    dn=&dw;                                  // use the work number\r
+    } // maybe out of range\r
+\r
+  if (dn->bits&DECSPECIAL) {                      // a special value\r
+    if (dn->bits&DECINF) targ=DECIMAL_Inf<<24;\r
+     else {                                       // sNaN or qNaN\r
+      if ((*dn->lsu!=0 || dn->digits>1)           // non-zero coefficient\r
+       && (dn->digits<DECIMAL32_Pmax)) {          // coefficient fits\r
+        decDigitsToDPD(dn, &targ, 0);\r
+        }\r
+      if (dn->bits&DECNAN) targ|=DECIMAL_NaN<<24;\r
+       else targ|=DECIMAL_sNaN<<24;\r
+      } // a NaN\r
+    } // special\r
+\r
+   else { // is finite\r
+    if (decNumberIsZero(dn)) {               // is a zero\r
+      // set and clamp exponent\r
+      if (dn->exponent<-DECIMAL32_Bias) {\r
+        exp=0;                               // low clamp\r
+        status|=DEC_Clamped;\r
+        }\r
+       else {\r
+        exp=dn->exponent+DECIMAL32_Bias;     // bias exponent\r
+        if (exp>DECIMAL32_Ehigh) {           // top clamp\r
+          exp=DECIMAL32_Ehigh;\r
+          status|=DEC_Clamped;\r
+          }\r
+        }\r
+      comb=(exp>>3) & 0x18;             // msd=0, exp top 2 bits ..\r
+      }\r
+     else {                             // non-zero finite number\r
+      uInt msd;                         // work\r
+      Int pad=0;                        // coefficient pad digits\r
+\r
+      // the dn is known to fit, but it may need to be padded\r
+      exp=(uInt)(dn->exponent+DECIMAL32_Bias);    // bias exponent\r
+      if (exp>DECIMAL32_Ehigh) {                  // fold-down case\r
+        pad=exp-DECIMAL32_Ehigh;\r
+        exp=DECIMAL32_Ehigh;                      // [to maximum]\r
+        status|=DEC_Clamped;\r
+        }\r
+\r
+      // fastpath common case\r
+      if (DECDPUN==3 && pad==0) {\r
+        targ=BIN2DPD[dn->lsu[0]];\r
+        if (dn->digits>3) targ|=(uInt)(BIN2DPD[dn->lsu[1]])<<10;\r
+        msd=(dn->digits==7 ? dn->lsu[2] : 0);\r
+        }\r
+       else { // general case\r
+        decDigitsToDPD(dn, &targ, pad);\r
+        // save and clear the top digit\r
+        msd=targ>>20;\r
+        targ&=0x000fffff;\r
+        }\r
+\r
+      // create the combination field\r
+      if (msd>=8) comb=0x18 | ((exp>>5) & 0x06) | (msd & 0x01);\r
+             else comb=((exp>>3) & 0x18) | msd;\r
+      }\r
+    targ|=comb<<26;                // add combination field ..\r
+    targ|=(exp&0x3f)<<20;          // .. and exponent continuation\r
+    } // finite\r
+\r
+  if (dn->bits&DECNEG) targ|=0x80000000;  // add sign bit\r
+\r
+  // now write to storage; this is endian\r
+  UBFROMUI(d32->bytes, targ);      // directly store the int\r
+\r
+  if (status!=0) decContextSetStatus(set, status); // pass on status\r
+  // decimal32Show(d32);\r
+  return d32;\r
+  } // decimal32FromNumber\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal32ToNumber -- convert decimal32 to decNumber                */\r
+/*   d32 is the source decimal32                                      */\r
+/*   dn is the target number, with appropriate space                  */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decimal32ToNumber(const decimal32 *d32, decNumber *dn) {\r
+  uInt msd;                        // coefficient MSD\r
+  uInt exp;                        // exponent top two bits\r
+  uInt comb;                       // combination field\r
+  uInt sour;                       // source 32-bit\r
+  uInt uiwork;                     // for macros\r
+\r
+  // load source from storage; this is endian\r
+  sour=UBTOUI(d32->bytes);         // directly load the int\r
+\r
+  comb=(sour>>26)&0x1f;            // combination field\r
+\r
+  decNumberZero(dn);               // clean number\r
+  if (sour&0x80000000) dn->bits=DECNEG; // set sign if negative\r
+\r
+  msd=COMBMSD[comb];               // decode the combination field\r
+  exp=COMBEXP[comb];               // ..\r
+\r
+  if (exp==3) {                    // is a special\r
+    if (msd==0) {\r
+      dn->bits|=DECINF;\r
+      return dn;                   // no coefficient needed\r
+      }\r
+    else if (sour&0x02000000) dn->bits|=DECSNAN;\r
+    else dn->bits|=DECNAN;\r
+    msd=0;                         // no top digit\r
+    }\r
+   else {                          // is a finite number\r
+    dn->exponent=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; // unbiased\r
+    }\r
+\r
+  // get the coefficient\r
+  sour&=0x000fffff;                // clean coefficient continuation\r
+  if (msd) {                       // non-zero msd\r
+    sour|=msd<<20;                 // prefix to coefficient\r
+    decDigitsFromDPD(dn, &sour, 3); // process 3 declets\r
+    return dn;\r
+    }\r
+  // msd=0\r
+  if (!sour) return dn;            // easy: coefficient is 0\r
+  if (sour&0x000ffc00)             // need 2 declets?\r
+    decDigitsFromDPD(dn, &sour, 2); // process 2 declets\r
+   else\r
+    decDigitsFromDPD(dn, &sour, 1); // process 1 declet\r
+  return dn;\r
+  } // decimal32ToNumber\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* to-scientific-string -- conversion to numeric string               */\r
+/* to-engineering-string -- conversion to numeric string              */\r
+/*                                                                    */\r
+/*   decimal32ToString(d32, string);                                  */\r
+/*   decimal32ToEngString(d32, string);                               */\r
+/*                                                                    */\r
+/*  d32 is the decimal32 format number to convert                     */\r
+/*  string is the string where the result will be laid out            */\r
+/*                                                                    */\r
+/*  string must be at least 24 characters                             */\r
+/*                                                                    */\r
+/*  No error is possible, and no status can be set.                   */\r
+/* ------------------------------------------------------------------ */\r
+char * decimal32ToEngString(const decimal32 *d32, char *string){\r
+  decNumber dn;                         // work\r
+  decimal32ToNumber(d32, &dn);\r
+  decNumberToEngString(&dn, string);\r
+  return string;\r
+  } // decimal32ToEngString\r
+\r
+char * decimal32ToString(const decimal32 *d32, char *string){\r
+  uInt msd;                        // coefficient MSD\r
+  Int  exp;                        // exponent top two bits or full\r
+  uInt comb;                       // combination field\r
+  char *cstart;                    // coefficient start\r
+  char *c;                         // output pointer in string\r
+  const uByte *u;                  // work\r
+  char *s, *t;                     // .. (source, target)\r
+  Int  dpd;                        // ..\r
+  Int  pre, e;                     // ..\r
+  uInt uiwork;                     // for macros\r
+  uInt sour;                       // source 32-bit\r
+\r
+  // load source from storage; this is endian\r
+  sour=UBTOUI(d32->bytes);         // directly load the int\r
+\r
+  c=string;                        // where result will go\r
+  if (((Int)sour)<0) *c++='-';     // handle sign\r
+\r
+  comb=(sour>>26)&0x1f;            // combination field\r
+  msd=COMBMSD[comb];               // decode the combination field\r
+  exp=COMBEXP[comb];               // ..\r
+\r
+  if (exp==3) {\r
+    if (msd==0) {                  // infinity\r
+      strcpy(c,   "Inf");\r
+      strcpy(c+3, "inity");\r
+      return string;               // easy\r
+      }\r
+    if (sour&0x02000000) *c++='s'; // sNaN\r
+    strcpy(c, "NaN");              // complete word\r
+    c+=3;                          // step past\r
+    if ((sour&0x000fffff)==0) return string; // zero payload\r
+    // otherwise drop through to add integer; set correct exp\r
+    exp=0; msd=0;                  // setup for following code\r
+    }\r
+   else exp=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; // unbiased\r
+\r
+  // convert 7 digits of significand to characters\r
+  cstart=c;                        // save start of coefficient\r
+  if (msd) *c++='0'+(char)msd;     // non-zero most significant digit\r
+\r
+  // Now decode the declets.  After extracting each one, it is\r
+  // decoded to binary and then to a 4-char sequence by table lookup;\r
+  // the 4-chars are a 1-char length (significant digits, except 000\r
+  // has length 0).  This allows us to left-align the first declet\r
+  // with non-zero content, then remaining ones are full 3-char\r
+  // length.  We use fixed-length memcpys because variable-length\r
+  // causes a subroutine call in GCC.  (These are length 4 for speed\r
+  // and are safe because the array has an extra terminator byte.)\r
+  #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4];                   \\r
+                   if (c!=cstart) {memcpy(c, u+1, 4); c+=3;}      \\r
+                    else if (*u)  {memcpy(c, u+4-*u, 4); c+=*u;}\r
+\r
+  dpd=(sour>>10)&0x3ff;            // declet 1\r
+  dpd2char;\r
+  dpd=(sour)&0x3ff;                // declet 2\r
+  dpd2char;\r
+\r
+  if (c==cstart) *c++='0';         // all zeros -- make 0\r
+\r
+  if (exp==0) {                    // integer or NaN case -- easy\r
+    *c='\0';                       // terminate\r
+    return string;\r
+    }\r
+\r
+  /* non-0 exponent */\r
+  e=0;                             // assume no E\r
+  pre=c-cstart+exp;\r
+  // [here, pre-exp is the digits count (==1 for zero)]\r
+  if (exp>0 || pre<-5) {           // need exponential form\r
+    e=pre-1;                       // calculate E value\r
+    pre=1;                         // assume one digit before '.'\r
+    } // exponential form\r
+\r
+  /* modify the coefficient, adding 0s, '.', and E+nn as needed */\r
+  s=c-1;                           // source (LSD)\r
+  if (pre>0) {                     // ddd.ddd (plain), perhaps with E\r
+    char *dotat=cstart+pre;\r
+    if (dotat<c) {                 // if embedded dot needed...\r
+      t=c;                              // target\r
+      for (; s>=dotat; s--, t--) *t=*s; // open the gap; leave t at gap\r
+      *t='.';                           // insert the dot\r
+      c++;                              // length increased by one\r
+      }\r
+\r
+    // finally add the E-part, if needed; it will never be 0, and has\r
+    // a maximum length of 3 digits (E-101 case)\r
+    if (e!=0) {\r
+      *c++='E';                    // starts with E\r
+      *c++='+';                    // assume positive\r
+      if (e<0) {\r
+        *(c-1)='-';                // oops, need '-'\r
+        e=-e;                      // uInt, please\r
+        }\r
+      u=&BIN2CHAR[e*4];            // -> length byte\r
+      memcpy(c, u+4-*u, 4);        // copy fixed 4 characters [is safe]\r
+      c+=*u;                       // bump pointer appropriately\r
+      }\r
+    *c='\0';                       // add terminator\r
+    //printf("res %s\n", string);\r
+    return string;\r
+    } // pre>0\r
+\r
+  /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */\r
+  t=c+1-pre;\r
+  *(t+1)='\0';                          // can add terminator now\r
+  for (; s>=cstart; s--, t--) *t=*s;    // shift whole coefficient right\r
+  c=cstart;\r
+  *c++='0';                             // always starts with 0.\r
+  *c++='.';\r
+  for (; pre<0; pre++) *c++='0';        // add any 0's after '.'\r
+  //printf("res %s\n", string);\r
+  return string;\r
+  } // decimal32ToString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* to-number -- conversion from numeric string                        */\r
+/*                                                                    */\r
+/*   decimal32FromString(result, string, set);                        */\r
+/*                                                                    */\r
+/*  result  is the decimal32 format number which gets the result of   */\r
+/*          the conversion                                            */\r
+/*  *string is the character string which should contain a valid      */\r
+/*          number (which may be a special value)                     */\r
+/*  set     is the context                                            */\r
+/*                                                                    */\r
+/* The context is supplied to this routine is used for error handling */\r
+/* (setting of status and traps) and for the rounding mode, only.     */\r
+/* If an error occurs, the result will be a valid decimal32 NaN.      */\r
+/* ------------------------------------------------------------------ */\r
+decimal32 * decimal32FromString(decimal32 *result, const char *string,\r
+                                decContext *set) {\r
+  decContext dc;                             // work\r
+  decNumber dn;                              // ..\r
+\r
+  decContextDefault(&dc, DEC_INIT_DECIMAL32); // no traps, please\r
+  dc.round=set->round;                        // use supplied rounding\r
+\r
+  decNumberFromString(&dn, string, &dc);     // will round if needed\r
+  decimal32FromNumber(result, &dn, &dc);\r
+  if (dc.status!=0) {                        // something happened\r
+    decContextSetStatus(set, dc.status);     // .. pass it on\r
+    }\r
+  return result;\r
+  } // decimal32FromString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal32IsCanonical -- test whether encoding is canonical         */\r
+/*   d32 is the source decimal32                                      */\r
+/*   returns 1 if the encoding of d32 is canonical, 0 otherwise       */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+uInt decimal32IsCanonical(const decimal32 *d32) {\r
+  decNumber dn;                         // work\r
+  decimal32 canon;                      // ..\r
+  decContext dc;                        // ..\r
+  decContextDefault(&dc, DEC_INIT_DECIMAL32);\r
+  decimal32ToNumber(d32, &dn);\r
+  decimal32FromNumber(&canon, &dn, &dc);// canon will now be canonical\r
+  return memcmp(d32, &canon, DECIMAL32_Bytes)==0;\r
+  } // decimal32IsCanonical\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal32Canonical -- copy an encoding, ensuring it is canonical   */\r
+/*   d32 is the source decimal32                                      */\r
+/*   result is the target (may be the same decimal32)                 */\r
+/*   returns result                                                   */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decimal32 * decimal32Canonical(decimal32 *result, const decimal32 *d32) {\r
+  decNumber dn;                         // work\r
+  decContext dc;                        // ..\r
+  decContextDefault(&dc, DEC_INIT_DECIMAL32);\r
+  decimal32ToNumber(d32, &dn);\r
+  decimal32FromNumber(result, &dn, &dc);// result will now be canonical\r
+  return result;\r
+  } // decimal32Canonical\r
+\r
+#if DECTRACE || DECCHECK\r
+/* Macros for accessing decimal32 fields.  These assume the argument\r
+   is a reference (pointer) to the decimal32 structure, and the\r
+   decimal32 is in network byte order (big-endian) */\r
+// Get sign\r
+#define decimal32Sign(d)       ((unsigned)(d)->bytes[0]>>7)\r
+\r
+// Get combination field\r
+#define decimal32Comb(d)       (((d)->bytes[0] & 0x7c)>>2)\r
+\r
+// Get exponent continuation [does not remove bias]\r
+#define decimal32ExpCon(d)     ((((d)->bytes[0] & 0x03)<<4)           \\r
+                             | ((unsigned)(d)->bytes[1]>>4))\r
+\r
+// Set sign [this assumes sign previously 0]\r
+#define decimal32SetSign(d, b) {                                      \\r
+  (d)->bytes[0]|=((unsigned)(b)<<7);}\r
+\r
+// Set exponent continuation [does not apply bias]\r
+// This assumes range has been checked and exponent previously 0;\r
+// type of exponent must be unsigned\r
+#define decimal32SetExpCon(d, e) {                                    \\r
+  (d)->bytes[0]|=(uByte)((e)>>4);                                     \\r
+  (d)->bytes[1]|=(uByte)(((e)&0x0F)<<4);}\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal32Show -- display a decimal32 in hexadecimal [debug aid]    */\r
+/*   d32 -- the number to show                                        */\r
+/* ------------------------------------------------------------------ */\r
+// Also shows sign/cob/expconfields extracted - valid bigendian only\r
+void decimal32Show(const decimal32 *d32) {\r
+  char buf[DECIMAL32_Bytes*2+1];\r
+  Int i, j=0;\r
+\r
+  if (DECLITEND) {\r
+    for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {\r
+      sprintf(&buf[j], "%02x", d32->bytes[3-i]);\r
+      }\r
+    printf(" D32> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,\r
+           d32->bytes[3]>>7, (d32->bytes[3]>>2)&0x1f,\r
+           ((d32->bytes[3]&0x3)<<4)| (d32->bytes[2]>>4));\r
+    }\r
+   else {\r
+    for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {\r
+      sprintf(&buf[j], "%02x", d32->bytes[i]);\r
+      }\r
+    printf(" D32> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,\r
+           decimal32Sign(d32), decimal32Comb(d32), decimal32ExpCon(d32));\r
+    }\r
+  } // decimal32Show\r
+#endif\r
diff --git a/src/decNumber/decimal32.h b/src/decNumber/decimal32.h
new file mode 100644 (file)
index 0000000..060640e
--- /dev/null
@@ -0,0 +1,81 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal 32-bit format module header                                */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2006.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#if !defined(DECIMAL32)\r
+  #define DECIMAL32\r
+  #define DEC32NAME     "decimal32"                   /* Short name   */\r
+  #define DEC32FULLNAME "Decimal 32-bit Number"       /* Verbose name */\r
+  #define DEC32AUTHOR   "Mike Cowlishaw"              /* Who to blame */\r
+\r
+  /* parameters for decimal32s */\r
+  #define DECIMAL32_Bytes  4            /* length                     */\r
+  #define DECIMAL32_Pmax   7            /* maximum precision (digits) */\r
+  #define DECIMAL32_Emax   96           /* maximum adjusted exponent  */\r
+  #define DECIMAL32_Emin  -95           /* minimum adjusted exponent  */\r
+  #define DECIMAL32_Bias   101          /* bias for the exponent      */\r
+  #define DECIMAL32_String 15           /* maximum string length, +1  */\r
+  #define DECIMAL32_EconL  6            /* exp. continuation length   */\r
+  /* highest biased exponent (Elimit-1)                               */\r
+  #define DECIMAL32_Ehigh  (DECIMAL32_Emax+DECIMAL32_Bias-DECIMAL32_Pmax+1)\r
+\r
+  /* check enough digits, if pre-defined                              */\r
+  #if defined(DECNUMDIGITS)\r
+    #if (DECNUMDIGITS<DECIMAL32_Pmax)\r
+      #error decimal32.h needs pre-defined DECNUMDIGITS>=7 for safe use\r
+    #endif\r
+  #endif\r
+\r
+  #ifndef DECNUMDIGITS\r
+    #define DECNUMDIGITS DECIMAL32_Pmax /* size if not already defined*/\r
+  #endif\r
+  #ifndef DECNUMBER\r
+    #include "decNumber.h"              /* context and number library */\r
+  #endif\r
+\r
+  /* Decimal 32-bit type, accessible by bytes */\r
+  typedef struct {\r
+    uint8_t bytes[DECIMAL32_Bytes];     /* decimal32: 1, 5, 6, 20 bits*/\r
+    } decimal32;\r
+\r
+  /* special values [top byte excluding sign bit; last two bits are   */\r
+  /* don't-care for Infinity on input, last bit don't-care for NaN]   */\r
+  #if !defined(DECIMAL_NaN)\r
+    #define DECIMAL_NaN     0x7c        /* 0 11111 00 NaN             */\r
+    #define DECIMAL_sNaN    0x7e        /* 0 11111 10 sNaN            */\r
+    #define DECIMAL_Inf     0x78        /* 0 11110 00 Infinity        */\r
+  #endif\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Routines                                                         */\r
+  /* ---------------------------------------------------------------- */\r
+  /* String conversions                                               */\r
+  decimal32 * decimal32FromString(decimal32 *, const char *, decContext *);\r
+  char * decimal32ToString(const decimal32 *, char *);\r
+  char * decimal32ToEngString(const decimal32 *, char *);\r
+\r
+  /* decNumber conversions                                            */\r
+  decimal32 * decimal32FromNumber(decimal32 *, const decNumber *,\r
+                                  decContext *);\r
+  decNumber * decimal32ToNumber(const decimal32 *, decNumber *);\r
+\r
+  /* Format-dependent utilities                                       */\r
+  uint32_t    decimal32IsCanonical(const decimal32 *);\r
+  decimal32 * decimal32Canonical(decimal32 *, const decimal32 *);\r
+\r
+#endif\r
diff --git a/src/decNumber/decimal64.c b/src/decNumber/decimal64.c
new file mode 100644 (file)
index 0000000..a21f42f
--- /dev/null
@@ -0,0 +1,839 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal 64-bit format module                                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2009.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+/* This module comprises the routines for decimal64 format numbers.   */\r
+/* Conversions are supplied to and from decNumber and String.         */\r
+/*                                                                    */\r
+/* This is used when decNumber provides operations, either for all    */\r
+/* operations or as a proxy between decNumber and decSingle.          */\r
+/*                                                                    */\r
+/* Error handling is the same as decNumber (qv.).                     */\r
+/* ------------------------------------------------------------------ */\r
+#include <string.h>           // [for memset/memcpy]\r
+#include <stdio.h>            // [for printf]\r
+\r
+#define  DECNUMDIGITS 16      // make decNumbers with space for 16\r
+#include "decNumber.h"        // base number library\r
+#include "decNumberLocal.h"   // decNumber local types, etc.\r
+#include "decimal64.h"        // our primary include\r
+\r
+/* Utility routines and tables [in decimal64.c]; externs for C++ */\r
+// DPD2BIN and the reverse are renamed to prevent link-time conflict\r
+// if decQuad is also built in the same executable\r
+#define DPD2BIN DPD2BINx\r
+#define BIN2DPD BIN2DPDx\r
+extern const uInt COMBEXP[32], COMBMSD[32];\r
+extern const uShort DPD2BIN[1024];\r
+extern const uShort BIN2DPD[1000];\r
+extern const uByte  BIN2CHAR[4001];\r
+\r
+extern void decDigitsFromDPD(decNumber *, const uInt *, Int);\r
+extern void decDigitsToDPD(const decNumber *, uInt *, Int);\r
+\r
+#if DECTRACE || DECCHECK\r
+void decimal64Show(const decimal64 *);            // for debug\r
+extern void decNumberShow(const decNumber *);     // ..\r
+#endif\r
+\r
+/* Useful macro */\r
+// Clear a structure (e.g., a decNumber)\r
+#define DEC_clear(d) memset(d, 0, sizeof(*d))\r
+\r
+/* define and include the tables to use for conversions */\r
+#define DEC_BIN2CHAR 1\r
+#define DEC_DPD2BIN  1\r
+#define DEC_BIN2DPD  1             // used for all sizes\r
+#include "decDPD.h"                // lookup tables\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal64FromNumber -- convert decNumber to decimal64              */\r
+/*                                                                    */\r
+/*   ds is the target decimal64                                       */\r
+/*   dn is the source number (assumed valid)                          */\r
+/*   set is the context, used only for reporting errors               */\r
+/*                                                                    */\r
+/* The set argument is used only for status reporting and for the     */\r
+/* rounding mode (used if the coefficient is more than DECIMAL64_Pmax */\r
+/* digits or an overflow is detected).  If the exponent is out of the */\r
+/* valid range then Overflow or Underflow will be raised.             */\r
+/* After Underflow a subnormal result is possible.                    */\r
+/*                                                                    */\r
+/* DEC_Clamped is set if the number has to be 'folded down' to fit,   */\r
+/* by reducing its exponent and multiplying the coefficient by a      */\r
+/* power of ten, or if the exponent on a zero had to be clamped.      */\r
+/* ------------------------------------------------------------------ */\r
+decimal64 * decimal64FromNumber(decimal64 *d64, const decNumber *dn,\r
+                                decContext *set) {\r
+  uInt status=0;                   // status accumulator\r
+  Int ae;                          // adjusted exponent\r
+  decNumber  dw;                   // work\r
+  decContext dc;                   // ..\r
+  uInt comb, exp;                  // ..\r
+  uInt uiwork;                     // for macros\r
+  uInt targar[2]={0, 0};           // target 64-bit\r
+  #define targhi targar[1]         // name the word with the sign\r
+  #define targlo targar[0]         // and the other\r
+\r
+  // If the number has too many digits, or the exponent could be\r
+  // out of range then reduce the number under the appropriate\r
+  // constraints.  This could push the number to Infinity or zero,\r
+  // so this check and rounding must be done before generating the\r
+  // decimal64]\r
+  ae=dn->exponent+dn->digits-1;              // [0 if special]\r
+  if (dn->digits>DECIMAL64_Pmax              // too many digits\r
+   || ae>DECIMAL64_Emax                      // likely overflow\r
+   || ae<DECIMAL64_Emin) {                   // likely underflow\r
+    decContextDefault(&dc, DEC_INIT_DECIMAL64); // [no traps]\r
+    dc.round=set->round;                     // use supplied rounding\r
+    decNumberPlus(&dw, dn, &dc);             // (round and check)\r
+    // [this changes -0 to 0, so enforce the sign...]\r
+    dw.bits|=dn->bits&DECNEG;\r
+    status=dc.status;                        // save status\r
+    dn=&dw;                                  // use the work number\r
+    } // maybe out of range\r
+\r
+  if (dn->bits&DECSPECIAL) {                      // a special value\r
+    if (dn->bits&DECINF) targhi=DECIMAL_Inf<<24;\r
+     else {                                       // sNaN or qNaN\r
+      if ((*dn->lsu!=0 || dn->digits>1)           // non-zero coefficient\r
+       && (dn->digits<DECIMAL64_Pmax)) {          // coefficient fits\r
+        decDigitsToDPD(dn, targar, 0);\r
+        }\r
+      if (dn->bits&DECNAN) targhi|=DECIMAL_NaN<<24;\r
+       else targhi|=DECIMAL_sNaN<<24;\r
+      } // a NaN\r
+    } // special\r
+\r
+   else { // is finite\r
+    if (decNumberIsZero(dn)) {               // is a zero\r
+      // set and clamp exponent\r
+      if (dn->exponent<-DECIMAL64_Bias) {\r
+        exp=0;                               // low clamp\r
+        status|=DEC_Clamped;\r
+        }\r
+       else {\r
+        exp=dn->exponent+DECIMAL64_Bias;     // bias exponent\r
+        if (exp>DECIMAL64_Ehigh) {           // top clamp\r
+          exp=DECIMAL64_Ehigh;\r
+          status|=DEC_Clamped;\r
+          }\r
+        }\r
+      comb=(exp>>5) & 0x18;             // msd=0, exp top 2 bits ..\r
+      }\r
+     else {                             // non-zero finite number\r
+      uInt msd;                         // work\r
+      Int pad=0;                        // coefficient pad digits\r
+\r
+      // the dn is known to fit, but it may need to be padded\r
+      exp=(uInt)(dn->exponent+DECIMAL64_Bias);    // bias exponent\r
+      if (exp>DECIMAL64_Ehigh) {                  // fold-down case\r
+        pad=exp-DECIMAL64_Ehigh;\r
+        exp=DECIMAL64_Ehigh;                      // [to maximum]\r
+        status|=DEC_Clamped;\r
+        }\r
+\r
+      // fastpath common case\r
+      if (DECDPUN==3 && pad==0) {\r
+        uInt dpd[6]={0,0,0,0,0,0};\r
+        uInt i;\r
+        Int d=dn->digits;\r
+        for (i=0; d>0; i++, d-=3) dpd[i]=BIN2DPD[dn->lsu[i]];\r
+        targlo =dpd[0];\r
+        targlo|=dpd[1]<<10;\r
+        targlo|=dpd[2]<<20;\r
+        if (dn->digits>6) {\r
+          targlo|=dpd[3]<<30;\r
+          targhi =dpd[3]>>2;\r
+          targhi|=dpd[4]<<8;\r
+          }\r
+        msd=dpd[5];                // [did not really need conversion]\r
+        }\r
+       else { // general case\r
+        decDigitsToDPD(dn, targar, pad);\r
+        // save and clear the top digit\r
+        msd=targhi>>18;\r
+        targhi&=0x0003ffff;\r
+        }\r
+\r
+      // create the combination field\r
+      if (msd>=8) comb=0x18 | ((exp>>7) & 0x06) | (msd & 0x01);\r
+             else comb=((exp>>5) & 0x18) | msd;\r
+      }\r
+    targhi|=comb<<26;              // add combination field ..\r
+    targhi|=(exp&0xff)<<18;        // .. and exponent continuation\r
+    } // finite\r
+\r
+  if (dn->bits&DECNEG) targhi|=0x80000000; // add sign bit\r
+\r
+  // now write to storage; this is now always endian\r
+  if (DECLITEND) {\r
+    // lo int then hi\r
+    UBFROMUI(d64->bytes,   targar[0]);\r
+    UBFROMUI(d64->bytes+4, targar[1]);\r
+    }\r
+   else {\r
+    // hi int then lo\r
+    UBFROMUI(d64->bytes,   targar[1]);\r
+    UBFROMUI(d64->bytes+4, targar[0]);\r
+    }\r
+\r
+  if (status!=0) decContextSetStatus(set, status); // pass on status\r
+  // decimal64Show(d64);\r
+  return d64;\r
+  } // decimal64FromNumber\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal64ToNumber -- convert decimal64 to decNumber                */\r
+/*   d64 is the source decimal64                                      */\r
+/*   dn is the target number, with appropriate space                  */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decNumber * decimal64ToNumber(const decimal64 *d64, decNumber *dn) {\r
+  uInt msd;                        // coefficient MSD\r
+  uInt exp;                        // exponent top two bits\r
+  uInt comb;                       // combination field\r
+  Int  need;                       // work\r
+  uInt uiwork;                     // for macros\r
+  uInt sourar[2];                  // source 64-bit\r
+  #define sourhi sourar[1]         // name the word with the sign\r
+  #define sourlo sourar[0]         // and the lower word\r
+\r
+  // load source from storage; this is endian\r
+  if (DECLITEND) {\r
+    sourlo=UBTOUI(d64->bytes  );   // directly load the low int\r
+    sourhi=UBTOUI(d64->bytes+4);   // then the high int\r
+    }\r
+   else {\r
+    sourhi=UBTOUI(d64->bytes  );   // directly load the high int\r
+    sourlo=UBTOUI(d64->bytes+4);   // then the low int\r
+    }\r
+\r
+  comb=(sourhi>>26)&0x1f;          // combination field\r
+\r
+  decNumberZero(dn);               // clean number\r
+  if (sourhi&0x80000000) dn->bits=DECNEG; // set sign if negative\r
+\r
+  msd=COMBMSD[comb];               // decode the combination field\r
+  exp=COMBEXP[comb];               // ..\r
+\r
+  if (exp==3) {                    // is a special\r
+    if (msd==0) {\r
+      dn->bits|=DECINF;\r
+      return dn;                   // no coefficient needed\r
+      }\r
+    else if (sourhi&0x02000000) dn->bits|=DECSNAN;\r
+    else dn->bits|=DECNAN;\r
+    msd=0;                         // no top digit\r
+    }\r
+   else {                          // is a finite number\r
+    dn->exponent=(exp<<8)+((sourhi>>18)&0xff)-DECIMAL64_Bias; // unbiased\r
+    }\r
+\r
+  // get the coefficient\r
+  sourhi&=0x0003ffff;              // clean coefficient continuation\r
+  if (msd) {                       // non-zero msd\r
+    sourhi|=msd<<18;               // prefix to coefficient\r
+    need=6;                        // process 6 declets\r
+    }\r
+   else { // msd=0\r
+    if (!sourhi) {                 // top word 0\r
+      if (!sourlo) return dn;      // easy: coefficient is 0\r
+      need=3;                      // process at least 3 declets\r
+      if (sourlo&0xc0000000) need++; // process 4 declets\r
+      // [could reduce some more, here]\r
+      }\r
+     else {                        // some bits in top word, msd=0\r
+      need=4;                      // process at least 4 declets\r
+      if (sourhi&0x0003ff00) need++; // top declet!=0, process 5\r
+      }\r
+    } //msd=0\r
+\r
+  decDigitsFromDPD(dn, sourar, need);   // process declets\r
+  return dn;\r
+  } // decimal64ToNumber\r
+\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* to-scientific-string -- conversion to numeric string               */\r
+/* to-engineering-string -- conversion to numeric string              */\r
+/*                                                                    */\r
+/*   decimal64ToString(d64, string);                                  */\r
+/*   decimal64ToEngString(d64, string);                               */\r
+/*                                                                    */\r
+/*  d64 is the decimal64 format number to convert                     */\r
+/*  string is the string where the result will be laid out            */\r
+/*                                                                    */\r
+/*  string must be at least 24 characters                             */\r
+/*                                                                    */\r
+/*  No error is possible, and no status can be set.                   */\r
+/* ------------------------------------------------------------------ */\r
+char * decimal64ToEngString(const decimal64 *d64, char *string){\r
+  decNumber dn;                         // work\r
+  decimal64ToNumber(d64, &dn);\r
+  decNumberToEngString(&dn, string);\r
+  return string;\r
+  } // decimal64ToEngString\r
+\r
+char * decimal64ToString(const decimal64 *d64, char *string){\r
+  uInt msd;                        // coefficient MSD\r
+  Int  exp;                        // exponent top two bits or full\r
+  uInt comb;                       // combination field\r
+  char *cstart;                    // coefficient start\r
+  char *c;                         // output pointer in string\r
+  const uByte *u;                  // work\r
+  char *s, *t;                     // .. (source, target)\r
+  Int  dpd;                        // ..\r
+  Int  pre, e;                     // ..\r
+  uInt uiwork;                     // for macros\r
+\r
+  uInt sourar[2];                  // source 64-bit\r
+  #define sourhi sourar[1]         // name the word with the sign\r
+  #define sourlo sourar[0]         // and the lower word\r
+\r
+  // load source from storage; this is endian\r
+  if (DECLITEND) {\r
+    sourlo=UBTOUI(d64->bytes  );   // directly load the low int\r
+    sourhi=UBTOUI(d64->bytes+4);   // then the high int\r
+    }\r
+   else {\r
+    sourhi=UBTOUI(d64->bytes  );   // directly load the high int\r
+    sourlo=UBTOUI(d64->bytes+4);   // then the low int\r
+    }\r
+\r
+  c=string;                        // where result will go\r
+  if (((Int)sourhi)<0) *c++='-';   // handle sign\r
+\r
+  comb=(sourhi>>26)&0x1f;          // combination field\r
+  msd=COMBMSD[comb];               // decode the combination field\r
+  exp=COMBEXP[comb];               // ..\r
+\r
+  if (exp==3) {\r
+    if (msd==0) {                  // infinity\r
+      strcpy(c,   "Inf");\r
+      strcpy(c+3, "inity");\r
+      return string;               // easy\r
+      }\r
+    if (sourhi&0x02000000) *c++='s'; // sNaN\r
+    strcpy(c, "NaN");              // complete word\r
+    c+=3;                          // step past\r
+    if (sourlo==0 && (sourhi&0x0003ffff)==0) return string; // zero payload\r
+    // otherwise drop through to add integer; set correct exp\r
+    exp=0; msd=0;                  // setup for following code\r
+    }\r
+   else exp=(exp<<8)+((sourhi>>18)&0xff)-DECIMAL64_Bias;\r
+\r
+  // convert 16 digits of significand to characters\r
+  cstart=c;                        // save start of coefficient\r
+  if (msd) *c++='0'+(char)msd;     // non-zero most significant digit\r
+\r
+  // Now decode the declets.  After extracting each one, it is\r
+  // decoded to binary and then to a 4-char sequence by table lookup;\r
+  // the 4-chars are a 1-char length (significant digits, except 000\r
+  // has length 0).  This allows us to left-align the first declet\r
+  // with non-zero content, then remaining ones are full 3-char\r
+  // length.  We use fixed-length memcpys because variable-length\r
+  // causes a subroutine call in GCC.  (These are length 4 for speed\r
+  // and are safe because the array has an extra terminator byte.)\r
+  #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4];                   \\r
+                   if (c!=cstart) {memcpy(c, u+1, 4); c+=3;}      \\r
+                    else if (*u)  {memcpy(c, u+4-*u, 4); c+=*u;}\r
+\r
+  dpd=(sourhi>>8)&0x3ff;                     // declet 1\r
+  dpd2char;\r
+  dpd=((sourhi&0xff)<<2) | (sourlo>>30);     // declet 2\r
+  dpd2char;\r
+  dpd=(sourlo>>20)&0x3ff;                    // declet 3\r
+  dpd2char;\r
+  dpd=(sourlo>>10)&0x3ff;                    // declet 4\r
+  dpd2char;\r
+  dpd=(sourlo)&0x3ff;                        // declet 5\r
+  dpd2char;\r
+\r
+  if (c==cstart) *c++='0';         // all zeros -- make 0\r
+\r
+  if (exp==0) {                    // integer or NaN case -- easy\r
+    *c='\0';                       // terminate\r
+    return string;\r
+    }\r
+\r
+  /* non-0 exponent */\r
+  e=0;                             // assume no E\r
+  pre=c-cstart+exp;\r
+  // [here, pre-exp is the digits count (==1 for zero)]\r
+  if (exp>0 || pre<-5) {           // need exponential form\r
+    e=pre-1;                       // calculate E value\r
+    pre=1;                         // assume one digit before '.'\r
+    } // exponential form\r
+\r
+  /* modify the coefficient, adding 0s, '.', and E+nn as needed */\r
+  s=c-1;                           // source (LSD)\r
+  if (pre>0) {                     // ddd.ddd (plain), perhaps with E\r
+    char *dotat=cstart+pre;\r
+    if (dotat<c) {                 // if embedded dot needed...\r
+      t=c;                              // target\r
+      for (; s>=dotat; s--, t--) *t=*s; // open the gap; leave t at gap\r
+      *t='.';                           // insert the dot\r
+      c++;                              // length increased by one\r
+      }\r
+\r
+    // finally add the E-part, if needed; it will never be 0, and has\r
+    // a maximum length of 3 digits\r
+    if (e!=0) {\r
+      *c++='E';                    // starts with E\r
+      *c++='+';                    // assume positive\r
+      if (e<0) {\r
+        *(c-1)='-';                // oops, need '-'\r
+        e=-e;                      // uInt, please\r
+        }\r
+      u=&BIN2CHAR[e*4];            // -> length byte\r
+      memcpy(c, u+4-*u, 4);        // copy fixed 4 characters [is safe]\r
+      c+=*u;                       // bump pointer appropriately\r
+      }\r
+    *c='\0';                       // add terminator\r
+    //printf("res %s\n", string);\r
+    return string;\r
+    } // pre>0\r
+\r
+  /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */\r
+  t=c+1-pre;\r
+  *(t+1)='\0';                          // can add terminator now\r
+  for (; s>=cstart; s--, t--) *t=*s;    // shift whole coefficient right\r
+  c=cstart;\r
+  *c++='0';                             // always starts with 0.\r
+  *c++='.';\r
+  for (; pre<0; pre++) *c++='0';        // add any 0's after '.'\r
+  //printf("res %s\n", string);\r
+  return string;\r
+  } // decimal64ToString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* to-number -- conversion from numeric string                        */\r
+/*                                                                    */\r
+/*   decimal64FromString(result, string, set);                        */\r
+/*                                                                    */\r
+/*  result  is the decimal64 format number which gets the result of   */\r
+/*          the conversion                                            */\r
+/*  *string is the character string which should contain a valid      */\r
+/*          number (which may be a special value)                     */\r
+/*  set     is the context                                            */\r
+/*                                                                    */\r
+/* The context is supplied to this routine is used for error handling */\r
+/* (setting of status and traps) and for the rounding mode, only.     */\r
+/* If an error occurs, the result will be a valid decimal64 NaN.      */\r
+/* ------------------------------------------------------------------ */\r
+decimal64 * decimal64FromString(decimal64 *result, const char *string,\r
+                                decContext *set) {\r
+  decContext dc;                             // work\r
+  decNumber dn;                              // ..\r
+\r
+  decContextDefault(&dc, DEC_INIT_DECIMAL64); // no traps, please\r
+  dc.round=set->round;                        // use supplied rounding\r
+\r
+  decNumberFromString(&dn, string, &dc);     // will round if needed\r
+\r
+  decimal64FromNumber(result, &dn, &dc);\r
+  if (dc.status!=0) {                        // something happened\r
+    decContextSetStatus(set, dc.status);     // .. pass it on\r
+    }\r
+  return result;\r
+  } // decimal64FromString\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal64IsCanonical -- test whether encoding is canonical         */\r
+/*   d64 is the source decimal64                                      */\r
+/*   returns 1 if the encoding of d64 is canonical, 0 otherwise       */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+uInt decimal64IsCanonical(const decimal64 *d64) {\r
+  decNumber dn;                         // work\r
+  decimal64 canon;                      // ..\r
+  decContext dc;                        // ..\r
+  decContextDefault(&dc, DEC_INIT_DECIMAL64);\r
+  decimal64ToNumber(d64, &dn);\r
+  decimal64FromNumber(&canon, &dn, &dc);// canon will now be canonical\r
+  return memcmp(d64, &canon, DECIMAL64_Bytes)==0;\r
+  } // decimal64IsCanonical\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal64Canonical -- copy an encoding, ensuring it is canonical   */\r
+/*   d64 is the source decimal64                                      */\r
+/*   result is the target (may be the same decimal64)                 */\r
+/*   returns result                                                   */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+decimal64 * decimal64Canonical(decimal64 *result, const decimal64 *d64) {\r
+  decNumber dn;                         // work\r
+  decContext dc;                        // ..\r
+  decContextDefault(&dc, DEC_INIT_DECIMAL64);\r
+  decimal64ToNumber(d64, &dn);\r
+  decimal64FromNumber(result, &dn, &dc);// result will now be canonical\r
+  return result;\r
+  } // decimal64Canonical\r
+\r
+#if DECTRACE || DECCHECK\r
+/* Macros for accessing decimal64 fields.  These assume the\r
+   argument is a reference (pointer) to the decimal64 structure,\r
+   and the decimal64 is in network byte order (big-endian) */\r
+// Get sign\r
+#define decimal64Sign(d)       ((unsigned)(d)->bytes[0]>>7)\r
+\r
+// Get combination field\r
+#define decimal64Comb(d)       (((d)->bytes[0] & 0x7c)>>2)\r
+\r
+// Get exponent continuation [does not remove bias]\r
+#define decimal64ExpCon(d)     ((((d)->bytes[0] & 0x03)<<6)           \\r
+                             | ((unsigned)(d)->bytes[1]>>2))\r
+\r
+// Set sign [this assumes sign previously 0]\r
+#define decimal64SetSign(d, b) {                                      \\r
+  (d)->bytes[0]|=((unsigned)(b)<<7);}\r
+\r
+// Set exponent continuation [does not apply bias]\r
+// This assumes range has been checked and exponent previously 0;\r
+// type of exponent must be unsigned\r
+#define decimal64SetExpCon(d, e) {                                    \\r
+  (d)->bytes[0]|=(uByte)((e)>>6);                                     \\r
+  (d)->bytes[1]|=(uByte)(((e)&0x3F)<<2);}\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decimal64Show -- display a decimal64 in hexadecimal [debug aid]    */\r
+/*   d64 -- the number to show                                        */\r
+/* ------------------------------------------------------------------ */\r
+// Also shows sign/cob/expconfields extracted\r
+void decimal64Show(const decimal64 *d64) {\r
+  char buf[DECIMAL64_Bytes*2+1];\r
+  Int i, j=0;\r
+\r
+  if (DECLITEND) {\r
+    for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {\r
+      sprintf(&buf[j], "%02x", d64->bytes[7-i]);\r
+      }\r
+    printf(" D64> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,\r
+           d64->bytes[7]>>7, (d64->bytes[7]>>2)&0x1f,\r
+           ((d64->bytes[7]&0x3)<<6)| (d64->bytes[6]>>2));\r
+    }\r
+   else { // big-endian\r
+    for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {\r
+      sprintf(&buf[j], "%02x", d64->bytes[i]);\r
+      }\r
+    printf(" D64> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,\r
+           decimal64Sign(d64), decimal64Comb(d64), decimal64ExpCon(d64));\r
+    }\r
+  } // decimal64Show\r
+#endif\r
+\r
+/* ================================================================== */\r
+/* Shared utility routines and tables                                 */\r
+/* ================================================================== */\r
+// define and include the conversion tables to use for shared code\r
+#if DECDPUN==3\r
+  #define DEC_DPD2BIN 1\r
+#else\r
+  #define DEC_DPD2BCD 1\r
+#endif\r
+#include "decDPD.h"           // lookup tables\r
+\r
+// The maximum number of decNumberUnits needed for a working copy of\r
+// the units array is the ceiling of digits/DECDPUN, where digits is\r
+// the maximum number of digits in any of the formats for which this\r
+// is used.  decimal128.h must not be included in this module, so, as\r
+// a very special case, that number is defined as a literal here.\r
+#define DECMAX754   34\r
+#define DECMAXUNITS ((DECMAX754+DECDPUN-1)/DECDPUN)\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* Combination field lookup tables (uInts to save measurable work)    */\r
+/*                                                                    */\r
+/*      COMBEXP - 2-bit most-significant-bits of exponent             */\r
+/*                [11 if an Infinity or NaN]                          */\r
+/*      COMBMSD - 4-bit most-significant-digit                        */\r
+/*                [0=Infinity, 1=NaN if COMBEXP=11]                   */\r
+/*                                                                    */\r
+/* Both are indexed by the 5-bit combination field (0-31)             */\r
+/* ------------------------------------------------------------------ */\r
+const uInt COMBEXP[32]={0, 0, 0, 0, 0, 0, 0, 0,\r
+                        1, 1, 1, 1, 1, 1, 1, 1,\r
+                        2, 2, 2, 2, 2, 2, 2, 2,\r
+                        0, 0, 1, 1, 2, 2, 3, 3};\r
+const uInt COMBMSD[32]={0, 1, 2, 3, 4, 5, 6, 7,\r
+                        0, 1, 2, 3, 4, 5, 6, 7,\r
+                        0, 1, 2, 3, 4, 5, 6, 7,\r
+                        8, 9, 8, 9, 8, 9, 0, 1};\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decDigitsToDPD -- pack coefficient into DPD form                   */\r
+/*                                                                    */\r
+/*   dn   is the source number (assumed valid, max DECMAX754 digits)  */\r
+/*   targ is 1, 2, or 4-element uInt array, which the caller must     */\r
+/*        have cleared to zeros                                       */\r
+/*   shift is the number of 0 digits to add on the right (normally 0) */\r
+/*                                                                    */\r
+/* The coefficient must be known small enough to fit.  The full       */\r
+/* coefficient is copied, including the leading 'odd' digit.  This    */\r
+/* digit is retrieved and packed into the combination field by the    */\r
+/* caller.                                                            */\r
+/*                                                                    */\r
+/* The target uInts are altered only as necessary to receive the      */\r
+/* digits of the decNumber.  When more than one uInt is needed, they  */\r
+/* are filled from left to right (that is, the uInt at offset 0 will  */\r
+/* end up with the least-significant digits).                         */\r
+/*                                                                    */\r
+/* shift is used for 'fold-down' padding.                             */\r
+/*                                                                    */\r
+/* No error is possible.                                              */\r
+/* ------------------------------------------------------------------ */\r
+#if DECDPUN<=4\r
+// Constant multipliers for divide-by-power-of five using reciprocal\r
+// multiply, after removing powers of 2 by shifting, and final shift\r
+// of 17 [we only need up to **4]\r
+static const uInt multies[]={131073, 26215, 5243, 1049, 210};\r
+// QUOT10 -- macro to return the quotient of unit u divided by 10**n\r
+#define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)\r
+#endif\r
+void decDigitsToDPD(const decNumber *dn, uInt *targ, Int shift) {\r
+  Int  cut;                   // work\r
+  Int  n;                     // output bunch counter\r
+  Int  digits=dn->digits;     // digit countdown\r
+  uInt dpd;                   // densely packed decimal value\r
+  uInt bin;                   // binary value 0-999\r
+  uInt *uout=targ;            // -> current output uInt\r
+  uInt  uoff=0;               // -> current output offset [from right]\r
+  const Unit *inu=dn->lsu;    // -> current input unit\r
+  Unit  uar[DECMAXUNITS];     // working copy of units, iff shifted\r
+  #if DECDPUN!=3              // not fast path\r
+    Unit in;                  // current unit\r
+  #endif\r
+\r
+  if (shift!=0) {             // shift towards most significant required\r
+    // shift the units array to the left by pad digits and copy\r
+    // [this code is a special case of decShiftToMost, which could\r
+    // be used instead if exposed and the array were copied first]\r
+    const Unit *source;                 // ..\r
+    Unit  *target, *first;              // ..\r
+    uInt  next=0;                       // work\r
+\r
+    source=dn->lsu+D2U(digits)-1;       // where msu comes from\r
+    target=uar+D2U(digits)-1+D2U(shift);// where upper part of first cut goes\r
+    cut=DECDPUN-MSUDIGITS(shift);       // where to slice\r
+    if (cut==0) {                       // unit-boundary case\r
+      for (; source>=dn->lsu; source--, target--) *target=*source;\r
+      }\r
+     else {\r
+      first=uar+D2U(digits+shift)-1;    // where msu will end up\r
+      for (; source>=dn->lsu; source--, target--) {\r
+        // split the source Unit and accumulate remainder for next\r
+        #if DECDPUN<=4\r
+          uInt quot=QUOT10(*source, cut);\r
+          uInt rem=*source-quot*DECPOWERS[cut];\r
+          next+=quot;\r
+        #else\r
+          uInt rem=*source%DECPOWERS[cut];\r
+          next+=*source/DECPOWERS[cut];\r
+        #endif\r
+        if (target<=first) *target=(Unit)next; // write to target iff valid\r
+        next=rem*DECPOWERS[DECDPUN-cut];       // save remainder for next Unit\r
+        }\r
+      } // shift-move\r
+    // propagate remainder to one below and clear the rest\r
+    for (; target>=uar; target--) {\r
+      *target=(Unit)next;\r
+      next=0;\r
+      }\r
+    digits+=shift;                 // add count (shift) of zeros added\r
+    inu=uar;                       // use units in working array\r
+    }\r
+\r
+  /* now densely pack the coefficient into DPD declets */\r
+\r
+  #if DECDPUN!=3                   // not fast path\r
+    in=*inu;                       // current unit\r
+    cut=0;                         // at lowest digit\r
+    bin=0;                         // [keep compiler quiet]\r
+  #endif\r
+\r
+  for(n=0; digits>0; n++) {        // each output bunch\r
+    #if DECDPUN==3                 // fast path, 3-at-a-time\r
+      bin=*inu;                    // 3 digits ready for convert\r
+      digits-=3;                   // [may go negative]\r
+      inu++;                       // may need another\r
+\r
+    #else                          // must collect digit-by-digit\r
+      Unit dig;                    // current digit\r
+      Int j;                       // digit-in-declet count\r
+      for (j=0; j<3; j++) {\r
+        #if DECDPUN<=4\r
+          Unit temp=(Unit)((uInt)(in*6554)>>16);\r
+          dig=(Unit)(in-X10(temp));\r
+          in=temp;\r
+        #else\r
+          dig=in%10;\r
+          in=in/10;\r
+        #endif\r
+        if (j==0) bin=dig;\r
+         else if (j==1)  bin+=X10(dig);\r
+         else /* j==2 */ bin+=X100(dig);\r
+        digits--;\r
+        if (digits==0) break;      // [also protects *inu below]\r
+        cut++;\r
+        if (cut==DECDPUN) {inu++; in=*inu; cut=0;}\r
+        }\r
+    #endif\r
+    // here there are 3 digits in bin, or have used all input digits\r
+\r
+    dpd=BIN2DPD[bin];\r
+\r
+    // write declet to uInt array\r
+    *uout|=dpd<<uoff;\r
+    uoff+=10;\r
+    if (uoff<32) continue;         // no uInt boundary cross\r
+    uout++;\r
+    uoff-=32;\r
+    *uout|=dpd>>(10-uoff);         // collect top bits\r
+    } // n declets\r
+  return;\r
+  } // decDigitsToDPD\r
+\r
+/* ------------------------------------------------------------------ */\r
+/* decDigitsFromDPD -- unpack a format's coefficient                  */\r
+/*                                                                    */\r
+/*   dn is the target number, with 7, 16, or 34-digit space.          */\r
+/*   sour is a 1, 2, or 4-element uInt array containing only declets  */\r
+/*   declets is the number of (right-aligned) declets in sour to      */\r
+/*     be processed.  This may be 1 more than the obvious number in   */\r
+/*     a format, as any top digit is prefixed to the coefficient      */\r
+/*     continuation field.  It also may be as small as 1, as the      */\r
+/*     caller may pre-process leading zero declets.                   */\r
+/*                                                                    */\r
+/* When doing the 'extra declet' case care is taken to avoid writing  */\r
+/* extra digits when there are leading zeros, as these could overflow */\r
+/* the units array when DECDPUN is not 3.                             */\r
+/*                                                                    */\r
+/* The target uInts are used only as necessary to process declets     */\r
+/* declets into the decNumber.  When more than one uInt is needed,    */\r
+/* they are used from left to right (that is, the uInt at offset 0    */\r
+/* provides the least-significant digits).                            */\r
+/*                                                                    */\r
+/* dn->digits is set, but not the sign or exponent.                   */\r
+/* No error is possible [the redundant 888 codes are allowed].        */\r
+/* ------------------------------------------------------------------ */\r
+void decDigitsFromDPD(decNumber *dn, const uInt *sour, Int declets) {\r
+\r
+  uInt  dpd;                       // collector for 10 bits\r
+  Int   n;                         // counter\r
+  Unit  *uout=dn->lsu;             // -> current output unit\r
+  Unit  *last=uout;                // will be unit containing msd\r
+  const uInt *uin=sour;            // -> current input uInt\r
+  uInt  uoff=0;                    // -> current input offset [from right]\r
+\r
+  #if DECDPUN!=3\r
+  uInt  bcd;                       // BCD result\r
+  uInt  nibble;                    // work\r
+  Unit  out=0;                     // accumulator\r
+  Int   cut=0;                     // power of ten in current unit\r
+  #endif\r
+  #if DECDPUN>4\r
+  uInt const *pow;                 // work\r
+  #endif\r
+\r
+  // Expand the densely-packed integer, right to left\r
+  for (n=declets-1; n>=0; n--) {   // count down declets of 10 bits\r
+    dpd=*uin>>uoff;\r
+    uoff+=10;\r
+    if (uoff>32) {                 // crossed uInt boundary\r
+      uin++;\r
+      uoff-=32;                    // [if using this code for wider, check this]\r
+      dpd|=*uin<<(10-uoff);        // get waiting bits\r
+      }\r
+    dpd&=0x3ff;                    // clear uninteresting bits\r
+\r
+  #if DECDPUN==3\r
+    if (dpd==0) *uout=0;\r
+     else {\r
+      *uout=DPD2BIN[dpd];          // convert 10 bits to binary 0-999\r
+      last=uout;                   // record most significant unit\r
+      }\r
+    uout++;\r
+    } // n\r
+\r
+  #else // DECDPUN!=3\r
+    if (dpd==0) {                  // fastpath [e.g., leading zeros]\r
+      // write out three 0 digits (nibbles); out may have digit(s)\r
+      cut++;\r
+      if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}\r
+      if (n==0) break;             // [as below, works even if MSD=0]\r
+      cut++;\r
+      if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}\r
+      cut++;\r
+      if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}\r
+      continue;\r
+      }\r
+\r
+    bcd=DPD2BCD[dpd];              // convert 10 bits to 12 bits BCD\r
+\r
+    // now accumulate the 3 BCD nibbles into units\r
+    nibble=bcd & 0x00f;\r
+    if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);\r
+    cut++;\r
+    if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}\r
+    bcd>>=4;\r
+\r
+    // if this is the last declet and the remaining nibbles in bcd\r
+    // are 00 then process no more nibbles, because this could be\r
+    // the 'odd' MSD declet and writing any more Units would then\r
+    // overflow the unit array\r
+    if (n==0 && !bcd) break;\r
+\r
+    nibble=bcd & 0x00f;\r
+    if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);\r
+    cut++;\r
+    if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}\r
+    bcd>>=4;\r
+\r
+    nibble=bcd & 0x00f;\r
+    if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);\r
+    cut++;\r
+    if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}\r
+    } // n\r
+  if (cut!=0) {                         // some more left over\r
+    *uout=out;                          // write out final unit\r
+    if (out) last=uout;                 // and note if non-zero\r
+    }\r
+  #endif\r
+\r
+  // here, last points to the most significant unit with digits;\r
+  // inspect it to get the final digits count -- this is essentially\r
+  // the same code as decGetDigits in decNumber.c\r
+  dn->digits=(last-dn->lsu)*DECDPUN+1;  // floor of digits, plus\r
+                                        // must be at least 1 digit\r
+  #if DECDPUN>1\r
+  if (*last<10) return;                 // common odd digit or 0\r
+  dn->digits++;                         // must be 2 at least\r
+  #if DECDPUN>2\r
+  if (*last<100) return;                // 10-99\r
+  dn->digits++;                         // must be 3 at least\r
+  #if DECDPUN>3\r
+  if (*last<1000) return;               // 100-999\r
+  dn->digits++;                         // must be 4 at least\r
+  #if DECDPUN>4\r
+  for (pow=&DECPOWERS[4]; *last>=*pow; pow++) dn->digits++;\r
+  #endif\r
+  #endif\r
+  #endif\r
+  #endif\r
+  return;\r
+  } //decDigitsFromDPD\r
diff --git a/src/decNumber/decimal64.h b/src/decNumber/decimal64.h
new file mode 100644 (file)
index 0000000..19a1b5e
--- /dev/null
@@ -0,0 +1,83 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal 64-bit format module header                                */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2000, 2005.  All rights reserved.   */\r
+/*                                                                    */\r
+/* This software is made available under the terms of the             */\r
+/* ICU License -- ICU 1.8.1 and later.                                */\r
+/*                                                                    */\r
+/* The description and User's Guide ("The decNumber C Library") for   */\r
+/* this software is called decNumber.pdf.  This document is           */\r
+/* available, together with arithmetic and format specifications,     */\r
+/* testcases, and Web links, on the General Decimal Arithmetic page.  */\r
+/*                                                                    */\r
+/* Please send comments, suggestions, and corrections to the author:  */\r
+/*   mfc@uk.ibm.com                                                   */\r
+/*   Mike Cowlishaw, IBM Fellow                                       */\r
+/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */\r
+/* ------------------------------------------------------------------ */\r
+\r
+#if !defined(DECIMAL64)\r
+  #define DECIMAL64\r
+  #define DEC64NAME     "decimal64"                   /* Short name   */\r
+  #define DEC64FULLNAME "Decimal 64-bit Number"       /* Verbose name */\r
+  #define DEC64AUTHOR   "Mike Cowlishaw"              /* Who to blame */\r
+\r
+\r
+  /* parameters for decimal64s                                        */\r
+  #define DECIMAL64_Bytes  8            /* length                     */\r
+  #define DECIMAL64_Pmax   16           /* maximum precision (digits) */\r
+  #define DECIMAL64_Emax   384          /* maximum adjusted exponent  */\r
+  #define DECIMAL64_Emin  -383          /* minimum adjusted exponent  */\r
+  #define DECIMAL64_Bias   398          /* bias for the exponent      */\r
+  #define DECIMAL64_String 24           /* maximum string length, +1  */\r
+  #define DECIMAL64_EconL  8            /* exp. continuation length   */\r
+  /* highest biased exponent (Elimit-1)                               */\r
+  #define DECIMAL64_Ehigh  (DECIMAL64_Emax+DECIMAL64_Bias-DECIMAL64_Pmax+1)\r
+\r
+  /* check enough digits, if pre-defined                              */\r
+  #if defined(DECNUMDIGITS)\r
+    #if (DECNUMDIGITS<DECIMAL64_Pmax)\r
+      #error decimal64.h needs pre-defined DECNUMDIGITS>=16 for safe use\r
+    #endif\r
+  #endif\r
+\r
+\r
+  #ifndef DECNUMDIGITS\r
+    #define DECNUMDIGITS DECIMAL64_Pmax /* size if not already defined*/\r
+  #endif\r
+  #ifndef DECNUMBER\r
+    #include "decNumber.h"              /* context and number library */\r
+  #endif\r
+\r
+  /* Decimal 64-bit type, accessible by bytes                         */\r
+  typedef struct {\r
+    uint8_t bytes[DECIMAL64_Bytes];     /* decimal64: 1, 5, 8, 50 bits*/\r
+    } decimal64;\r
+\r
+  /* special values [top byte excluding sign bit; last two bits are   */\r
+  /* don't-care for Infinity on input, last bit don't-care for NaN]   */\r
+  #if !defined(DECIMAL_NaN)\r
+    #define DECIMAL_NaN     0x7c        /* 0 11111 00 NaN             */\r
+    #define DECIMAL_sNaN    0x7e        /* 0 11111 10 sNaN            */\r
+    #define DECIMAL_Inf     0x78        /* 0 11110 00 Infinity        */\r
+  #endif\r
+\r
+  /* ---------------------------------------------------------------- */\r
+  /* Routines                                                         */\r
+  /* ---------------------------------------------------------------- */\r
+  /* String conversions                                               */\r
+  decimal64 * decimal64FromString(decimal64 *, const char *, decContext *);\r
+  char * decimal64ToString(const decimal64 *, char *);\r
+  char * decimal64ToEngString(const decimal64 *, char *);\r
+\r
+  /* decNumber conversions                                            */\r
+  decimal64 * decimal64FromNumber(decimal64 *, const decNumber *,\r
+                                  decContext *);\r
+  decNumber * decimal64ToNumber(const decimal64 *, decNumber *);\r
+\r
+  /* Format-dependent utilities                                       */\r
+  uint32_t    decimal64IsCanonical(const decimal64 *);\r
+  decimal64 * decimal64Canonical(decimal64 *, const decimal64 *);\r
+\r
+#endif\r
diff --git a/src/decNumber/decnumber.pdf b/src/decNumber/decnumber.pdf
new file mode 100644 (file)
index 0000000..f601105
Binary files /dev/null and b/src/decNumber/decnumber.pdf differ
diff --git a/src/decNumber/example1.c b/src/decNumber/example1.c
new file mode 100644 (file)
index 0000000..c204b7e
--- /dev/null
@@ -0,0 +1,38 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number Library Demonstration program                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2001, 2007.  All rights reserved.   */\r
+/* ----------------------------------------------------------------+- */\r
+/*                                                 right margin -->|  */\r
+\r
+// example1.c -- convert the first two argument words to decNumber,\r
+// add them together, and display the result\r
+\r
+#define  DECNUMDIGITS 34           // work with up to 34 digits\r
+#include "decNumber.h"             // base number library\r
+#include <stdio.h>                 // for printf\r
+\r
+int main(int argc, char *argv[]) {\r
+  decNumber a, b;                  // working numbers\r
+  decContext set;                  // working context\r
+  char string[DECNUMDIGITS+14];    // conversion buffer\r
+\r
+  decContextTestEndian(0);         // warn if DECLITEND is wrong\r
+\r
+  if (argc<3) {                    // not enough words\r
+    printf("Please supply two numbers to add.\n");\r
+    return 1;\r
+    }\r
+  decContextDefault(&set, DEC_INIT_BASE); // initialize\r
+  set.traps=0;                     // no traps, thank you\r
+  set.digits=DECNUMDIGITS;         // set precision\r
+\r
+  decNumberFromString(&a, argv[1], &set);\r
+  decNumberFromString(&b, argv[2], &set);\r
+\r
+  decNumberAdd(&a, &a, &b, &set);            // a=a+b\r
+  decNumberToString(&a, string);\r
+\r
+  printf("%s + %s => %s\n", argv[1], argv[2], string);\r
+  return 0;\r
+  } // main\r
diff --git a/src/decNumber/example2.c b/src/decNumber/example2.c
new file mode 100644 (file)
index 0000000..cb19730
--- /dev/null
@@ -0,0 +1,52 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number Library Demonstration program                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2001.  All rights reserved.         */\r
+/* ----------------------------------------------------------------+- */\r
+/*                                                 right margin -->|  */\r
+\r
+// example2.c -- calculate compound interest\r
+// Arguments are investment, rate (%), and years\r
+\r
+#define  DECNUMDIGITS 38           // work with up to 38 digits\r
+#include "decNumber.h"             // base number library\r
+#include <stdio.h>                 // for printf\r
+\r
+int main(int argc, char *argv[]) {\r
+  int need=3;\r
+  if (argc<need+1) {               // not enough words\r
+    printf("Please supply %d number(s).\n", need);\r
+    return 1;\r
+    }\r
+\r
+  { // excerpt for User's Guide starts here--------------------------|\r
+  decNumber one, mtwo, hundred;                   // constants\r
+  decNumber start, rate, years;                   // parameters\r
+  decNumber total;                                // result\r
+  decContext set;                                 // working context\r
+  char string[DECNUMDIGITS+14];                   // conversion buffer\r
+\r
+  decContextDefault(&set, DEC_INIT_BASE);         // initialize\r
+  set.traps=0;                                    // no traps\r
+  set.digits=25;                                  // precision 25\r
+  decNumberFromString(&one,       "1", &set);     // set constants\r
+  decNumberFromString(&mtwo,     "-2", &set);\r
+  decNumberFromString(&hundred, "100", &set);\r
+\r
+  decNumberFromString(&start, argv[1], &set);     // parameter words\r
+  decNumberFromString(&rate,  argv[2], &set);\r
+  decNumberFromString(&years, argv[3], &set);\r
+\r
+  decNumberDivide(&rate, &rate, &hundred, &set);  // rate=rate/100\r
+  decNumberAdd(&rate, &rate, &one, &set);         // rate=rate+1\r
+  decNumberPower(&rate, &rate, &years, &set);     // rate=rate^years\r
+  decNumberMultiply(&total, &rate, &start, &set); // total=rate*start\r
+  decNumberRescale(&total, &total, &mtwo, &set);  // two digits please\r
+\r
+  decNumberToString(&total, string);\r
+  printf("%s at %s%% for %s years => %s\n",\r
+         argv[1], argv[2], argv[3], string);\r
+\r
+  } //---------------------------------------------------------------|\r
+  return 0;\r
+  } // main\r
diff --git a/src/decNumber/example3.c b/src/decNumber/example3.c
new file mode 100644 (file)
index 0000000..b84085c
--- /dev/null
@@ -0,0 +1,64 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number Library Demonstration program                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2001.  All rights reserved.         */\r
+/* ----------------------------------------------------------------+- */\r
+/*                                                 right margin -->|  */\r
+\r
+// example3.c -- calculate compound interest, passive checking\r
+// Arguments are investment, rate (%), and years\r
+\r
+#define  DECNUMDIGITS 38           // work with up to 38 digits\r
+#include "decNumber.h"             // base number library\r
+#include <stdio.h>                 // for printf\r
+\r
+int main(int argc, char *argv[]) {\r
+  int need=3;\r
+  if (argc<need+1) {               // not enough words\r
+    printf("Please supply %d number(s).\n", need);\r
+    return 1;\r
+    }\r
+\r
+  { // start of Example 2 segment\r
+  decNumber one, mtwo, hundred;                   // constants\r
+  decNumber start, rate, years;                   // parameters\r
+  decNumber total;                                // result\r
+  decContext set;                                 // working context\r
+  char string[DECNUMDIGITS+14];                   // conversion buffer\r
+\r
+  decContextDefault(&set, DEC_INIT_BASE);         // initialize\r
+  set.traps=0;                                    // no traps\r
+  set.digits=25;                                  // precision 25\r
+  decNumberFromString(&one,       "1", &set);     // set constants\r
+  decNumberFromString(&mtwo,     "-2", &set);\r
+  decNumberFromString(&hundred, "100", &set);\r
+\r
+// [snip...\r
+  decNumberFromString(&start, argv[1], &set);     // parameter words\r
+  decNumberFromString(&rate,  argv[2], &set);\r
+  decNumberFromString(&years, argv[3], &set);\r
+  if (set.status & DEC_Errors) {\r
+    printf("An input argument word was invalid [%s]\n",\r
+           decContextStatusToString(&set));\r
+    return 1;\r
+    }\r
+  decNumberDivide(&rate, &rate, &hundred, &set);  // rate=rate/100\r
+  decNumberAdd(&rate, &rate, &one, &set);         // rate=rate+1\r
+  decNumberPower(&rate, &rate, &years, &set);     // rate=rate^years\r
+  decNumberMultiply(&total, &rate, &start, &set); // total=rate*start\r
+  decNumberRescale(&total, &total, &mtwo, &set);  // two digits please\r
+  if (set.status & DEC_Errors) {\r
+    set.status &= DEC_Errors;                     // keep only errors\r
+    printf("Result could not be calculated [%s]\n",\r
+           decContextStatusToString(&set));\r
+    return 1;\r
+    }\r
+// ...snip]\r
+\r
+  decNumberToString(&total, string);\r
+  printf("%s at %s%% for %s years => %s\n",\r
+         argv[1], argv[2], argv[3], string);\r
+\r
+  } //---------------------------------------------------------------|\r
+  return 0;\r
+  } // main\r
diff --git a/src/decNumber/example4.c b/src/decNumber/example4.c
new file mode 100644 (file)
index 0000000..ce8028b
--- /dev/null
@@ -0,0 +1,61 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number Library Demonstration program                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2001.  All rights reserved.         */\r
+/* ----------------------------------------------------------------+- */\r
+/*                                                 right margin -->|  */\r
+\r
+// example4.c -- add two numbers, active error handling\r
+// Arguments are two numbers\r
+\r
+#define  DECNUMDIGITS 38           // work with up to 38 digits\r
+#include "decNumber.h"             // base number library\r
+#include <stdio.h>                 // for printf\r
+\r
+// [snip...\r
+#include <signal.h>                // signal handling\r
+#include <setjmp.h>                // setjmp/longjmp\r
+\r
+jmp_buf preserve;                  // stack snapshot\r
+\r
+void signalHandler(int);           // prototype for GCC\r
+void signalHandler(int sig) {\r
+  signal(SIGFPE, signalHandler);   // re-enable\r
+  longjmp(preserve, sig);          // branch to preserved point\r
+  }\r
+// ...snip]\r
+int main(int argc, char *argv[]) {\r
+  decNumber a, b;                  // working numbers\r
+  decContext set;                  // working context\r
+  char string[DECNUMDIGITS+14];    // conversion buffer\r
+  int value;                       // work variable\r
+\r
+  if (argc<3) {                    // not enough words\r
+    printf("Please supply two numbers to add.\n");\r
+    return 1;\r
+    }\r
+  decContextDefault(&set, DEC_INIT_BASE);    // initialize\r
+\r
+// [snip...\r
+  signal(SIGFPE, signalHandler);   // set up signal handler\r
+  value=setjmp(preserve);          // preserve and test environment\r
+  if (value) {                     // (non-0 after longjmp)\r
+    set.status &= DEC_Errors;      // keep only errors\r
+    printf("Signal trapped [%s].\n", decContextStatusToString(&set));\r
+    return 1;\r
+    }\r
+// ...snip]\r
+\r
+// [change from Example 1, here]\r
+  // leave traps enabled\r
+  set.digits=DECNUMDIGITS;         // set precision\r
+\r
+  decNumberFromString(&a, argv[1], &set);\r
+  decNumberFromString(&b, argv[2], &set);\r
+\r
+  decNumberAdd(&a, &a, &b, &set);            // A=A+B\r
+  decNumberToString(&a, string);\r
+\r
+  printf("%s + %s => %s\n", argv[1], argv[2], string);\r
+  return 0;\r
+  } // main\r
diff --git a/src/decNumber/example5.c b/src/decNumber/example5.c
new file mode 100644 (file)
index 0000000..5f89d8c
--- /dev/null
@@ -0,0 +1,36 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number Library Demonstration program                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2001, 2007.  All rights reserved.   */\r
+/* ----------------------------------------------------------------+- */\r
+/*                                                 right margin -->|  */\r
+\r
+// example5.c -- decimal64 conversions\r
+\r
+#include "decimal64.h"             // decimal64 and decNumber library\r
+#include <stdio.h>                 // for (s)printf\r
+\r
+int main(int argc, char *argv[]) {\r
+  decimal64 a;                     // working decimal64 number\r
+  decNumber d;                     // working number\r
+  decContext set;                  // working context\r
+  char string[DECIMAL64_String];   // number->string buffer\r
+  char hexes[25];                  // decimal64->hex buffer\r
+  int i;                           // counter\r
+\r
+  if (argc<2) {                    // not enough words\r
+    printf("Please supply a number.\n");\r
+    return 1;\r
+    }\r
+  decContextDefault(&set, DEC_INIT_DECIMAL64); // initialize\r
+\r
+  decimal64FromString(&a, argv[1], &set);\r
+  // lay out the decimal64 as eight hexadecimal pairs\r
+  for (i=0; i<8; i++) {\r
+    sprintf(&hexes[i*3], "%02x ", a.bytes[i]);\r
+    }\r
+  decimal64ToNumber(&a, &d);\r
+  decNumberToString(&d, string);\r
+  printf("%s => %s=> %s\n", argv[1], hexes, string);\r
+  return 0;\r
+  } // main\r
diff --git a/src/decNumber/example6.c b/src/decNumber/example6.c
new file mode 100644 (file)
index 0000000..486b979
--- /dev/null
@@ -0,0 +1,61 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number Library Demonstration program                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2001.  All rights reserved.         */\r
+/* ----------------------------------------------------------------+- */\r
+/*                                                 right margin -->|  */\r
+\r
+// example6.c -- calculate compound interest, using Packed Decimal\r
+// Values are investment, rate (%), and years\r
+\r
+#include "decPacked.h"             // base number library\r
+#include <stdio.h>                 // for printf\r
+\r
+int main(int argc, char *argv[]) {\r
+  { // excerpt for User's Guide starts here--------------------------|\r
+  decNumber one, mtwo, hundred;                   // constants\r
+  decNumber start, rate, years;                   // parameters\r
+  decNumber total;                                // result\r
+  decContext set;                                 // working context\r
+\r
+  uint8_t startpack[]={0x01, 0x00, 0x00, 0x0C};   // investment=100000\r
+  int32_t startscale=0;\r
+  uint8_t ratepack[]={0x06, 0x5C};                // rate=6.5%\r
+  int32_t ratescale=1;\r
+  uint8_t yearspack[]={0x02, 0x0C};               // years=20\r
+  int32_t yearsscale=0;\r
+  uint8_t respack[16];                            // result, packed\r
+  int32_t resscale;                               // ..\r
+  char  hexes[49];                                // for packed->hex\r
+  int   i;                                        // counter\r
+\r
+  if (argc<0) printf("%s", argv[1]);              // noop for warning\r
+\r
+  decContextDefault(&set, DEC_INIT_BASE);         // initialize\r
+  set.traps=0;                                    // no traps\r
+  set.digits=25;                                  // precision 25\r
+  decNumberFromString(&one,       "1", &set);     // set constants\r
+  decNumberFromString(&mtwo,     "-2", &set);\r
+  decNumberFromString(&hundred, "100", &set);\r
+\r
+  decPackedToNumber(startpack, sizeof(startpack), &startscale, &start);\r
+  decPackedToNumber(ratepack,  sizeof(ratepack),  &ratescale,  &rate);\r
+  decPackedToNumber(yearspack, sizeof(yearspack), &yearsscale, &years);\r
+\r
+  decNumberDivide(&rate, &rate, &hundred, &set);  // rate=rate/100\r
+  decNumberAdd(&rate, &rate, &one, &set);         // rate=rate+1\r
+  decNumberPower(&rate, &rate, &years, &set);     // rate=rate^years\r
+  decNumberMultiply(&total, &rate, &start, &set); // total=rate*start\r
+  decNumberRescale(&total, &total, &mtwo, &set);  // two digits please\r
+\r
+  decPackedFromNumber(respack, sizeof(respack), &resscale, &total);\r
+\r
+  // lay out the total as sixteen hexadecimal pairs\r
+  for (i=0; i<16; i++) {\r
+    sprintf(&hexes[i*3], "%02x ", respack[i]);\r
+    }\r
+  printf("Result: %s (scale=%ld)\n", hexes, (long int)resscale);\r
+\r
+  } //---------------------------------------------------------------|\r
+  return 0;\r
+  } // main\r
diff --git a/src/decNumber/example7.c b/src/decNumber/example7.c
new file mode 100644 (file)
index 0000000..cc933ca
--- /dev/null
@@ -0,0 +1,35 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number Library Demonstration program                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2001, 2008.  All rights reserved.   */\r
+/* ----------------------------------------------------------------+- */\r
+/*                                                 right margin -->|  */\r
+\r
+// example7.c -- using decQuad to add two numbers together\r
+\r
+// compile: example7.c decContext.c decQuad.c\r
+\r
+#include "decQuad.h"               // decQuad library\r
+#include <stdio.h>                 // for printf\r
+\r
+int main(int argc, char *argv[]) {\r
+  decQuad a, b;                    // working decQuads\r
+  decContext set;                  // working context\r
+  char string[DECQUAD_String];     // number->string buffer\r
+\r
+  decContextTestEndian(0);         // warn if DECLITEND is wrong\r
+\r
+  if (argc<3) {                    // not enough words\r
+    printf("Please supply two numbers to add.\n");\r
+    return 1;\r
+    }\r
+  decContextDefault(&set, DEC_INIT_DECQUAD); // initialize\r
+\r
+  decQuadFromString(&a, argv[1], &set);\r
+  decQuadFromString(&b, argv[2], &set);\r
+  decQuadAdd(&a, &a, &b, &set);    // a=a+b\r
+  decQuadToString(&a, string);\r
+\r
+  printf("%s + %s => %s\n", argv[1], argv[2], string);\r
+  return 0;\r
+  } // main\r
diff --git a/src/decNumber/example8.c b/src/decNumber/example8.c
new file mode 100644 (file)
index 0000000..7fe35b9
--- /dev/null
@@ -0,0 +1,39 @@
+/* ------------------------------------------------------------------ */\r
+/* Decimal Number Library Demonstration program                       */\r
+/* ------------------------------------------------------------------ */\r
+/* Copyright (c) IBM Corporation, 2001, 2007.  All rights reserved.   */\r
+/* ----------------------------------------------------------------+- */\r
+/*                                                 right margin -->|  */\r
+\r
+// example8.c -- using decQuad with the decNumber module\r
+\r
+// compile: example8.c decContext.c decQuad.c\r
+//     and: decNumber.c decimal128.c decimal64.c\r
+\r
+#include "decQuad.h"               // decQuad library\r
+#include "decimal128.h"            // interface to decNumber\r
+#include <stdio.h>                 // for printf\r
+\r
+int main(int argc, char *argv[]) {\r
+  decQuad a;                       // working decQuad\r
+  decNumber numa, numb;            // working decNumbers\r
+  decContext set;                  // working context\r
+  char string[DECQUAD_String];     // number->string buffer\r
+\r
+  if (argc<3) {                    // not enough words\r
+    printf("Please supply two numbers for power(2*a, b).\n");\r
+    return 1;\r
+    }\r
+  decContextDefault(&set, DEC_INIT_DECQUAD); // initialize\r
+\r
+  decQuadFromString(&a, argv[1], &set);      // get a\r
+  decQuadAdd(&a, &a, &a, &set);              // double a\r
+  decQuadToNumber(&a, &numa);                // convert to decNumber\r
+  decNumberFromString(&numb, argv[2], &set);\r
+  decNumberPower(&numa, &numa, &numb, &set); // numa=numa**numb\r
+  decQuadFromNumber(&a, &numa, &set);        // back via a Quad\r
+  decQuadToString(&a, string);               // ..\r
+\r
+  printf("power(2*%s, %s) => %s\n", argv[1], argv[2], string);\r
+  return 0;\r
+  } // main\r
diff --git a/src/decNumber/readme.txt b/src/decNumber/readme.txt
new file mode 100644 (file)
index 0000000..375623f
--- /dev/null
@@ -0,0 +1,81 @@
+This is the readme.txt for the decNumber package.  It includes\r
+instructions for compiling and testing the package; please read them.\r
+---------------------------------------------------------------------\r
+\r
+decNumber is distributed in two forms; as a complete package from\r
+the International Components for Unicode (ICU) site (under an as-is\r
+license), or as a collection of Open Source files from the GCC source\r
+repository (under the GPL license).\r
+\r
+If you are using the GCC files, you can obtain the documentation, the\r
+example files mentioned below, and this readme from the General\r
+Decimal Arithmetic web page -- http://speleotrove.com/decimal/ (the\r
+URL for the open source files is also linked from there).\r
+\r
+\r
+The ICU package\r
+---------------\r
+\r
+The ICU package includes the files:\r
+\r
+  *  readme.txt (this file)\r
+\r
+  *  ICU-license.html\r
+\r
+  *  decNumber.pdf (documentation)\r
+\r
+  *  The .c and .h file for each module in the package (see the\r
+     decNumber documentation), together with other included files.\r
+\r
+  *  The .c files for each of the examples (example1.c through\r
+     example8.c).\r
+\r
+The ICU package is made available under the terms of the ICU License\r
+(ICU 1.8.1 and later) included in the package as ICU-license.html.\r
+Your use of that package indicates your acceptance of the terms and\r
+conditions of that Agreement.\r
+\r
+\r
+To use and check decNumber\r
+--------------------------\r
+\r
+  Please read the appropriate license and documentation before using\r
+  this package.  If you are upgrading an existing use of decNumber\r
+  (with version <= 3.37) please read the Changes Appendix for later\r
+  versions -- you may need to change the DECLITEND flag.\r
+\r
+  1. Compile and link example1.c, decNumber.c, and decContext.c\r
+     For instance, use:\r
+\r
+       gcc -o example1 example1.c decNumber.c decContext.c\r
+\r
+     Note: If your compiler does not provide stdint.h or if your C\r
+     compiler does not handle line comments (// ...), then see the\r
+     User's Guide section in the documentation for further information\r
+     (including a sample minimal stdint.h).\r
+\r
+     The use of compiler optimization is strongly recommended (e.g.,\r
+     -O3 for GCC or /O2 for Visual Studio).\r
+\r
+  2. Run example1 with two numeric arguments, for example:\r
+\r
+       example1 1.23 1.27\r
+\r
+     this should display:\r
+\r
+       1.23 + 1.27 => 2.50\r
+\r
+  3. Similarly, try the other examples, at will.\r
+\r
+     Examples 2->4 require three files to be compiled, like Example 1.\r
+\r
+     Example 5 requires decimal64.c in addition to the core modules.\r
+\r
+     Example 6 requires decPacked.c in addition to the core modules.\r
+\r
+     Example 7 requires only example7.c decContext.c and decQuad.c\r
+\r
+     Example 8 requires example8.c, decContext.c, and decQuad.c, plus\r
+               decNumber.c, decimal128.c, and decimal64.c (the latter\r
+               for shared tables and code)\r
+\r
diff --git a/tests.out b/tests.out
new file mode 100644 (file)
index 0000000..38c3d00
--- /dev/null
+++ b/tests.out
@@ -0,0 +1,101 @@
+Skipped 9 tests
+Testing '.[0]' at line number 37
+Hit the number of tests limit (1), breaking
+1 of 1 tests passed (0 malformed)
+==9681== 17 bytes in 1 blocks are definitely lost in loss record 4 of 45
+==9681==    at 0x100180545: malloc (vg_replace_malloc.c:302)
+==9681==    by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)
+==9681==    by 0x10001F425: jv_number_with_literal (jv.c:193)
+==9681==    by 0x10002F9C8: check_literal (jv_parse.c:508)
+==9681==    by 0x10002EAA4: jv_parser_next (jv_parse.c:797)
+==9681==    by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)
+==9681==    by 0x10003544B: jq_yylex (lexer.l:90)
+==9681==    by 0x100036FB4: yylex (parser.y:153)
+==9681==    by 0x100037352: yyparse (parser.c:2292)
+==9681==    by 0x10003B0FD: jq_parse (parser.y:967)
+==9681==    by 0x100032CD4: load_program (linker.c:374)
+==9681==    by 0x10001C5B3: jq_compile_args (execute.c:1172)
+==9681==
+
+
+Skipped 10 tests
+Testing '.[2]' at line number 41
+Hit the number of tests limit (1), breaking
+1 of 1 tests passed (0 malformed)
+==9690== 17 bytes in 1 blocks are definitely lost in loss record 4 of 45
+==9690==    at 0x100180545: malloc (vg_replace_malloc.c:302)
+==9690==    by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)
+==9690==    by 0x10001F425: jv_number_with_literal (jv.c:193)
+==9690==    by 0x10002F9C8: check_literal (jv_parse.c:508)
+==9690==    by 0x10002EAA4: jv_parser_next (jv_parse.c:797)
+==9690==    by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)
+==9690==    by 0x10003544B: jq_yylex (lexer.l:90)
+==9690==    by 0x100036FB4: yylex (parser.y:153)
+==9690==    by 0x100037352: yyparse (parser.c:2292)
+==9690==    by 0x10003B0FD: jq_parse (parser.y:967)
+==9690==    by 0x100032CD4: load_program (linker.c:374)
+==9690==    by 0x10001C5B3: jq_compile_args (execute.c:1172)
+==9690==
+
+Skipped 12 tests
+Testing '.[2:4]' at line number 49
+Hit the number of tests limit (1), breaking
+1 of 1 tests passed (0 malformed)
+==9713== 34 bytes in 2 blocks are definitely lost in loss record 15 of 45
+==9713==    at 0x100180545: malloc (vg_replace_malloc.c:302)
+==9713==    by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)
+==9713==    by 0x10001F425: jv_number_with_literal (jv.c:193)
+==9713==    by 0x10002F9C8: check_literal (jv_parse.c:508)
+==9713==    by 0x10002EAA4: jv_parser_next (jv_parse.c:797)
+==9713==    by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)
+==9713==    by 0x10003544B: jq_yylex (lexer.l:90)
+==9713==    by 0x100036FB4: yylex (parser.y:153)
+==9713==    by 0x100037352: yyparse (parser.c:2292)
+==9713==    by 0x10003B0FD: jq_parse (parser.y:967)
+==9713==    by 0x100032CD4: load_program (linker.c:374)
+==9713==    by 0x10001C5B3: jq_compile_args (execute.c:1172)
+==9713==
+
+Skipped 13 tests
+Testing '.[2:4]' at line number 53
+Hit the number of tests limit (1), breaking
+1 of 1 tests passed (0 malformed)
+==9714== 34 bytes in 2 blocks are definitely lost in loss record 15 of 45
+==9714==    at 0x100180545: malloc (vg_replace_malloc.c:302)
+==9714==    by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)
+==9714==    by 0x10001F425: jv_number_with_literal (jv.c:193)
+==9714==    by 0x10002F9C8: check_literal (jv_parse.c:508)
+==9714==    by 0x10002EAA4: jv_parser_next (jv_parse.c:797)
+==9714==    by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)
+==9714==    by 0x10003544B: jq_yylex (lexer.l:90)
+==9714==    by 0x100036FB4: yylex (parser.y:153)
+==9714==    by 0x100037352: yyparse (parser.c:2292)
+==9714==    by 0x10003B0FD: jq_parse (parser.y:967)
+==9714==    by 0x100032CD4: load_program (linker.c:374)
+==9714==    by 0x10001C5B3: jq_compile_args (execute.c:1172)
+==9714==
+
+Skipped 14 tests
+Testing '.[:3]' at line number 57
+Hit the number of tests limit (1), breaking
+1 of 1 tests passed (0 malformed)
+==9715== 17 bytes in 1 blocks are definitely lost in loss record 4 of 45
+==9715==    at 0x100180545: malloc (vg_replace_malloc.c:302)
+==9715==    by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)
+==9715==    by 0x10001F425: jv_number_with_literal (jv.c:193)
+==9715==    by 0x10002F9C8: check_literal (jv_parse.c:508)
+==9715==    by 0x10002EAA4: jv_parser_next (jv_parse.c:797)
+==9715==    by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)
+==9715==    by 0x10003544B: jq_yylex (lexer.l:90)
+==9715==    by 0x100036FB4: yylex (parser.y:153)
+==9715==    by 0x100037352: yyparse (parser.c:2292)
+==9715==    by 0x10003B0FD: jq_parse (parser.y:967)
+==9715==    by 0x100032CD4: load_program (linker.c:374)
+==9715==    by 0x10001C5B3: jq_compile_args (execute.c:1172)
+==9715==
+
+Skipped 19 tests
+Testing '.foo, .bar' at line number 78
+Hit the number of tests limit (1), breaking
+1 of 1 tests passed (0 malformed)
+