home *** CD-ROM | disk | FTP | other *** search
/ GEMini Atari / GEMini_Atari_CD-ROM_Walnut_Creek_December_1993.iso / files / mint / mntlib24 / doprnt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-08-03  |  19.7 KB  |  807 lines

  1. /*
  2.  * Copyright (c) 1988 Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms are permitted
  6.  * provided that the above copyright notice and this paragraph are
  7.  * duplicated in all such forms and that any documentation,
  8.  * advertising materials, and other materials related to such
  9.  * distribution and use acknowledge that the software was developed
  10.  * by the University of California, Berkeley.  The name of the
  11.  * University may not be used to endorse or promote products derived
  12.  * from this software without specific prior written permission.
  13.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  14.  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  15.  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  16.  */
  17.  
  18. /*
  19.  * minorly customized for gcc lib
  20.  *    ++jrb
  21.  * and for the sfp004 as well as the TT's 68881
  22.  *      mjr++
  23.  * and for turbo C and the MiNT library
  24.  *     ++um,mh
  25.  */
  26.  
  27. #ifndef __NO_FLOAT__
  28. #if 0
  29. static unsigned long
  30.     __notanumber[2] = { 0x7fffffffL, 0xffffffffL }; /* ieee NAN */
  31. #define NAN  (*((double *)&__notanumber[0]))
  32. static unsigned long
  33.     __p_infinity[2] = { 0x7ff00000L, 0x00000000L }; /* ieee NAN */
  34. #define INF  (*((double *)&__p_infinity[0]))
  35. #endif
  36.  
  37. #define NAN_HI 0x7fffffffL
  38. #define NAN_LO 0xffffffffL
  39. #define INF_HI 0x7ff00000L
  40. #define INF_LO 0x00000000L
  41.  
  42. #endif /* __NO_FLOAT__ */
  43.  
  44. #ifdef LIBC_SCCS
  45. static char sccsid[] = "@(#)doprnt.c    5.37 (Berkeley) 3/26/89";
  46. #endif /* LIBC_SCCS */
  47.  
  48. #ifdef __TURBOC__
  49. #include <sys\types.h>
  50. #else
  51. #include <sys/types.h>
  52. #endif
  53. #include <stdarg.h>
  54. #include <stdio.h>
  55. #include <ctype.h>
  56. #include <string.h>
  57. #include <limits.h>
  58. #include    <math.h>    /* mjr++    */
  59.  
  60. #ifndef __GNUC__    /* gcc lib has these typedefs in sys/types.h */
  61. #ifndef __MINT__    /* as does the MiNT library */
  62. typedef unsigned char u_char;
  63. typedef unsigned long u_long;
  64. #endif
  65. #endif
  66.  
  67. /* 11-bit exponent (VAX G floating point) is 308 decimal digits */
  68. #define    MAXEXP        308
  69.  
  70. /* 128 bit fraction takes up 39 decimal digits; max reasonable precision */
  71. # define    MAXFRACT    39
  72. # define    MAXEXP        308
  73.  
  74. #if defined (__M68881__) && !defined (sfp004)
  75. #  include <math-68881.h>    /* mjr: use the inline functions    */
  76. #endif    __M68881__
  77.  
  78. #define    DEFPREC        6
  79.  
  80. #define    BUF        (MAXEXP+MAXFRACT+1)    /* + decimal point */
  81.  
  82. #define    PUTC(ch)     if( fputc(ch, fp) == EOF ) return EOF;
  83.  
  84. #define ARG(basetype) \
  85.     _ulong = flags&LONGINT ? va_arg(argp, long basetype) : \
  86.         flags&SHORTINT ? (short basetype)va_arg(argp, short) : \
  87.         va_arg(argp, int)
  88.  
  89. #define TEN_MUL(X)    ((((X) << 2) + (X)) << 1)
  90.  
  91. #define    todigit(c)    ((c) - '0')
  92. #define    tochar(n)    ((n) + '0')
  93.  
  94. #define    LONGINT        0x01        /* long integer */
  95. #define    LONGDBL        0x02        /* long double; unimplemented */
  96. #define    SHORTINT    0x04        /* short integer */
  97. #define    ALT        0x08        /* alternate form */
  98. #define    LADJUST        0x10        /* left adjustment */
  99. #define    ZEROPAD        0x20        /* zero (as opposed to blank) pad */
  100. #define    HEXPREFIX    0x40        /* add 0x or 0X prefix */
  101.  
  102. #ifndef __NO_FLOAT__
  103. #define __FLOATS__ 1
  104. #endif
  105.  
  106. #ifdef __FLOATS__
  107. # include    "flonum.h"
  108. #  if __STDC__
  109. static char *exponent(char *, int, int);
  110. static char *_round(double, int *, char *, char *, int, char *);
  111. static int  cvt(double, int, int, char *, int, char *, char *);
  112. #  else
  113. static char *exponent();
  114. static char *_round();
  115. static int  cvt();
  116. #  endif
  117. #endif
  118.  
  119. #ifdef __GNUC__
  120. #ifdef __M68020__
  121.  
  122. #define _ICONV(NUMBER, BASE, BUF)                \
  123. {                                \
  124.   long i;                            \
  125.   do                                \
  126.     {                                \
  127.       __asm__ volatile                        \
  128.     ("divull %3,%0:%1"                    \
  129.      : "=d"((long)(NUMBER)), "=d"(i)            \
  130.      : "0"((long)(NUMBER)), "d"((long)(BASE)));        \
  131.       *--(BUF) = digs[i];                    \
  132.     }                                \
  133.   while (NUMBER);                        \
  134. }
  135.  
  136. #else /* !__M68020 */  
  137.  
  138. #define _ICONV(NUMBER, BASE, BUF)                 \
  139. {                                \
  140.                                 \
  141.     while((NUMBER) > 65535L)                    \
  142.     {                                \
  143.         extern unsigned long __udivsi3(); /* quot = d0, rem = d1 */ \
  144.         register long i __asm ("d1");                    \
  145.     __asm__ volatile("
  146.         movl    %3,sp@-;
  147.          movl    %2,sp@-;
  148.          jsr    ___udivsi3;
  149.          addqw    #8,sp;
  150.          movl    d0,%0"                    \
  151.              : "=r"((long)NUMBER), "=d"(i)            \
  152.          : "0"((long)NUMBER), "r"((long)BASE)        \
  153.              : "d0", "d1", "a0", "a1");            \
  154.         *--BUF = digs[i];                    \
  155.     }                                \
  156.     do                                 \
  157.     {                                \
  158.             short i;                        \
  159.         __asm__ volatile("
  160.          divu    %3,%2;
  161.          swap    %0;
  162.          movw    %0,%1;
  163.          clrw    %0;
  164.                 swap    %0"                    \
  165.              : "=d"((long)NUMBER), "=g"(i)            \
  166.          : "0"((long)NUMBER), "g"((short)BASE));    \
  167.         *--BUF = digs[i];                    \
  168.     } while(NUMBER);                        \
  169. }
  170.  
  171. #endif /* __M68020 */
  172.  
  173. #else /* !__GNUC__ */
  174.  
  175. #define _ICONV(NUMBER, BASE, BUF)                 \
  176.   do {                                \
  177.     *--(BUF) = digs[(NUMBER) % (BASE)];                \
  178.     (NUMBER) /= (BASE);                        \
  179.   } while (NUMBER);
  180.  
  181. #endif /* __GNUC__ */
  182.  
  183.  
  184. int _doprnt(fp, fmt0, argp)
  185.     register FILE *fp;
  186.     const char *fmt0;
  187.     va_list argp;
  188. {
  189.     register const u_char *fmt;    /* format string */
  190.     register int ch;    /* character from fmt */
  191.     register int cnt;    /* return value accumulator */
  192.     register int n;        /* random handy integer */
  193.     register char *t;    /* buffer pointer */
  194. #ifdef    __FLOATS__
  195. /*    double _double;        *//* double precision arguments %[eEfgG] */
  196.     union double_di _dd;    /* _double is #defined to be _dd later on */
  197.     char softsign;        /* temporary negative sign for floats */
  198. #endif    __FLOATS__
  199.     u_long _ulong;        /* integer arguments %[diouxX] */
  200.     short base;        /* base for [diouxX] conversion */
  201.     short dprec;        /* decimal precision in [diouxX] */
  202.     short fieldsz;        /* field size expanded by sign, etc */
  203.     short flags;        /* flags as above */
  204.     short fpprec;        /* `extra' floating precision in [eEfgG] */
  205.     short prec;        /* precision from format (%.3d), or -1 */
  206.     short realsz;        /* field size expanded by decimal precision */
  207.     short size;        /* size of converted field or string */
  208.     short width;        /* width from format (%8d), or 0 */
  209.     char sign;        /* sign prefix (' ', '+', '-', or \0) */
  210.     char *digs;        /* digits for [diouxX] conversion */
  211.     char buf[BUF];        /* space for %c, %[diouxX], %[eEfgG] */
  212.  
  213.         t = buf;
  214.     fmt = (const u_char *) fmt0;
  215.     digs = "0123456789abcdef";
  216.     for (cnt = 0;; ++fmt) {
  217.         if ((ch = *fmt) == 0)
  218.             return (cnt);
  219.         if (ch != '%') {
  220.             PUTC(ch);
  221.             cnt++;
  222.             continue;
  223.         }
  224.         flags = 0; dprec = 0; fpprec = 0; width = 0;
  225.         prec = -1;
  226.         sign = '\0';
  227.  
  228. rflag:        switch (*++fmt) {
  229.         case ' ':
  230.             /*
  231.              * ``If the space and + flags both appear, the space
  232.              * flag will be ignored.''
  233.              *    -- ANSI X3J11
  234.              */
  235.             if (!sign)
  236.                 sign = ' ';
  237.             goto rflag;
  238.         case '#':
  239.             flags |= ALT;
  240.             goto rflag;
  241.         case '*':
  242.             /*
  243.              * ``A negative field width argument is taken as a
  244.              * - flag followed by a  positive field width.''
  245.              *    -- ANSI X3J11
  246.              * They don't exclude field widths read from args.
  247.              */
  248.             if ((width = (short)(va_arg(argp, int))) >= 0)
  249.                 goto rflag;
  250.             width = -width;
  251.             /* FALLTHROUGH */
  252.         case '-':
  253.             flags |= LADJUST;
  254.             goto rflag;
  255.         case '+':
  256.             sign = '+';
  257.             goto rflag;
  258.         case '.':
  259.             if (*++fmt == '*')
  260.                 n = va_arg(argp, int);
  261.             else {
  262.                 n = 0;
  263.                 while (isascii(*fmt) && isdigit(*fmt))
  264.                     n = TEN_MUL(n) + todigit(*fmt++);
  265.                 --fmt;
  266.             }
  267.             prec = n < 0 ? -1 : n;
  268.             goto rflag;
  269.         case '0':
  270.             /*
  271.              * ``Note that 0 is taken as a flag, not as the
  272.              * beginning of a field width.''
  273.              *    -- ANSI X3J11
  274.              */
  275.             flags |= ZEROPAD;
  276.             goto rflag;
  277.         case '1': case '2': case '3': case '4':
  278.         case '5': case '6': case '7': case '8': case '9':
  279.             n = 0;
  280.             do {
  281.                 n = TEN_MUL(n) + todigit(*fmt);
  282.             } while (isascii(*++fmt) && isdigit(*fmt));
  283.             width = n;
  284.             --fmt;
  285.             goto rflag;
  286.         case 'L':
  287.             flags |= LONGDBL;
  288.             goto rflag;
  289.         case 'h':
  290.             flags |= SHORTINT;
  291.             goto rflag;
  292.         case 'l':
  293.             flags |= LONGINT;
  294.             goto rflag;
  295.         case 'c':
  296.             *(t = buf) = va_arg(argp, int);
  297.             size = 1;
  298.             sign = '\0';
  299.             goto pforw;
  300.         case 'D':
  301.             flags |= LONGINT;
  302.             /*FALLTHROUGH*/
  303.         case 'd':
  304.         case 'i':
  305.             ARG(int);
  306.             if ((long)_ulong < 0) {
  307.                 _ulong = -_ulong;
  308.                 sign = '-';
  309.             }
  310.             base = 10;
  311.             goto number;
  312. #ifdef __FLOATS__
  313.         case 'e':
  314.         case 'E':
  315.         case 'f':
  316.         case 'g':
  317.         case 'G':
  318.  
  319. /* mjr: check for NANs */
  320. #define    _double _dd.d
  321.             _double = va_arg(argp, double);
  322.             if (_dd.i[0] == NAN_HI)
  323.             {
  324.                 t = buf;
  325.                 t = strcpy(t, "NaN");
  326.                 size = strlen(t);
  327.                 goto pforw;
  328.             }
  329.             /*
  330.              * don't do unrealistic precision; just pad it with
  331.              * zeroes later, so buffer size stays rational.
  332.              */
  333.             if (prec > MAXFRACT) {
  334.                 if ((*fmt != 'g' && *fmt != 'G') || (flags&ALT))
  335.                     fpprec = prec - MAXFRACT;
  336.                 prec = MAXFRACT;
  337.             }
  338.             else if (prec == -1)
  339.                 prec = DEFPREC;
  340.             /*
  341.              * softsign avoids negative 0 if _double is < 0 and
  342.              * no significant digits will be shown
  343.              */
  344.             if (_double < 0) {
  345.                 softsign = '-';
  346.                 _double = -_double;
  347.             }
  348.             else
  349.                 softsign = 0;
  350. /* mjr: check for +-INFINITY */
  351.             if (((unsigned long)_dd.i[0] == INF_HI) &&
  352.                 ((unsigned long)_dd.i[1] == INF_LO))
  353.               {
  354.                 t = buf;
  355.                 if(softsign == 0)
  356.                 t = strcpy(t, "+Inf");
  357.                 else
  358.                 t = strcpy(t, "-Inf");
  359.                 size = strlen(t);
  360.                 goto pforw;
  361.             }
  362.             /*
  363.              * cvt may have to round up past the "start" of the
  364.              * buffer, i.e. ``printf("%.2f", (double)9.999);'';
  365.              * if the first char isn't '\0', it did.
  366.              */
  367.             *buf = '\0';
  368.             size = cvt(_double, (int)prec, (int)flags, &softsign,
  369.                    *fmt, buf, buf + (int)sizeof(buf)); 
  370.             if (softsign)
  371.                 sign = '-';
  372.             t = *buf ? buf : buf + 1;
  373.             goto pforw;
  374. #endif /* __FLOATS__ */
  375.         case 'n':
  376.             if (flags & LONGINT)
  377.                 *va_arg(argp, long *) = cnt;
  378.             else if (flags & SHORTINT)
  379.                 *va_arg(argp, short *) = cnt;
  380.             else
  381.                 *va_arg(argp, int *) = cnt;
  382.             break;
  383.         case 'O':
  384.             flags |= LONGINT;
  385.             /*FALLTHROUGH*/
  386.         case 'o':
  387.             ARG(unsigned);
  388.             base = 8;
  389.             goto nosign;
  390.         case 'p':
  391.             /*
  392.              * ``The argument shall be a pointer to void.  The
  393.              * value of the pointer is converted to a sequence
  394.              * of printable characters, in an implementation-
  395.              * defined manner.''
  396.              *    -- ANSI X3J11
  397.              */
  398.             /* NOSTRICT */
  399.             _ulong = (u_long)va_arg(argp, void *);
  400.             base = 16;
  401.             goto nosign;
  402.         case 's':
  403.             if ((t = va_arg(argp, char *)) == 0)
  404.                 t = "(null)";
  405.             if (prec >= 0) {
  406.                 /*
  407.                  * can't use strlen; can only look for the
  408.                  * NUL in the first `prec' characters, and
  409.                  * strlen() will go further.
  410.                  */
  411. #ifdef __STDC__
  412.                 char *p;
  413.                 void *memchr(const void *, int, size_t);
  414. #else
  415.                 char *p, *memchr();
  416. #endif
  417.  
  418.                 if ((p = (char *)memchr(t, 0, (size_t)prec)) != NULL) {
  419.                     size = p - t;
  420.                     if (size > prec)
  421.                         size = prec;
  422.                 } else
  423.                     size = prec;
  424.             } else
  425.                 size = (int)strlen(t);
  426.             sign = '\0';
  427.             goto pforw;
  428.         case 'U':
  429.             flags |= LONGINT;
  430.             /*FALLTHROUGH*/
  431.         case 'u':
  432.             ARG(unsigned);
  433.             base = 10;
  434.             goto nosign;
  435.         case 'X':
  436.             digs = "0123456789ABCDEF";
  437.             /* FALLTHROUGH */
  438.         case 'x':
  439.             ARG(unsigned);
  440.             base = 16;
  441.             /* leading 0x/X only if non-zero */
  442.             if (flags & ALT && _ulong != 0)
  443.                 flags |= HEXPREFIX;
  444.  
  445.             /* unsigned conversions */
  446. nosign:            sign = '\0';
  447.             /*
  448.              * ``... diouXx conversions ... if a precision is
  449.              * specified, the 0 flag will be ignored.''
  450.              *    -- ANSI X3J11
  451.              */
  452. number:            if ((dprec = prec) >= 0)
  453.                 flags &= ~ZEROPAD;
  454.  
  455.             /*
  456.              * ``The result of converting a zero value with an
  457.              * explicit precision of zero is no characters.''
  458.              *    -- ANSI X3J11
  459.              */
  460.             t = buf + BUF;
  461.             if (_ulong != 0 || prec != 0) {
  462.                 _ICONV(_ulong, base, t);
  463.                 digs = "0123456789abcdef";
  464.                 if (flags & ALT && base == 8 && *t != '0')
  465.                     *--t = '0'; /* octal leading 0 */
  466.             }
  467.             size = buf + BUF - t;
  468.  
  469. pforw:
  470.             /*
  471.              * All reasonable formats wind up here.  At this point,
  472.              * `t' points to a string which (if not flags&LADJUST)
  473.              * should be padded out to `width' places.  If
  474.              * flags&ZEROPAD, it should first be prefixed by any
  475.              * sign or other prefix; otherwise, it should be blank
  476.              * padded before the prefix is emitted.  After any
  477.              * left-hand padding and prefixing, emit zeroes
  478.              * required by a decimal [diouxX] precision, then print
  479.              * the string proper, then emit zeroes required by any
  480.              * leftover floating precision; finally, if LADJUST,
  481.              * pad with blanks.
  482.              */
  483.  
  484.             /*
  485.              * compute actual size, so we know how much to pad
  486.              * fieldsz excludes decimal prec; realsz includes it
  487.              */
  488.             fieldsz = size + fpprec;
  489.             if (sign)
  490.                 fieldsz++;
  491.             if (flags & HEXPREFIX)
  492.                 fieldsz += 2;
  493.             realsz = dprec > fieldsz ? dprec : fieldsz;
  494.  
  495.             /* right-adjusting blank padding */
  496.             if ((flags & (LADJUST|ZEROPAD)) == 0 && width)
  497.                 for (n = realsz; n < width; n++)
  498.                     PUTC(' ');
  499.             /* prefix */
  500.             if (sign)
  501.                 PUTC(sign);
  502.             if (flags & HEXPREFIX) {
  503.                 PUTC('0');
  504.                 PUTC((char)*fmt);
  505.             }
  506.             /* right-adjusting zero padding */
  507.             if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
  508.                 for (n = realsz; n < width; n++)
  509.                     PUTC('0');
  510.             /* leading zeroes from decimal precision */
  511.             for (n = fieldsz; n < dprec; n++)
  512.                 PUTC('0');
  513.  
  514.             /* the string or number proper */
  515.             for (n = size; --n >= 0; )
  516.                 PUTC(*t++);
  517.             /* trailing f.p. zeroes */
  518.             while (--fpprec >= 0)
  519.                 PUTC('0');
  520.             /* left-adjusting padding (always blank) */
  521.             if (flags & LADJUST)
  522.                 for (n = realsz; n < width; n++)
  523.                     PUTC(' ');
  524.             /* finally, adjust cnt */
  525.             cnt += width > realsz ? width : realsz;
  526.             break;
  527.         case '\0':    /* "%?" prints ?, unless ? is NULL */
  528.             return (cnt);
  529.         default:
  530.             PUTC((char)*fmt);
  531.             cnt++;
  532.         }
  533.     }
  534.     /* NOTREACHED */
  535. }
  536.  
  537. #ifdef __FLOATS__
  538. static int
  539. cvt(number,prec,flags, signp, fmtch, startp, endp)
  540.     double number;
  541.     register int prec;
  542.     int flags;
  543.     int fmtch;
  544.     char *signp, *startp, *endp;
  545. {
  546.     register char *p, *t;
  547.     register double fract;
  548.     int dotrim, expcnt, gformat;
  549.     double integer, tmp, modf __PROTO((double, double *));
  550.     char *exponent __PROTO((char *, int, int)),
  551.          *_round __PROTO((double, int *, char *, char *, int, char *));
  552.  
  553.     dotrim = expcnt = gformat = 0;
  554.     fract = modf(number, &integer);
  555.  
  556.     /* get an extra slot for rounding. */
  557.     t = ++startp;
  558.  
  559.     /*
  560.      * get integer portion of number; put into the end of the buffer; the
  561.      * .01 is added for modf(356.0 / 10, &integer) returning .59999999...
  562.      */
  563.     for (p = endp - 1; integer; ++expcnt) {
  564.         tmp = modf(integer / 10, &integer);
  565.         *p-- = tochar((int)((tmp + .01) * 10));
  566.     }
  567.     switch(fmtch) {
  568.     case 'f':
  569.         /* reverse integer into beginning of buffer */
  570.         if (expcnt)
  571.             for (; ++p < endp; *t++ = *p);
  572.         else
  573.             *t++ = '0';
  574.         /*
  575.          * if precision required or alternate flag set, add in a
  576.          * decimal point.
  577.          */
  578.         if (prec || flags&ALT)
  579.             *t++ = '.';
  580.         /* if requires more precision and some fraction left */
  581.         if (fract) {
  582.             if (prec)
  583.                 do {
  584.                     fract = modf(fract * 10, &tmp);
  585.                     *t++ = tochar((int)tmp);
  586.                 } while (--prec && fract);
  587.             if (fract)
  588.                 startp = _round(fract, (int *)NULL, startp,
  589.                     t - 1, (char)0, signp);
  590.         }
  591.         for (; prec--; *t++ = '0');
  592.         break;
  593.     case 'e':
  594.     case 'E':
  595. eformat:    if (expcnt) {
  596.             *t++ = *++p;
  597.             if (prec || flags&ALT)
  598.                 *t++ = '.';
  599.             /* if requires more precision and some integer left */
  600.             for (; prec && ++p < endp; --prec)
  601.                 *t++ = *p;
  602.             /*
  603.              * if done precision and more of the integer component,
  604.              * round using it; adjust fract so we don't re-round
  605.              * later.
  606.              */
  607.             if (!prec && ++p < endp) {
  608.                 fract = 0;
  609.                 startp = _round((double)0, &expcnt, startp,
  610.                     t - 1, *p, signp);
  611.             }
  612.             /* adjust expcnt for digit in front of decimal */
  613.             --expcnt;
  614.         }
  615.         /* until first fractional digit, decrement exponent */
  616.         else if (fract) {
  617.             /* adjust expcnt for digit in front of decimal */
  618.             for (expcnt = -1;; --expcnt) {
  619.                 fract = modf(fract * 10, &tmp);
  620.                 if (tmp)
  621.                     break;
  622.             }
  623.             *t++ = tochar((int)tmp);
  624.             if (prec || flags&ALT)
  625.                 *t++ = '.';
  626.         }
  627.         else {
  628.             *t++ = '0';
  629.             if (prec || flags&ALT)
  630.                 *t++ = '.';
  631.         }
  632.         /* if requires more precision and some fraction left */
  633.         if (fract) {
  634.             if (prec)
  635.                 do {
  636.                     fract = modf(fract * 10, &tmp);
  637.                     *t++ = tochar((int)tmp);
  638.                 } while (--prec && fract);
  639.             if (fract)
  640.                 startp = _round(fract, &expcnt, startp,
  641.                     t - 1, (char)0, signp);
  642.         }
  643.         /* if requires more precision */
  644.         for (; prec--; *t++ = '0');
  645.  
  646.         /* unless alternate flag, trim any g/G format trailing 0's */
  647.         if (gformat && !(flags&ALT)) {
  648.             while (t > startp && *--t == '0');
  649.             if (*t == '.')
  650.                 --t;
  651.             ++t;
  652.         }
  653.         t = exponent(t, expcnt, fmtch);
  654.         break;
  655.     case 'g':
  656.     case 'G':
  657.         /* a precision of 0 is treated as a precision of 1. */
  658.         if (!prec)
  659.             ++prec;
  660.         /*
  661.          * ``The style used depends on the value converted; style e
  662.          * will be used only if the exponent resulting from the
  663.          * conversion is less than -4 or greater than the precision.''
  664.          *    -- ANSI X3J11
  665.          */
  666.         if (expcnt > prec || (!expcnt && fract && fract < .0001)) {
  667.             /*
  668.              * g/G format counts "significant digits, not digits of
  669.              * precision; for the e/E format, this just causes an
  670.              * off-by-one problem, i.e. g/G considers the digit
  671.              * before the decimal point significant and e/E doesn't
  672.              * count it as precision.
  673.              */
  674.             --prec;
  675.             fmtch -= 2;        /* G->E, g->e */
  676.             gformat = 1;
  677.             goto eformat;
  678.         }
  679.         /*
  680.          * reverse integer into beginning of buffer,
  681.          * note, decrement precision
  682.          */
  683.         if (expcnt)
  684.             for (; ++p < endp; *t++ = *p, --prec);
  685.         else
  686.             *t++ = '0';
  687.         /*
  688.          * if precision required or alternate flag set, add in a
  689.          * decimal point.  If no digits yet, add in leading 0.
  690.          */
  691.         if (prec || flags&ALT) {
  692.             dotrim = 1;
  693.             *t++ = '.';
  694.         }
  695.         else
  696.             dotrim = 0;
  697.         /* if requires more precision and some fraction left */
  698.         if (fract) {
  699.             if (prec) {
  700.                 if (0 == expcnt) {
  701.                     /* if no significant digits yet */
  702.                     do {
  703.                         fract = modf(fract * 10, &tmp);
  704.                         *t++ = tochar((int)tmp);
  705.                     } while(!tmp);
  706.                     prec--;
  707.                 }
  708.                 while (prec && fract) {
  709.                     fract = modf(fract * 10, &tmp);
  710.                     *t++ = tochar((int)tmp);
  711.                     prec--;
  712.                 }
  713.             }
  714.             if (fract)
  715.                 startp = _round(fract, (int *)NULL, startp,
  716.                     t - 1, (char)0, signp);
  717.         }
  718.         /* alternate format, adds 0's for precision, else trim 0's */
  719.         if (flags&ALT)
  720.             for (; prec--; *t++ = '0');
  721.         else if (dotrim) {
  722.             while (t > startp && *--t == '0');
  723.             if (*t != '.')
  724.                 ++t;
  725.         }
  726.     }
  727.     return((int)(t - startp));
  728. }
  729.  
  730. static char *
  731. _round(fract, exp, start, end, ch, signp)
  732.     double fract;
  733.     int *exp;
  734.     register char *start, *end;
  735.     int ch;
  736.     char *signp;
  737. {
  738.     double tmp;
  739.  
  740.     if (fract)
  741.         (void)modf(fract * 10, &tmp);
  742.     else
  743.         tmp = todigit(ch);
  744.     if (tmp > 4)
  745.         for (;; --end) {
  746.             if (*end == '.')
  747.                 --end;
  748.             if (++*end <= '9')
  749.                 break;
  750.             *end = '0';
  751.             if (end == start) {
  752.                 if (exp) {    /* e/E; increment exponent */
  753.                     *end = '1';
  754.                     ++*exp;
  755.                 }
  756.                 else {        /* f; add extra digit */
  757.                     *--end = '1';
  758.                     --start;
  759.                 }
  760.                 break;
  761.             }
  762.         }
  763.     /* ``"%.3f", (double)-0.0004'' gives you a negative 0. */
  764.     else if (*signp == '-')
  765.         for (;; --end) {
  766.             if (*end == '.')
  767.                 --end;
  768.             if (*end != '0')
  769.                 break;
  770.             if (end == start)
  771.                 *signp = 0;
  772.         }
  773.     return(start);
  774. }
  775.  
  776. static char *
  777. exponent(p, exp, fmtch)
  778.     register char *p;
  779.     register int exp;
  780.     int fmtch;
  781. {
  782.     register char *t;
  783.     char expbuf[MAXEXP];
  784.  
  785.     *p++ = fmtch;
  786.     if (exp < 0) {
  787.         exp = -exp;
  788.         *p++ = '-';
  789.     }
  790.     else
  791.         *p++ = '+';
  792.     t = expbuf + MAXEXP;
  793.     if (exp > 9) {
  794.         do {
  795.             *--t = tochar(exp % 10);
  796.         } while ((exp /= 10) > 9);
  797.         *--t = tochar(exp);
  798.         for (; t < expbuf + MAXEXP; *p++ = *t++);
  799.     }
  800.     else {
  801.         *p++ = '0';
  802.         *p++ = tochar(exp);
  803.     }
  804.     return(p);
  805. }
  806. #endif __FLOATS__
  807.