aboutsummaryrefslogtreecommitdiffstats
path: root/trio/trio.c
blob: 61d7c40b64a72e598022c70feb2096bb57111f21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
 <title>TRIO</title>
 <link href="trio.css" rel="stylesheet" type="text/css">
</head>
<body>
<!-- Generated by Doxygen 1.2.12 -->
<center>
<a class="qindex" href="index.html">Main Page</a> &nbsp; <a class="qindex" href="modules.html">Modules</a> &nbsp; </center>
<hr><h1>Special Quantifies.</h1>Functions to detect and fabricate special quantities in floating-point numbers. 
<a href="#_details">More...</a><table border=0 cellpadding=0 cellspacing=0>
<tr><td colspan=2><br><h2>Functions</h2></td></tr>
<tr><td nowrap align=right valign=top>double&nbsp;</td><td valign=bottom><a class="el" href="group___special_quantities.html#a1">trio_nzero</a> (void)</td></tr>
<tr><td>&nbsp;</td><td><font size=-1><em>Generate negative zero.</em> <a href="#a1">More...</a><em></em></font><br><br></td></tr>
<tr><td nowrap align=right valign=top>double&nbsp;</td><td valign=bottom><a class="el" href="group___special_quantities.html#a2">trio_pinf</a> (void)</td></tr>
<tr><td>&nbsp;</td><td><font size=-1><em>Generate positive infinity.</em> <a href="#a2">More...</a><em></em></font><br><br></td></tr>
<tr><td nowrap align=right valign=top>double&nbsp;</td><td valign=bottom><a class="el" href="group___special_quantities.html#a3">trio_ninf</a> (void)</td></tr>
<tr><td>&nbsp;</td><td><font size=-1><em>Generate negative infinity.</em> <a href="#a3">More...</a><em></em></font><br><br></td></tr>
<tr><td nowrap align=right valign=top>double&nbsp;</td><td valign=bottom><a class="el" href="group___special_quantities.html#a4">trio_nan</a> (void)</td></tr>
<tr><td>&nbsp;</td><td><font size=-1><em>Generate NaN.</em> <a href="#a4">More...</a><em></em></font><br><br></td></tr>
<tr><td nowrap align=right valign=top>int&nbsp;</td><td valign=bottom><a class="el" href="group___special_quantities.html#a5">trio_isnan</a> (double number)</td></tr>
<tr><td>&nbsp;</td><td><font size=-1><em>Check for NaN.</em> <a href="#a5">More...</a><em></em></font><br><br></td></tr>
<tr><td nowrap align=right valign=top>int&nbsp;</td><td valign=bottom><a class="el" href="group___special_quantities.html#a6">trio_isinf</a> (double number)</td></tr>
<tr><td>&nbsp;</td><td><font size=-1><em>Check for infinity.</em> <a href="#a6">More...</a><em></em></font><br><br></td></tr>
<tr><td nowrap align=right valign=top>int&nbsp;</td><td valign=bottom><a class="el" href="group___special_quantities.html#a7">trio_isfinite</a> (double number)</td></tr>
<tr><td>&nbsp;</td><td><font size=-1><em>Check for finity.</em> <a href="#a7">More...</a><em></em></font><br><br></td></tr>
<tr><td nowrap align=right valign=top>int&nbsp;</td><td valign=bottom><a class="el" href="group___special_quantities.html#a9">trio_signbit</a> (double number)</td></tr>
<tr><td>&nbsp;</td><td><font size=-1><em>Examine the sign of a number.</em> <a href="#a9">More...</a><em></em></font><br><br></td></tr>
<tr><td nowrap align=right valign=top>int&nbsp;</td><td valign=bottom><a class="el" href="group___special_quantities.html#a10">trio_fpclassify</a> (double number)</td></tr>
<tr><td>&nbsp;</td><td><font size=-1><em>Examine the class of a number.</em> <a href="#a10">More...</a><em></em></font><br><br></td></tr>
</table>
<hr><a name="_details"></a><h2>Detailed Description</h2>
Functions to detect and fabricate special quantities in floating-point numbers.
<p>
<b>SYNOPSIS</b>
<p>
<div class="fragment"><pre>
cc ... -ltrio -lm

#include &lt;trionan.h&gt;
</pre></div>
<p>
<b>DESCRIPTION</b>
<p>
Certain arithmetical operations does not result in normal numbers. Instead they result in special quantities that must be handled differently by the floating-point hardware. These includes Infinity and Not-A-Number (NaN).
<p>
For example, 0/0 (zero divided by zero) yields NaN. Any operation which involves a NaN will result in NaN. Any comparison involving NaN will be unsuccessful, even if NaN is compared to NaN.
<p>
These special quantities are represented with special bit patterns by the floating-point hardware, and this bit patterns depend on the hardware. There may even be hardware that does not support special quantities, so the functions in this module are not guaranteed to work on all platforms.
<p>
The approach used in this module is to (in decreasing order of importance) <ul>
<li> Use C99 functionality when available. <li> Use IEEE 754-1985 bit patterns if possible. <li> Use platform-specific techniques.</ul>
<b>NOTES</b>
<p>
This module does not depend on the rest of trio, and can thus be reused separately. The following files are necessary: <ul>
<li> <code>triodef.h</code> <li> <code>trionan.h</code> <li> <code>trionan.c</code> </ul>
<hr><h2>Function Documentation</h2>
<a name="a10" doxytag="trionan.c::trio_fpclassify"></a><p>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
  <tr>
    <td class="md">
      <table cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td class="md" nowrap valign="top"> int trio_fpclassify </td>
          <td class="md" valign="top">(&nbsp;</td>
          <td class="md" nowrap valign="top">double&nbsp;</td>
          <td class="mdname1" valign="top" nowrap>&nbsp; <em>number</em>          </td>
          <td class="md" valign="top">)&nbsp;</td>
          <td class="md" nowrap></td>
        </tr>

      </table>
    </td>
  </tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>

<p>
Examine the class of a number.
<p>
<dl compact><dt><b>
Parameters: </b><dd>
<table border=0 cellspacing=2 cellpadding=0>
<tr><td valign=top><em>number</em>&nbsp;</td><td>
An arbitrary floating-point number. </td></tr>
</table>
</dl><dl compact><dt><b>
Returns: </b><dd>
Enumerable value indicating the class of <code>number</code> </dl>    </td>
  </tr>
</table>
<a name="a7" doxytag="trionan.c::trio_isfinite"></a><p>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
  <tr>
    <td class="md">
      <table cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td class="md" nowrap valign="top"> int trio_isfinite </td>
          <td class="md" valign="top">(&nbsp;</td>
          <td class="md" nowrap valign="top">double&nbsp;</td>
          <td class="mdname1" valign="top" nowrap>&nbsp; <em>number</em>          </td>
          <td class="md" valign="top">)&nbsp;</td>
          <td class="md" nowrap></td>
        </tr>

      </table>
    </td>
  </tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>

<p>
Check for finity.
<p>
<dl compact><dt><b>
Parameters: </b><dd>
<table border=0 cellspacing=2 cellpadding=0>
<tr><td valign=top><em>number</em>&nbsp;</td><td>
An arbitrary floating-point number. </td></tr>
</table>
</dl><dl compact><dt><b>
Returns: </b><dd>
Boolean value indicating whether or not the number is a finite. </dl>    </td>
  </tr>
</table>
<a name="a6" doxytag="trionan.c::trio_isinf"></a><p>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
  <tr>
    <td class="md">
      <table cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td class="md" nowrap valign="top"> int trio_isinf </td>
          <td class="md" valign="top">(&nbsp;</td>
          <td class="md" nowrap valign="top">double&nbsp;</td>
          <td class="mdname1" valign="top" nowrap>&nbsp; <em>number</em>          </td>
          <td class="md" valign="top">)&nbsp;</td>
          <td class="md" nowrap></td>
        </tr>

      </table>
    </td>
  </tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>

<p>
Check for infinity.
<p>
<dl compact><dt><b>
Parameters: </b><dd>
<table border=0 cellspacing=2 cellpadding=0>
<tr><td valign=top><em>number</em>&nbsp;</td><td>
An arbitrary floating-point number. </td></tr>
</table>
</dl><dl compact><dt><b>
Returns: </b><dd>
1 if positive infinity, -1 if negative infinity, 0 otherwise. </dl>    </td>
  </tr>
</table>
<a name="a5" doxytag="trionan.c::trio_isnan"></a><p>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
  <tr>
    <td class="md">
      <table cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td class="md" nowrap valign="top"> int trio_isnan </td>
          <td class="md" valign="top">(&nbsp;</td>
          <td class="md" nowrap valign="top">double&nbsp;</td>
          <td class="mdname1" valign="top" nowrap>&nbsp; <em>number</em>          </td>
          <td class="md" valign="top">)&nbsp;</td>
          <td class="md" nowrap></td>
        </tr>

      </table>
    </td>
  </tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>

<p>
Check for NaN.
<p>
<dl compact><dt><b>
Parameters: </b><dd>
<table border=0 cellspacing=2 cellpadding=0>
<tr><td valign=top><em>number</em>&nbsp;</td><td>
An arbitrary floating-point number. </td></tr>
</table>
</dl><dl compact><dt><b>
Returns: </b><dd>
Boolean value indicating whether or not the number is a NaN. </dl>    </td>
  </tr>
</table>
<a name="a4" doxytag="trionan.c::trio_nan"></a><p>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
  <tr>
    <td class="md">
      <table cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td class="md" nowrap valign="top"> double trio_nan </td>
          <td class="md" valign="top">(&nbsp;</td>
          <td class="md" nowrap valign="top">void&nbsp;</td>
          <td class="mdname1" valign="top" nowrap>&nbsp;          </td>
          <td class="md" valign="top">)&nbsp;</td>
          <td class="md" nowrap></td>
        </tr>

      </table>
    </td>
  </tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>

<p>
Generate NaN.
<p>
<dl compact><dt><b>
Returns: </b><dd>
Floating-point representation of NaN. </dl>    </td>
  </tr>
</table>
<a name="a3" doxytag="trionan.c::trio_ninf"></a><p>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
  <tr>
    <td class="md">
      <table cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td class="md" nowrap valign="top"> double trio_ninf </td>
          <td class="md" valign="top">(&nbsp;</td>
          <td class="md" nowrap valign="top">void&nbsp;</td>
          <td class="mdname1" valign="top" nowrap>&nbsp;          </td>
          <td class="md" valign="top">)&nbsp;</td>
          <td class="md" nowrap></td>
        </tr>

      </table>
    </td>
  </tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>

<p>
Generate negative infinity.
<p>
<dl compact><dt><b>
Returns: </b><dd>
Floating-point value of negative infinity. </dl>    </td>
  </tr>
</table>
<a name="a1" doxytag="trionan.c::trio_nzero"></a><p>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
  <tr>
    <td class="md">
      <table cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td class="md" nowrap valign="top"> double trio_nzero </td>
          <td class="md" valign="top">(&nbsp;</td>
          <td class="md" nowrap valign="top">void&nbsp;</td>
          <td class="mdname1" valign="top" nowrap>&nbsp;          </td>
          <td class="md" valign="top">)&nbsp;</td>
          <td class="md" nowrap></td>
        </tr>

      </table>
    </td>
  </tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>

<p>
Generate negative zero.
<p>
<dl compact><dt><b>
Returns: </b><dd>
Floating-point representation of negative zero. </dl>    </td>
  </tr>
</table>
<a name="a2" doxytag="trionan.c::trio_pinf"></a><p>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
  <tr>
    <td class="md">
      <table cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td class="md" nowrap valign="top"> double trio_pinf </td>
          <td class="md" valign="top">(&nbsp;</td>
          <td class="md" nowrap valign="top">void&nbsp;</td>
          <td class="mdname1" valign="top" nowrap>&nbsp;          </td>
          <td class="md" valign="top">)&nbsp;</td>
          <td class="md" nowrap></td>
        </tr>

      </table>
    </td>
  </tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>

<p>
Generate positive infinity.
<p>
<dl compact><dt><b>
Returns: </b><dd>
Floating-point representation of positive infinity. </dl>    </td>
  </tr>
</table>
<a name="a9" doxytag="trionan.c::trio_signbit"></a><p>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
  <tr>
    <td class="md">
      <table cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td class="md" nowrap valign="top"> int trio_signbit </td>
          <td class="md" valign="top">(&nbsp;</td>
          <td class="md" nowrap valign="top">double&nbsp;</td>
          <td class="mdname1" valign="top" nowrap>&nbsp; <em>number</em>          </td>
          <td class="md" valign="top">)&nbsp;</td>
          <td class="md" nowrap></td>
        </tr>

      </table>
    </td>
  </tr>
</table>
<table cellspacing=5 cellpadding=0 border=0>
  <tr>
    <td>
      &nbsp;
    </td>
    <td>

<p>
Examine the sign of a number.
<p>
<dl compact><dt><b>
Parameters: </b><dd>
<table border=0 cellspacing=2 cellpadding=0>
<tr><td valign=top><em>number</em>&nbsp;</td><td>
An arbitrary floating-point number. </td></tr>
</table>
</dl><dl compact><dt><b>
Returns: </b><dd>
Boolean value indicating whether or not the number has the sign bit set (i.e. is negative). </dl>    </td>
  </tr>
</table>
<HR>
<center class="copyright">Copyright (C) 2001 Bj&oslash;rn Reese and Daniel Stenberg.</center>
</body>
</html>
'#n3126'>3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765
/*************************************************************************
 *
 * $Id: trio.c,v 1.129 2009/09/20 11:37:15 breese Exp $
 *
 * Copyright (C) 1998, 2009 Bjorn Reese and Daniel Stenberg.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND
 * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
 *
 *************************************************************************
 *
 * A note to trio contributors:
 *
 * Avoid heap allocation at all costs to ensure that the trio functions
 * are async-safe. The exceptions are the printf/fprintf functions, which
 * uses fputc, and the asprintf functions and the <alloc> modifier, which
 * by design are required to allocate form the heap.
 *
 ************************************************************************/

/*
 * TODO:
 *  - Scan is probably too permissive about its modifiers.
 *  - C escapes in %#[] ?
 *  - Multibyte characters (done for format parsing, except scan groups)
 *  - Complex numbers? (C99 _Complex)
 *  - Boolean values? (C99 _Bool)
 *  - C99 NaN(n-char-sequence) missing. The n-char-sequence can be used
 *    to print the mantissa, e.g. NaN(0xc000000000000000)
 *  - Should we support the GNU %a alloc modifier? GNU has an ugly hack
 *    for %a, because C99 used %a for other purposes. If specified as
 *    %as or %a[ it is interpreted as the alloc modifier, otherwise as
 *    the C99 hex-float. This means that you cannot scan %as as a hex-float
 *    immediately followed by an 's'.
 *  - Scanning of collating symbols.
 */

/*************************************************************************
 * Trio include files
 */
#include "triodef.h"
#include "trio.h"
#include "triop.h"

#if defined(TRIO_EMBED_NAN)
# define TRIO_PUBLIC_NAN static
# if TRIO_FEATURE_FLOAT
#  define TRIO_FUNC_NAN
#  define TRIO_FUNC_NINF
#  define TRIO_FUNC_PINF
#  define TRIO_FUNC_FPCLASSIFY_AND_SIGNBIT
#  define TRIO_FUNC_ISINF
# endif
#endif
#include "trionan.h"

#if defined(TRIO_EMBED_STRING)
# define TRIO_PUBLIC_STRING static
# define TRIO_FUNC_LENGTH
# define TRIO_FUNC_LENGTH_MAX
# define TRIO_FUNC_TO_LONG
# if TRIO_FEATURE_LOCALE
#  define TRIO_FUNC_COPY_MAX
# endif
# if TRIO_FEATURE_DYNAMICSTRING
#  define TRIO_FUNC_XSTRING_DUPLICATE
# endif
# if TRIO_EXTENSION && TRIO_FEATURE_SCANF
#  define TRIO_FUNC_EQUAL_LOCALE
# endif
# if TRIO_FEATURE_ERRNO
#  define TRIO_FUNC_ERROR
# endif
# if TRIO_FEATURE_FLOAT && TRIO_FEATURE_SCANF
#  define TRIO_FUNC_TO_DOUBLE
# endif
# if TRIO_FEATURE_DYNAMICSTRING
#  define TRIO_FUNC_STRING_EXTRACT
# endif
# if TRIO_FEATURE_DYNAMICSTRING
#  define TRIO_FUNC_STRING_TERMINATE
# endif
# if TRIO_FEATURE_USER_DEFINED
#  define TRIO_FUNC_DUPLICATE
# endif
# if TRIO_FEATURE_DYNAMICSTRING
#  define TRIO_FUNC_STRING_DESTROY
# endif
# if TRIO_FEATURE_USER_DEFINED
#  define TRIO_FUNC_DESTROY
# endif
# if TRIO_FEATURE_USER_DEFINED || (TRIO_FEATURE_FLOAT && TRIO_FEATURE_SCANF)
#  define TRIO_FUNC_EQUAL
# endif
# if TRIO_FEATURE_USER_DEFINED || TRIO_FEATURE_SCANF
#  define TRIO_FUNC_EQUAL_CASE
# endif
# if (TRIO_EXTENSION && TRIO_FEATURE_SCANF)
#  define TRIO_FUNC_EQUAL_MAX
# endif
# if TRIO_FEATURE_SCANF
#  define TRIO_FUNC_TO_UPPER
# endif
# if TRIO_FEATURE_DYNAMICSTRING
#  define TRIO_FUNC_XSTRING_APPEND_CHAR
# endif
#endif
#include "triostr.h"

/**************************************************************************
 *
 * Definitions
 *
 *************************************************************************/

#include <limits.h>
#if TRIO_FEATURE_FLOAT
# include <math.h>
# include <float.h>
#endif

#if defined(__STDC_ISO_10646__) || defined(MB_LEN_MAX) || defined(USE_MULTIBYTE) || TRIO_FEATURE_WIDECHAR
# if !defined(TRIO_PLATFORM_WINCE)
#  define TRIO_COMPILER_SUPPORTS_MULTIBYTE
#  if !defined(MB_LEN_MAX)
#   define MB_LEN_MAX 6
#  endif
# endif
#endif

#if (TRIO_COMPILER_VISUALC - 0 >= 1100) || defined(TRIO_COMPILER_BORLAND)
# define TRIO_COMPILER_SUPPORTS_VISUALC_INT
#endif

#if TRIO_FEATURE_FLOAT
# if defined(PREDEF_STANDARD_C99) \
  || defined(PREDEF_STANDARD_UNIX03)
#  if !defined(HAVE_FLOORL) && !defined(TRIO_NO_FLOORL)
#   define HAVE_FLOORL
#  endif
#  if !defined(HAVE_CEILL) && !defined(TRIO_NO_CEILL)
#   define HAVE_CEILL
#  endif
#  if !defined(HAVE_POWL) && !defined(TRIO_NO_POWL)
#   define HAVE_POWL
#  endif
#  if !defined(HAVE_FMODL) && !defined(TRIO_NO_FMODL)
#   define HAVE_FMODL
#  endif
#  if !defined(HAVE_LOG10L) && !defined(TRIO_NO_LOG10L)
#   define HAVE_LOG10L
#  endif
# endif
# if defined(TRIO_COMPILER_VISUALC)
#  if defined(floorl)
#   define HAVE_FLOORL
#  endif
#  if defined(ceill)
#   define HAVE_CEILL
#  endif
#  if defined(powl)
#   define HAVE_POWL
#  endif
#  if defined(fmodl)
#   define HAVE_FMODL
#  endif
#  if defined(log10l)
#   define HAVE_LOG10L
#  endif
# endif
#endif

/*************************************************************************
 * Generic definitions
 */

#if !(defined(DEBUG) || defined(NDEBUG))
# define NDEBUG
#endif

#include <assert.h>
#include <ctype.h>
#if defined(PREDEF_STANDARD_C99) && !defined(isascii)
# define isascii(x) ((x) & 0x7F)
#endif
#if defined(TRIO_COMPILER_ANCIENT)
# include <varargs.h>
#else
# include <stdarg.h>
#endif
#include <stddef.h>
#if defined(TRIO_PLATFORM_WINCE)
extern int errno;
#else
# include <errno.h>
#endif

#ifndef NULL
# define NULL 0
#endif
#define NIL ((char)0)
#ifndef FALSE
# define FALSE (1 == 0)
# define TRUE (! FALSE)
#endif
#define BOOLEAN_T int

/* mincore() can be used for debugging purposes */
#define VALID(x) (NULL != (x))

#if TRIO_FEATURE_ERRORCODE
  /*
   * Encode the error code and the position. This is decoded
   * with TRIO_ERROR_CODE and TRIO_ERROR_POSITION.
   */
# define TRIO_ERROR_RETURN(x,y) (- ((x) + ((y) << 8)))
#else
# define TRIO_ERROR_RETURN(x,y) (-1)
#endif

typedef unsigned long trio_flags_t;


/*************************************************************************
 * Platform specific definitions
 */
#if defined(TRIO_PLATFORM_UNIX)
# include <unistd.h>
# include <signal.h>
# include <locale.h>
# if !defined(TRIO_FEATURE_LOCALE)
#  define USE_LOCALE
# endif
#endif /* TRIO_PLATFORM_UNIX */
#if defined(TRIO_PLATFORM_VMS)
# include <unistd.h>
#endif
#if defined(TRIO_PLATFORM_WIN32)
# if defined(TRIO_PLATFORM_WINCE)
int read(int handle, char *buffer, unsigned int length);
int write(int handle, const char *buffer, unsigned int length);
# else
#  include <io.h>
#  define read _read
#  define write _write
# endif
#endif /* TRIO_PLATFORM_WIN32 */

#if TRIO_FEATURE_WIDECHAR
# if defined(PREDEF_STANDARD_C94)
#  include <wchar.h>
#  include <wctype.h>
typedef wchar_t trio_wchar_t;
typedef wint_t trio_wint_t;
# else
typedef char trio_wchar_t;
typedef int trio_wint_t;
#  define WCONST(x) L ## x
#  define WEOF EOF
#  define iswalnum(x) isalnum(x)
#  define iswalpha(x) isalpha(x)
#  define iswcntrl(x) iscntrl(x)
#  define iswdigit(x) isdigit(x)
#  define iswgraph(x) isgraph(x)
#  define iswlower(x) islower(x)
#  define iswprint(x) isprint(x)
#  define iswpunct(x) ispunct(x)
#  define iswspace(x) isspace(x)
#  define iswupper(x) isupper(x)
#  define iswxdigit(x) isxdigit(x)
# endif
#endif


/*************************************************************************
 * Compiler dependent definitions
 */

/* Support for long long */
#ifndef __cplusplus
# if !defined(USE_LONGLONG)
#  if defined(TRIO_COMPILER_GCC) && !defined(__STRICT_ANSI__)
#   define USE_LONGLONG
#  else
#   if defined(TRIO_COMPILER_SUNPRO)
#    define USE_LONGLONG
#   else
#    if defined(TRIO_COMPILER_MSVC) && (_MSC_VER >= 1400)
#     define USE_LONGLONG
#    else
#     if defined(_LONG_LONG) || defined(_LONGLONG)
#      define USE_LONGLONG
#     endif
#    endif
#   endif
#  endif
# endif
#endif

/* The extra long numbers */
#if defined(USE_LONGLONG)
typedef signed long long int trio_longlong_t;
typedef unsigned long long int trio_ulonglong_t;
#else
# if defined(TRIO_COMPILER_SUPPORTS_VISUALC_INT)
typedef signed __int64 trio_longlong_t;
typedef unsigned __int64 trio_ulonglong_t;
# else
typedef TRIO_SIGNED long int trio_longlong_t;
typedef unsigned long int trio_ulonglong_t;
# endif
#endif

/* Maximal and fixed integer types */
#if defined(PREDEF_STANDARD_C99)
# include <stdint.h>
typedef intmax_t trio_intmax_t;
typedef uintmax_t trio_uintmax_t;
typedef int8_t trio_int8_t;
typedef int16_t trio_int16_t;
typedef int32_t trio_int32_t;
typedef int64_t trio_int64_t;
#else
# if defined(PREDEF_STANDARD_UNIX98)
#  include <inttypes.h>
typedef intmax_t trio_intmax_t;
typedef uintmax_t trio_uintmax_t;
typedef int8_t trio_int8_t;
typedef int16_t trio_int16_t;
typedef int32_t trio_int32_t;
typedef int64_t trio_int64_t;
# else
#  if defined(TRIO_COMPILER_SUPPORTS_VISUALC_INT)
typedef trio_longlong_t trio_intmax_t;
typedef trio_ulonglong_t trio_uintmax_t;
typedef __int8 trio_int8_t;
typedef __int16 trio_int16_t;
typedef __int32 trio_int32_t;
typedef __int64 trio_int64_t;
#  else
typedef trio_longlong_t trio_intmax_t;
typedef trio_ulonglong_t trio_uintmax_t;
#   if defined(TRIO_INT8_T)
typedef TRIO_INT8_T trio_int8_t;
#   else
typedef TRIO_SIGNED char trio_int8_t;
#   endif
#   if defined(TRIO_INT16_T)
typedef TRIO_INT16_T trio_int16_t;
#   else
typedef TRIO_SIGNED short trio_int16_t;
#   endif
#   if defined(TRIO_INT32_T)
typedef TRIO_INT32_T trio_int32_t;
#   else
typedef TRIO_SIGNED int trio_int32_t;
#   endif
#   if defined(TRIO_INT64_T)
typedef TRIO_INT64_T trio_int64_t;
#   else
typedef trio_longlong_t trio_int64_t;
#   endif
#  endif
# endif
#endif

#if defined(HAVE_FLOORL)
# define trio_floor(x) floorl((x))
#else
# define trio_floor(x) floor((double)(x))
#endif

#if defined(HAVE_CEILL)
# define trio_ceil(x) ceill((x))
#else
# define trio_ceil(x) ceil((double)(x))
#endif

#if defined(HAVE_FMODL)
# define trio_fmod(x,y) fmodl((x),(y))
#else
# define trio_fmod(x,y) fmod((double)(x),(double)(y))
#endif

#if defined(HAVE_POWL)
# define trio_pow(x,y) powl((x),(y))
#else
# define trio_pow(x,y) pow((double)(x),(double)(y))
#endif

#if defined(HAVE_LOG10L)
# define trio_log10(x) log10l((x))
#else
# define trio_log10(x) log10((double)(x))
#endif

#if TRIO_FEATURE_FLOAT
# define TRIO_FABS(x) (((x) < 0.0) ? -(x) : (x))
#endif

/*************************************************************************
 * Internal Definitions
 */

#if TRIO_FEATURE_FLOAT

# if !defined(DECIMAL_DIG)
#  define DECIMAL_DIG DBL_DIG
# endif

/* Long double sizes */
# ifdef LDBL_DIG
#  define MAX_MANTISSA_DIGITS LDBL_DIG
#  define MAX_EXPONENT_DIGITS 4
#  define MAX_DOUBLE_DIGITS LDBL_MAX_10_EXP
# else
#  define MAX_MANTISSA_DIGITS DECIMAL_DIG
#  define MAX_EXPONENT_DIGITS 3
#  define MAX_DOUBLE_DIGITS DBL_MAX_10_EXP
# endif

# if defined(TRIO_COMPILER_ANCIENT) || !defined(LDBL_DIG)
#  undef LDBL_DIG
#  undef LDBL_MANT_DIG
#  undef LDBL_EPSILON
#  define LDBL_DIG DBL_DIG
#  define LDBL_MANT_DIG DBL_MANT_DIG
#  define LDBL_EPSILON DBL_EPSILON
# endif

#endif /* TRIO_FEATURE_FLOAT */

/* The maximal number of digits is for base 2 */
#define MAX_CHARS_IN(x) (sizeof(x) * CHAR_BIT)
/* The width of a pointer. The number of bits in a hex digit is 4 */
#define POINTER_WIDTH ((sizeof("0x") - 1) + sizeof(trio_pointer_t) * CHAR_BIT / 4)

#if TRIO_FEATURE_FLOAT
/* Infinite and Not-A-Number for floating-point */
# define INFINITE_LOWER "inf"
# define INFINITE_UPPER "INF"
# define LONG_INFINITE_LOWER "infinite"
# define LONG_INFINITE_UPPER "INFINITE"
# define NAN_LOWER "nan"
# define NAN_UPPER "NAN"
#endif

/* Various constants */
enum {
  TYPE_PRINT = 1,
#if TRIO_FEATURE_SCANF
  TYPE_SCAN  = 2,
#endif

  /* Flags. FLAGS_LAST must be less than ULONG_MAX */
  FLAGS_NEW                 = 0,
  FLAGS_STICKY              = 1,
  FLAGS_SPACE               = 2 * FLAGS_STICKY,
  FLAGS_SHOWSIGN            = 2 * FLAGS_SPACE,
  FLAGS_LEFTADJUST          = 2 * FLAGS_SHOWSIGN,
  FLAGS_ALTERNATIVE         = 2 * FLAGS_LEFTADJUST,
  FLAGS_SHORT               = 2 * FLAGS_ALTERNATIVE,
  FLAGS_SHORTSHORT          = 2 * FLAGS_SHORT,
  FLAGS_LONG                = 2 * FLAGS_SHORTSHORT,
  FLAGS_QUAD                = 2 * FLAGS_LONG,
  FLAGS_LONGDOUBLE          = 2 * FLAGS_QUAD,
  FLAGS_SIZE_T              = 2 * FLAGS_LONGDOUBLE,
  FLAGS_PTRDIFF_T           = 2 * FLAGS_SIZE_T,
  FLAGS_INTMAX_T            = 2 * FLAGS_PTRDIFF_T,
  FLAGS_NILPADDING          = 2 * FLAGS_INTMAX_T,
  FLAGS_UNSIGNED            = 2 * FLAGS_NILPADDING,
  FLAGS_UPPER               = 2 * FLAGS_UNSIGNED,
  FLAGS_WIDTH               = 2 * FLAGS_UPPER,
  FLAGS_WIDTH_PARAMETER     = 2 * FLAGS_WIDTH,
  FLAGS_PRECISION           = 2 * FLAGS_WIDTH_PARAMETER,
  FLAGS_PRECISION_PARAMETER = 2 * FLAGS_PRECISION,
  FLAGS_BASE                = 2 * FLAGS_PRECISION_PARAMETER,
  FLAGS_BASE_PARAMETER      = 2 * FLAGS_BASE,
  FLAGS_FLOAT_E             = 2 * FLAGS_BASE_PARAMETER,
  FLAGS_FLOAT_G             = 2 * FLAGS_FLOAT_E,
  FLAGS_QUOTE               = 2 * FLAGS_FLOAT_G,
  FLAGS_WIDECHAR            = 2 * FLAGS_QUOTE,
  FLAGS_IGNORE              = 2 * FLAGS_WIDECHAR,
  FLAGS_IGNORE_PARAMETER    = 2 * FLAGS_IGNORE,
  FLAGS_VARSIZE_PARAMETER   = 2 * FLAGS_IGNORE_PARAMETER,
  FLAGS_FIXED_SIZE          = 2 * FLAGS_VARSIZE_PARAMETER,
  FLAGS_LAST                = FLAGS_FIXED_SIZE,
  /* Reused flags */
  FLAGS_EXCLUDE             = FLAGS_SHORT,
  FLAGS_USER_DEFINED        = FLAGS_IGNORE,
  FLAGS_USER_DEFINED_PARAMETER = FLAGS_IGNORE_PARAMETER,
  FLAGS_ROUNDING            = FLAGS_INTMAX_T,
  /* Compounded flags */
  FLAGS_ALL_VARSIZES        = FLAGS_LONG | FLAGS_QUAD | FLAGS_INTMAX_T | FLAGS_PTRDIFF_T | FLAGS_SIZE_T,
  FLAGS_ALL_SIZES           = FLAGS_ALL_VARSIZES | FLAGS_SHORTSHORT | FLAGS_SHORT,

  NO_POSITION  = -1,
  NO_WIDTH     =  0,
  NO_PRECISION = -1,
  NO_SIZE      = -1,

  /* Do not change these */
  NO_BASE      = -1,
  MIN_BASE     =  2,
  MAX_BASE     = 36,
  BASE_BINARY  =  2,
  BASE_OCTAL   =  8,
  BASE_DECIMAL = 10,
  BASE_HEX     = 16,

  /* Maximal number of allowed parameters */
  MAX_PARAMETERS = 64,
  /* Maximal number of characters in class */
  MAX_CHARACTER_CLASS = UCHAR_MAX + 1,

#if TRIO_FEATURE_USER_DEFINED
  /* Maximal string lengths for user-defined specifiers */
  MAX_USER_NAME = 64,
  MAX_USER_DATA = 256,
#endif
  
  /* Maximal length of locale separator strings */
  MAX_LOCALE_SEPARATOR_LENGTH = MB_LEN_MAX,
  /* Maximal number of integers in grouping */
  MAX_LOCALE_GROUPS = 64
};

#define NO_GROUPING ((int)CHAR_MAX)

/* Fundamental formatting parameter types */
#define FORMAT_SENTINEL  -1	/* marks end of parameters array */
#define FORMAT_UNKNOWN   0
#define FORMAT_INT       1
#define FORMAT_DOUBLE    2
#define FORMAT_CHAR      3
#define FORMAT_STRING    4
#define FORMAT_POINTER   5
#define FORMAT_COUNT     6
#define FORMAT_PARAMETER 7
#define FORMAT_GROUP     8
#define FORMAT_ERRNO     9
#define FORMAT_USER_DEFINED 10

/* Character constants */
#define CHAR_IDENTIFIER '%'
#define CHAR_ALT_IDENTIFIER '$'
#define CHAR_BACKSLASH '\\'
#define CHAR_QUOTE '\"'
#define CHAR_ADJUST ' '

#if TRIO_EXTENSION
/* Character class expressions */
# define CLASS_ALNUM "[:alnum:]"
# define CLASS_ALPHA "[:alpha:]"
# define CLASS_BLANK "[:blank:]"
# define CLASS_CNTRL "[:cntrl:]"
# define CLASS_DIGIT "[:digit:]"
# define CLASS_GRAPH "[:graph:]"
# define CLASS_LOWER "[:lower:]"
# define CLASS_PRINT "[:print:]"
# define CLASS_PUNCT "[:punct:]"
# define CLASS_SPACE "[:space:]"
# define CLASS_UPPER "[:upper:]"
# define CLASS_XDIGIT "[:xdigit:]"
#endif

/*
 * SPECIFIERS:
 *
 *
 * a  Hex-float
 * A  Hex-float
 * c  Character
 * C  Widechar character (wint_t)
 * d  Decimal
 * e  Float
 * E  Float
 * F  Float
 * F  Float
 * g  Float
 * G  Float
 * i  Integer
 * m  Error message
 * n  Count
 * o  Octal
 * p  Pointer
 * s  String
 * S  Widechar string (wchar_t *)
 * u  Unsigned
 * x  Hex
 * X  Hex
 * [] Group
 * <> User-defined
 *
 * Reserved:
 *
 * D  Binary Coded Decimal %D(length,precision) (OS/390)
 */
#define SPECIFIER_CHAR 'c'
#define SPECIFIER_STRING 's'
#define SPECIFIER_DECIMAL 'd'
#define SPECIFIER_INTEGER 'i'
#define SPECIFIER_UNSIGNED 'u'
#define SPECIFIER_OCTAL 'o'
#define SPECIFIER_HEX 'x'
#define SPECIFIER_HEX_UPPER 'X'
#if TRIO_FEATURE_FLOAT
# define SPECIFIER_FLOAT_E 'e'
# define SPECIFIER_FLOAT_E_UPPER 'E'
# define SPECIFIER_FLOAT_F 'f'
# define SPECIFIER_FLOAT_F_UPPER 'F'
# define SPECIFIER_FLOAT_G 'g'
# define SPECIFIER_FLOAT_G_UPPER 'G'
#endif
#define SPECIFIER_POINTER 'p'
#if TRIO_FEATURE_SCANF
# define SPECIFIER_GROUP '['
# define SPECIFIER_UNGROUP ']'
#endif
#define SPECIFIER_COUNT 'n'
#if TRIO_UNIX98
# define SPECIFIER_CHAR_UPPER 'C'
# define SPECIFIER_STRING_UPPER 'S'
#endif
#define SPECIFIER_HEXFLOAT 'a'
#define SPECIFIER_HEXFLOAT_UPPER 'A'
#define SPECIFIER_ERRNO 'm'
#if TRIO_FEATURE_BINARY
# define SPECIFIER_BINARY 'b'
# define SPECIFIER_BINARY_UPPER 'B'
#endif
#if TRIO_FEATURE_USER_DEFINED
# define SPECIFIER_USER_DEFINED_BEGIN '<'
# define SPECIFIER_USER_DEFINED_END '>'
# define SPECIFIER_USER_DEFINED_SEPARATOR ':'
# define SPECIFIER_USER_DEFINED_EXTRA '|'
#endif

/*
 * QUALIFIERS:
 *
 *
 * Numbers = d,i,o,u,x,X
 * Float = a,A,e,E,f,F,g,G
 * String = s
 * Char = c
 *
 *
 * 9$ Position
 *      Use the 9th parameter. 9 can be any number between 1 and
 *      the maximal argument
 *
 * 9 Width
 *      Set width to 9. 9 can be any number, but must not be postfixed
 *      by '$'
 *
 * h  Short
 *    Numbers:
 *      (unsigned) short int
 *
 * hh Short short
 *    Numbers:
 *      (unsigned) char
 *
 * l  Long
 *    Numbers:
 *      (unsigned) long int
 *    String:
 *      as the S specifier
 *    Char:
 *      as the C specifier
 *
 * ll Long Long
 *    Numbers:
 *      (unsigned) long long int
 *
 * L  Long Double
 *    Float
 *      long double
 *
 * #  Alternative
 *    Float:
 *      Decimal-point is always present
 *    String:
 *      non-printable characters are handled as \number
 *
 *    Spacing
 *
 * +  Sign
 *
 * -  Alignment
 *
 * .  Precision
 *
 * *  Parameter
 *    print: use parameter
 *    scan: no parameter (ignore)
 *
 * q  Quad
 *
 * Z  size_t
 *
 * w  Widechar
 *
 * '  Thousands/quote
 *    Numbers:
 *      Integer part grouped in thousands
 *    Binary numbers:
 *      Number grouped in nibbles (4 bits)
 *    String:
 *      Quoted string
 *
 * j  intmax_t
 * t  prtdiff_t
 * z  size_t
 *
 * !  Sticky
 * @  Parameter (for both print and scan)
 *
 * I  n-bit Integer
 *    Numbers:
 *      The following options exists
 *        I8  = 8-bit integer
 *        I16 = 16-bit integer
 *        I32 = 32-bit integer
 *        I64 = 64-bit integer
 */
#define QUALIFIER_POSITION '$'
#define QUALIFIER_SHORT 'h'
#define QUALIFIER_LONG 'l'
#define QUALIFIER_LONG_UPPER 'L'
#define QUALIFIER_ALTERNATIVE '#'
#define QUALIFIER_SPACE ' '
#define QUALIFIER_PLUS '+'
#define QUALIFIER_MINUS '-'
#define QUALIFIER_DOT '.'
#define QUALIFIER_STAR '*'
#define QUALIFIER_CIRCUMFLEX '^' /* For scanlists */
#define QUALIFIER_SIZE_T 'z'
#define QUALIFIER_PTRDIFF_T 't'
#define QUALIFIER_INTMAX_T 'j'
#define QUALIFIER_QUAD 'q'
#define QUALIFIER_SIZE_T_UPPER 'Z'
#if TRIO_MISC
# define QUALIFIER_WIDECHAR 'w'
#endif
#define QUALIFIER_FIXED_SIZE 'I'
#define QUALIFIER_QUOTE '\''
#define QUALIFIER_STICKY '!'
#define QUALIFIER_VARSIZE '&' /* This should remain undocumented */
#define QUALIFIER_ROUNDING_UPPER 'R'
#if TRIO_EXTENSION
# define QUALIFIER_PARAM '@' /* Experimental */
# define QUALIFIER_COLON ':' /* For scanlists */
# define QUALIFIER_EQUAL '=' /* For scanlists */
#endif


/*************************************************************************
 *
 * Internal Structures
 *
 *************************************************************************/

/* Parameters */
typedef struct {
  /* An indication of which entry in the data union is used */
  int type;
  /* The flags */
  trio_flags_t flags;
  /* The width qualifier */
  int width;
  /* The precision qualifier */
  int precision;
  /* The base qualifier */
  int base;
  /* Base from specifier */
  int baseSpecifier;
  /* The size for the variable size qualifier */
  int varsize;
  /* Offset of the first character of the specifier */
  int beginOffset;
  /* Offset of the first character after the specifier */
  int endOffset;
  /* Position in the argument list that this parameter refers to */
  int position;
  /* The data from the argument list */
  union {
    char *string;
#if TRIO_FEATURE_WIDECHAR
    trio_wchar_t *wstring;
#endif
    trio_pointer_t pointer;
    union {
      trio_intmax_t as_signed;
      trio_uintmax_t as_unsigned;
    } number;
#if TRIO_FEATURE_FLOAT
    double doubleNumber;
    double *doublePointer;
    trio_long_double_t longdoubleNumber;
    trio_long_double_t *longdoublePointer;
#endif
    int errorNumber;
  } data;
#if TRIO_FEATURE_USER_DEFINED
  /* For the user-defined specifier */
  union {
    char namespace[MAX_USER_NAME];
    int handler;        /* if flags & FLAGS_USER_DEFINED_PARAMETER */
  } user_defined;
  char user_data[MAX_USER_DATA];
#endif
} trio_parameter_t;

/* Container for customized functions */
typedef struct {
  union {
    trio_outstream_t out;
    trio_instream_t in;
  } stream;
  trio_pointer_t closure;
} trio_custom_t;

/* General trio "class" */
typedef struct _trio_class_t {
  /*
   * The function to write characters to a stream.
   */
  void (*OutStream) TRIO_PROTO((struct _trio_class_t *, int));
  /*
   * The function to read characters from a stream.
   */
  void (*InStream) TRIO_PROTO((struct _trio_class_t *, int *));
  /*
   * The function to undo read characters from a stream.
   */
  void (*UndoStream) TRIO_PROTO((struct _trio_class_t *));
  /*
   * The current location in the stream.
   */
  trio_pointer_t location;
  /*
   * The character currently being processed.
   */
  int current;
  /*
   * The number of characters that would have been written/read
   * if there had been sufficient space.
   */
  int processed;
  union {
    /*
     * The number of characters that are actually written. Processed and
     * committed will only differ for the *nprintf functions.
     */
    int committed;
    /*
     * The number of look-ahead characters read.
     */
    int cached;
  } actually;
  /*
   * The upper limit of characters that may be written/read.
   */
  int max;
  /*
   * The last output error that was detected.
   */
  int error;
} trio_class_t;

/* References (for user-defined callbacks) */
typedef struct _trio_reference_t {
  trio_class_t *data;
  trio_parameter_t *parameter;
} trio_reference_t;

#if TRIO_FEATURE_USER_DEFINED
/* Registered entries (for user-defined callbacks) */
typedef struct _trio_userdef_t {
  struct _trio_userdef_t *next;
  trio_callback_t callback;
  char *name;
} trio_userdef_t;
#endif

/*************************************************************************
 *
 * Internal Variables
 *
 *************************************************************************/

static TRIO_CONST char rcsid[] = "@(#)$Id: trio.c,v 1.129 2009/09/20 11:37:15 breese Exp $";

#if TRIO_FEATURE_FLOAT
/*
 * Need this to workaround a parser bug in HP C/iX compiler that fails
 * to resolves macro definitions that includes type 'long double',
 * e.g: va_arg(arg_ptr, long double)
 */
# if defined(TRIO_PLATFORM_MPEIX)
static TRIO_CONST trio_long_double_t ___dummy_long_double = 0;
# endif
#endif

static TRIO_CONST char internalNullString[] = "(nil)";

#if defined(USE_LOCALE)
static struct lconv *internalLocaleValues = NULL;
#endif

/*
 * UNIX98 says "in a locale where the radix character is not defined,
 * the radix character defaults to a period (.)"
 */
#if TRIO_FEATURE_FLOAT || TRIO_FEATURE_LOCALE || defined(USE_LOCALE)
static int internalDecimalPointLength = 1;
static char internalDecimalPoint = '.';
static char internalDecimalPointString[MAX_LOCALE_SEPARATOR_LENGTH + 1] = ".";
#endif
#if TRIO_FEATURE_QUOTE || TRIO_FEATURE_LOCALE || TRIO_EXTENSION
static int internalThousandSeparatorLength = 1;
static char internalThousandSeparator[MAX_LOCALE_SEPARATOR_LENGTH + 1] = ",";
static char internalGrouping[MAX_LOCALE_GROUPS] = { (char)NO_GROUPING };
#endif

static TRIO_CONST char internalDigitsLower[] = "0123456789abcdefghijklmnopqrstuvwxyz";
static TRIO_CONST char internalDigitsUpper[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#if TRIO_FEATURE_SCANF
static BOOLEAN_T internalDigitsUnconverted = TRUE;
static int internalDigitArray[128];
# if TRIO_EXTENSION
static BOOLEAN_T internalCollationUnconverted = TRUE;
static char internalCollationArray[MAX_CHARACTER_CLASS][MAX_CHARACTER_CLASS];
# endif
#endif

#if TRIO_FEATURE_USER_DEFINED
static TRIO_VOLATILE trio_callback_t internalEnterCriticalRegion = NULL;
static TRIO_VOLATILE trio_callback_t internalLeaveCriticalRegion = NULL;
static trio_userdef_t *internalUserDef = NULL;
#endif


/*************************************************************************
 *
 * Internal Functions
 *
 ************************************************************************/

#if defined(TRIO_EMBED_NAN)
# include "trionan.c"
#endif

#if defined(TRIO_EMBED_STRING)
# include "triostr.c"
#endif

/*************************************************************************
 * TrioInitializeParameter
 *
 * Description:
 *  Initialize a trio_parameter_t struct.
 */
TRIO_PRIVATE void
TrioInitializeParameter
TRIO_ARGS1((parameter),
	   trio_parameter_t *parameter)
{
  parameter->type = FORMAT_UNKNOWN;
  parameter->flags = 0;
  parameter->width = 0;
  parameter->precision = 0;
  parameter->base = 0;
  parameter->baseSpecifier = 0;
  parameter->varsize = 0;
  parameter->beginOffset = 0;
  parameter->endOffset = 0;
  parameter->position = 0;
  parameter->data.pointer = 0;
#if TRIO_FEATURE_USER_DEFINED
  parameter->user_defined.handler = 0;
  parameter->user_data[0] = 0;
#endif
}

/*************************************************************************
 * TrioCopyParameter
 *
 * Description:
 *  Copies one trio_parameter_t struct to another.
 */
TRIO_PRIVATE void
TrioCopyParameter
TRIO_ARGS2((target, source),
	   trio_parameter_t *target,
	   TRIO_CONST trio_parameter_t *source)
{
#if TRIO_FEATURE_USER_DEFINED
  size_t i;
#endif

  target->type = source->type;
  target->flags = source->flags;
  target->width = source->width;
  target->precision = source->precision;
  target->base = source->base;
  target->baseSpecifier = source->baseSpecifier;
  target->varsize = source->varsize;
  target->beginOffset = source->beginOffset;
  target->endOffset = source->endOffset;
  target->position = source->position;
  target->data = source->data;

#if TRIO_FEATURE_USER_DEFINED
  target->user_defined = source->user_defined;

  for (i = 0U; i < sizeof(target->user_data); ++i)
    {
      if ((target->user_data[i] = source->user_data[i]) == NIL)
	break;
    }
#endif
}

/*************************************************************************
 * TrioIsQualifier
 *
 * Description:
 *  Remember to add all new qualifiers to this function.
 *  QUALIFIER_POSITION must not be added.
 */
TRIO_PRIVATE BOOLEAN_T
TrioIsQualifier
TRIO_ARGS1((character),
	   TRIO_CONST char character)
{
  /* QUALIFIER_POSITION is not included */
  switch (character)
    {
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
    case QUALIFIER_PLUS:
    case QUALIFIER_MINUS:
    case QUALIFIER_SPACE:
    case QUALIFIER_DOT:
    case QUALIFIER_STAR:
    case QUALIFIER_ALTERNATIVE:
    case QUALIFIER_SHORT:
    case QUALIFIER_LONG:
    case QUALIFIER_CIRCUMFLEX:
    case QUALIFIER_LONG_UPPER:
    case QUALIFIER_SIZE_T:
    case QUALIFIER_PTRDIFF_T:
    case QUALIFIER_INTMAX_T:
    case QUALIFIER_QUAD:
    case QUALIFIER_SIZE_T_UPPER:
#if defined(QUALIFIER_WIDECHAR)
    case QUALIFIER_WIDECHAR:
#endif
    case QUALIFIER_QUOTE:
    case QUALIFIER_STICKY:
    case QUALIFIER_VARSIZE:
#if defined(QUALIFIER_PARAM)
    case QUALIFIER_PARAM:
#endif
    case QUALIFIER_FIXED_SIZE:
    case QUALIFIER_ROUNDING_UPPER:
      return TRUE;
    default:
      return FALSE;
    }
}

/*************************************************************************
 * TrioSetLocale
 */
#if defined(USE_LOCALE)
TRIO_PRIVATE void
TrioSetLocale(TRIO_NOARGS)
{
  internalLocaleValues = (struct lconv *)localeconv();
  if (internalLocaleValues)
    {
      if ((internalLocaleValues->decimal_point) &&
	  (internalLocaleValues->decimal_point[0] != NIL))
	{
	  internalDecimalPointLength = trio_length(internalLocaleValues->decimal_point);
	  if (internalDecimalPointLength == 1)
	    {
	      internalDecimalPoint = internalLocaleValues->decimal_point[0];
	    }
	  else
	    {
	      internalDecimalPoint = NIL;
	      trio_copy_max(internalDecimalPointString,
			    sizeof(internalDecimalPointString),
			    internalLocaleValues->decimal_point);
	    }
	}
# if TRIO_EXTENSION
      if ((internalLocaleValues->thousands_sep) &&
	  (internalLocaleValues->thousands_sep[0] != NIL))
	{
	  trio_copy_max(internalThousandSeparator,
			sizeof(internalThousandSeparator),
			internalLocaleValues->thousands_sep);
	  internalThousandSeparatorLength = trio_length(internalThousandSeparator);
	}
# endif
# if TRIO_EXTENSION
      if ((internalLocaleValues->grouping) &&
	  (internalLocaleValues->grouping[0] != NIL))
	{
	  trio_copy_max(internalGrouping,
			sizeof(internalGrouping),
			internalLocaleValues->grouping);
	}
# endif
    }
}
#endif /* defined(USE_LOCALE) */

#if TRIO_FEATURE_FLOAT && TRIO_FEATURE_QUOTE
TRIO_PRIVATE int
TrioCalcThousandSeparatorLength
TRIO_ARGS1((digits),
	   int digits)
{
  int count = 0;
  int step = NO_GROUPING;
  char *groupingPointer = internalGrouping;

  while (digits > 0)
    {
      if (*groupingPointer == CHAR_MAX)
	{
	  /* Disable grouping */
	  break; /* while */
	}
      else if (*groupingPointer == 0)
	{
	  /* Repeat last group */
	  if (step == NO_GROUPING)
	    {
	      /* Error in locale */
	      break; /* while */
	    }
	}
      else
	{
	  step = *groupingPointer++;
	}
      if (digits > step)
	count += internalThousandSeparatorLength;
      digits -= step;
    }
  return count;
}
#endif /* TRIO_FEATURE_FLOAT && TRIO_FEATURE_QUOTE */

#if TRIO_FEATURE_QUOTE
TRIO_PRIVATE BOOLEAN_T
TrioFollowedBySeparator
TRIO_ARGS1((position),
	   int position)
{
  int step = 0;
  char *groupingPointer = internalGrouping;

  position--;
  if (position == 0)
    return FALSE;
  while (position > 0)
    {
      if (*groupingPointer == CHAR_MAX)
	{
	  /* Disable grouping */
	  break; /* while */
	}
      else if (*groupingPointer != 0)
	{
	  step = *groupingPointer++;
	}
      if (step == 0)
	break;
      position -= step;
    }
  return (position == 0);
}
#endif /* TRIO_FEATURE_QUOTE */

/*************************************************************************
 * TrioGetPosition
 *
 * Get the %n$ position.
 */
TRIO_PRIVATE int
TrioGetPosition
TRIO_ARGS2((format, offsetPointer),
	   TRIO_CONST char *format,
	   int *offsetPointer)
{
#if TRIO_FEATURE_POSITIONAL
  char *tmpformat;
  int number = 0;
  int offset = *offsetPointer;

  number = (int)trio_to_long(&format[offset], &tmpformat, BASE_DECIMAL);
  offset = (int)(tmpformat - format);
  if ((number != 0) && (QUALIFIER_POSITION == format[offset++]))
    {
      *offsetPointer = offset;
      /*
       * number is decreased by 1, because n$ starts from 1, whereas
       * the array it is indexing starts from 0.
       */
      return number - 1;
    }
#endif
  return NO_POSITION;
}

/*************************************************************************
 * TrioFindNamespace
 *
 * Find registered user-defined specifier.
 * The prev argument is used for optimization only.
 */
#if TRIO_FEATURE_USER_DEFINED
TRIO_PRIVATE trio_userdef_t *
TrioFindNamespace
TRIO_ARGS2((name, prev),
	   TRIO_CONST char *name,
	   trio_userdef_t **prev)
{
  trio_userdef_t *def;
  
  if (internalEnterCriticalRegion)
    (void)internalEnterCriticalRegion(NULL);
  
  for (def = internalUserDef; def; def = def->next)
    {
      /* Case-sensitive string comparison */
      if (trio_equal_case(def->name, name))
	break;
      
      if (prev)
	*prev = def;
    }
  
  if (internalLeaveCriticalRegion)
    (void)internalLeaveCriticalRegion(NULL);
  
  return def;
}
#endif

/*************************************************************************
 * TrioPower
 *
 * Description:
 *  Calculate pow(base, exponent), where number and exponent are integers.
 */
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE trio_long_double_t
TrioPower
TRIO_ARGS2((number, exponent),
	   int number,
	   int exponent)
{
  trio_long_double_t result;

  if (number == 10)
    {
      switch (exponent)
	{
	  /* Speed up calculation of common cases */
	case 0:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E-1);
	  break;
	case 1:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+0);
	  break;
	case 2:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+1);
	  break;
	case 3:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+2);
	  break;
	case 4:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+3);
	  break;
	case 5:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+4);
	  break;
	case 6:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+5);
	  break;
	case 7:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+6);
	  break;
	case 8:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+7);
	  break;
	case 9:
	  result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+8);
	  break;
	default:
	  result = trio_pow((trio_long_double_t)number,
			    (trio_long_double_t)exponent);
	  break;
	}
    }
  else
    {
      return trio_pow((trio_long_double_t)number,
		      (trio_long_double_t)exponent);
    }
  return result;
}
#endif /* TRIO_FEATURE_FLOAT */

/*************************************************************************
 * TrioLogarithm
 */
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE trio_long_double_t
TrioLogarithm
TRIO_ARGS2((number, base),
	   trio_long_double_t number,
	   int base)
{
  trio_long_double_t result;

  if (number <= 0.0)
    {
      /* xlC crashes on log(0) */
      result = (number == 0.0) ? trio_ninf() : trio_nan();
    }
  else
    {
      if (base == 10)
	{
	  result = trio_log10(number);
	}
      else
	{
	  result = trio_log10(number) / trio_log10((double)base);
	}
    }
  return result;
}
#endif /* TRIO_FEATURE_FLOAT */

/*************************************************************************
 * TrioLogarithmBase
 */
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE double
TrioLogarithmBase
TRIO_ARGS1((base),
	   int base)
{
  switch (base)
    {
    case BASE_BINARY : return 1.0;
    case BASE_OCTAL  : return 3.0;
    case BASE_DECIMAL: return 3.321928094887362345;
    case BASE_HEX    : return 4.0;
    default          : return TrioLogarithm((double)base, 2);
    }
}
#endif /* TRIO_FEATURE_FLOAT */

/*************************************************************************
 * TrioParseQualifiers
 *
 * Description:
 *  Parse the qualifiers of a potential conversion specifier
 */
TRIO_PRIVATE int
TrioParseQualifiers
TRIO_ARGS4((type, format, offset, parameter),
	   int type,
	   TRIO_CONST char *format,
	   int offset,
	   trio_parameter_t *parameter)
{
  char ch;
  int dots = 0;  /* Count number of dots in modifier part */
  char *tmpformat;

  parameter->beginOffset = offset - 1;
  parameter->flags = FLAGS_NEW;
  parameter->position = TrioGetPosition(format, &offset);

  /* Default values */
  parameter->width = NO_WIDTH;
  parameter->precision = NO_PRECISION;
  parameter->base = NO_BASE;
  parameter->varsize = NO_SIZE;

  while (TrioIsQualifier(format[offset]))
    {
      ch = format[offset++];

      switch (ch)
        {
	case QUALIFIER_SPACE:
	  parameter->flags |= FLAGS_SPACE;
	  break;

	case QUALIFIER_PLUS:
	  parameter->flags |= FLAGS_SHOWSIGN;
	  break;

	case QUALIFIER_MINUS:
	  parameter->flags |= FLAGS_LEFTADJUST;
	  parameter->flags &= ~FLAGS_NILPADDING;
	  break;

	case QUALIFIER_ALTERNATIVE:
	  parameter->flags |= FLAGS_ALTERNATIVE;
	  break;

	case QUALIFIER_DOT:
	  if (dots == 0) /* Precision */
	    {
	      dots++;

	      /* Skip if no precision */
	      if (QUALIFIER_DOT == format[offset])
		break;

	      /* After the first dot we have the precision */
	      parameter->flags |= FLAGS_PRECISION;
	      if ((QUALIFIER_STAR == format[offset])
#if defined(QUALIFIER_PARAM)
		  || (QUALIFIER_PARAM == format[offset])
#endif
		  )
		{
		  offset++;
		  parameter->flags |= FLAGS_PRECISION_PARAMETER;
		  parameter->precision = TrioGetPosition(format, &offset);
		}
	      else
		{
		  parameter->precision = trio_to_long(&format[offset],
						      &tmpformat,
						      BASE_DECIMAL);
		  offset = (int)(tmpformat - format);
		}
	    }
	  else if (dots == 1) /* Base */
	    {
	      dots++;

	      /* After the second dot we have the base */
	      parameter->flags |= FLAGS_BASE;
	      if ((QUALIFIER_STAR == format[offset])
#if defined(QUALIFIER_PARAM)
		  || (QUALIFIER_PARAM == format[offset])
#endif
		  )
		{
		  offset++;
		  parameter->flags |= FLAGS_BASE_PARAMETER;
		  parameter->base = TrioGetPosition(format, &offset);
		}
	      else
		{
		  parameter->base = trio_to_long(&format[offset],
						 &tmpformat,
						 BASE_DECIMAL);
		  if (parameter->base > MAX_BASE)
		    return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
		  offset = (int)(tmpformat - format);
		}
	    }
	  else
	    {
	      return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
	    }
	  break; /* QUALIFIER_DOT */

#if defined(QUALIFIER_PARAM)
	case QUALIFIER_PARAM:
	  parameter->type = TYPE_PRINT;
	  /* FALLTHROUGH */
#endif
	case QUALIFIER_STAR:
	  /* This has different meanings for print and scan */
	  if (TYPE_PRINT == type)
	    {
	      /* Read with from parameter */
	      int width = TrioGetPosition(format, &offset);
	      parameter->flags |= (FLAGS_WIDTH | FLAGS_WIDTH_PARAMETER);
	      if (NO_POSITION != width)
                parameter->width = width;
	      /* else keep parameter->width = NO_WIDTH which != NO_POSITION */
	    }
#if TRIO_FEATURE_SCANF
	  else
	    {
	      /* Scan, but do not store result */
	      parameter->flags |= FLAGS_IGNORE;
	    }
#endif
	  break; /* QUALIFIER_STAR */

	case '0':
	  if (! (parameter->flags & FLAGS_LEFTADJUST))
	    parameter->flags |= FLAGS_NILPADDING;
	  /* FALLTHROUGH */
	case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
	  parameter->flags |= FLAGS_WIDTH;
	  /*
	   * &format[offset - 1] is used to "rewind" the read
	   * character from format
	   */
	  parameter->width = trio_to_long(&format[offset - 1],
					  &tmpformat,
					  BASE_DECIMAL);
	  offset = (int)(tmpformat - format);
	  break;

	case QUALIFIER_SHORT:
	  if (parameter->flags & FLAGS_SHORTSHORT)
	    return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
	  else if (parameter->flags & FLAGS_SHORT)
	    parameter->flags |= FLAGS_SHORTSHORT;
	  else
	    parameter->flags |= FLAGS_SHORT;
	  break;

	case QUALIFIER_LONG:
	  if (parameter->flags & FLAGS_QUAD)
	    return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
	  else if (parameter->flags & FLAGS_LONG)
	    parameter->flags |= FLAGS_QUAD;
	  else
	    parameter->flags |= FLAGS_LONG;
	  break;

#if TRIO_FEATURE_LONGDOUBLE
	case QUALIFIER_LONG_UPPER:
	  parameter->flags |= FLAGS_LONGDOUBLE;
	  break;
#endif

#if TRIO_FEATURE_SIZE_T
	case QUALIFIER_SIZE_T:
	  parameter->flags |= FLAGS_SIZE_T;
	  /* Modify flags for later truncation of number */
	  if (sizeof(size_t) == sizeof(trio_ulonglong_t))
	    parameter->flags |= FLAGS_QUAD;
	  else if (sizeof(size_t) == sizeof(long))
	    parameter->flags |= FLAGS_LONG;
	  break;
#endif

#if TRIO_FEATURE_PTRDIFF_T
	case QUALIFIER_PTRDIFF_T:
	  parameter->flags |= FLAGS_PTRDIFF_T;
	  if (sizeof(ptrdiff_t) == sizeof(trio_ulonglong_t))
	    parameter->flags |= FLAGS_QUAD;
	  else if (sizeof(ptrdiff_t) == sizeof(long))
	    parameter->flags |= FLAGS_LONG;
	  break;
#endif

#if TRIO_FEATURE_INTMAX_T
	case QUALIFIER_INTMAX_T:
	  parameter->flags |= FLAGS_INTMAX_T;
	  if (sizeof(trio_intmax_t) == sizeof(trio_ulonglong_t))
	    parameter->flags |= FLAGS_QUAD;
	  else if (sizeof(trio_intmax_t) == sizeof(long))
	    parameter->flags |= FLAGS_LONG;
	  break;
#endif

#if TRIO_FEATURE_QUAD
	case QUALIFIER_QUAD:
	  parameter->flags |= FLAGS_QUAD;
	  break;
#endif

#if TRIO_FEATURE_FIXED_SIZE
	case QUALIFIER_FIXED_SIZE:
	  if (parameter->flags & FLAGS_FIXED_SIZE)
	    return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);

	  if (parameter->flags & (FLAGS_ALL_SIZES |
				  FLAGS_LONGDOUBLE |
				  FLAGS_WIDECHAR |
				  FLAGS_VARSIZE_PARAMETER))
	    return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);

	  if ((format[offset] == '6') &&
	      (format[offset + 1] == '4'))
	    {
	      parameter->varsize = sizeof(trio_int64_t);
	      offset += 2;
	    }
	  else if ((format[offset] == '3') &&
		   (format[offset + 1] == '2'))
	    {
	      parameter->varsize = sizeof(trio_int32_t);
	      offset += 2;
	    }
	  else if ((format[offset] == '1') &&
		   (format[offset + 1] == '6'))
	    {
	      parameter->varsize = sizeof(trio_int16_t);
	      offset += 2;
	    }
	  else if (format[offset] == '8')
	    {
	      parameter->varsize = sizeof(trio_int8_t);
	      offset++;
	    }
	  else
	    return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);

	  parameter->flags |= FLAGS_FIXED_SIZE;
	  break;
#endif /* TRIO_FEATURE_FIXED_SIZE */

#if defined(QUALIFIER_WIDECHAR)
	case QUALIFIER_WIDECHAR:
	  parameter->flags |= FLAGS_WIDECHAR;
	  break;
#endif

#if TRIO_FEATURE_SIZE_T_UPPER
	case QUALIFIER_SIZE_T_UPPER:
	  break;
#endif

#if TRIO_FEATURE_QUOTE
	case QUALIFIER_QUOTE:
	  parameter->flags |= FLAGS_QUOTE;
	  break;
#endif

#if TRIO_FEATURE_STICKY
	case QUALIFIER_STICKY:
	  parameter->flags |= FLAGS_STICKY;
	  break;
#endif

#if TRIO_FEATURE_VARSIZE
	case QUALIFIER_VARSIZE:
	  parameter->flags |= FLAGS_VARSIZE_PARAMETER;
	  break;
#endif

#if TRIO_FEATURE_ROUNDING
	case QUALIFIER_ROUNDING_UPPER:
	  parameter->flags |= FLAGS_ROUNDING;
	  break;
#endif

	default:
	  /* Bail out completely to make the error more obvious */
	  return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
	}
    } /* while qualifier */

  parameter->endOffset = offset;

  return 0;
}

/*************************************************************************
 * TrioParseSpecifier
 *
 * Description:
 *  Parse the specifier part of a potential conversion specifier
 */
TRIO_PRIVATE int
TrioParseSpecifier
TRIO_ARGS4((type, format, offset, parameter),
	   int type,
	   TRIO_CONST char *format,
	   int offset,
	   trio_parameter_t *parameter)
{
  parameter->baseSpecifier = NO_BASE;

  switch (format[offset++])
    {
#if defined(SPECIFIER_CHAR_UPPER)
    case SPECIFIER_CHAR_UPPER:
      parameter->flags |= FLAGS_WIDECHAR;
      /* FALLTHROUGH */
#endif
    case SPECIFIER_CHAR:
      if (parameter->flags & FLAGS_LONG)
	parameter->flags |= FLAGS_WIDECHAR;
      else if (parameter->flags & FLAGS_SHORT)
	parameter->flags &= ~FLAGS_WIDECHAR;
      parameter->type = FORMAT_CHAR;
      break;

#if defined(SPECIFIER_STRING_UPPER)
    case SPECIFIER_STRING_UPPER:
      parameter->flags |= FLAGS_WIDECHAR;
      /* FALLTHROUGH */
#endif
    case SPECIFIER_STRING:
      if (parameter->flags & FLAGS_LONG)
	parameter->flags |= FLAGS_WIDECHAR;
      else if (parameter->flags & FLAGS_SHORT)
	parameter->flags &= ~FLAGS_WIDECHAR;
      parameter->type = FORMAT_STRING;
      break;

#if defined(SPECIFIER_GROUP)
    case SPECIFIER_GROUP:
      if (TYPE_SCAN == type)
	{
	  int depth = 1;
	  parameter->type = FORMAT_GROUP;
	  if (format[offset] == QUALIFIER_CIRCUMFLEX)
	    offset++;
	  if (format[offset] == SPECIFIER_UNGROUP)
	    offset++;
	  if (format[offset] == QUALIFIER_MINUS)
	    offset++;
	  /* Skip nested brackets */
	  while (format[offset] != NIL)
	    {
	      if (format[offset] == SPECIFIER_GROUP)
		{
		  depth++;
		}
	      else if (format[offset] == SPECIFIER_UNGROUP)
	      {
		if (--depth <= 0)
		  {
		    offset++;
		    break;
		  }
	      }
	      offset++;
	    }
	}
      break;
#endif /* defined(SPECIFIER_GROUP) */

    case SPECIFIER_INTEGER:
      parameter->type = FORMAT_INT;
      break;

    case SPECIFIER_UNSIGNED:
      parameter->flags |= FLAGS_UNSIGNED;
      parameter->type = FORMAT_INT;
      break;

    case SPECIFIER_DECIMAL:
      parameter->baseSpecifier = BASE_DECIMAL;
      parameter->type = FORMAT_INT;
      break;

    case SPECIFIER_OCTAL:
      parameter->flags |= FLAGS_UNSIGNED;
      parameter->baseSpecifier = BASE_OCTAL;
      parameter->type = FORMAT_INT;
      break;

#if TRIO_FEATURE_BINARY
    case SPECIFIER_BINARY_UPPER:
      parameter->flags |= FLAGS_UPPER;
      /* FALLTHROUGH */
    case SPECIFIER_BINARY:
      parameter->flags |= FLAGS_NILPADDING;
      parameter->baseSpecifier = BASE_BINARY;
      parameter->type = FORMAT_INT;
      break;
#endif

    case SPECIFIER_HEX_UPPER:
      parameter->flags |= FLAGS_UPPER;
      /* FALLTHROUGH */
    case SPECIFIER_HEX:
      parameter->flags |= FLAGS_UNSIGNED;
      parameter->baseSpecifier = BASE_HEX;
      parameter->type = FORMAT_INT;
      break;

#if defined(SPECIFIER_FLOAT_E)
# if defined(SPECIFIER_FLOAT_E_UPPER)
    case SPECIFIER_FLOAT_E_UPPER:
      parameter->flags |= FLAGS_UPPER;
      /* FALLTHROUGH */
# endif
    case SPECIFIER_FLOAT_E:
      parameter->flags |= FLAGS_FLOAT_E;
      parameter->type = FORMAT_DOUBLE;
      break;
#endif

#if defined(SPECIFIER_FLOAT_G)
# if defined(SPECIFIER_FLOAT_G_UPPER)
    case SPECIFIER_FLOAT_G_UPPER:
      parameter->flags |= FLAGS_UPPER;
      /* FALLTHROUGH */
# endif
    case SPECIFIER_FLOAT_G:
      parameter->flags |= FLAGS_FLOAT_G;
      parameter->type = FORMAT_DOUBLE;
      break;
#endif

#if defined(SPECIFIER_FLOAT_F)
# if defined(SPECIFIER_FLOAT_F_UPPER)
    case SPECIFIER_FLOAT_F_UPPER:
      parameter->flags |= FLAGS_UPPER;
      /* FALLTHROUGH */
# endif
    case SPECIFIER_FLOAT_F:
      parameter->type = FORMAT_DOUBLE;
      break;
#endif

#if defined(TRIO_COMPILER_VISUALC)
# pragma warning( push )
# pragma warning( disable : 4127 ) /* Conditional expression is constant */
#endif
    case SPECIFIER_POINTER:
      if (sizeof(trio_pointer_t) == sizeof(trio_ulonglong_t))
	parameter->flags |= FLAGS_QUAD;
      else if (sizeof(trio_pointer_t) == sizeof(long))
	parameter->flags |= FLAGS_LONG;
      parameter->type = FORMAT_POINTER;
      break;
#if defined(TRIO_COMPILER_VISUALC)
# pragma warning( pop )
#endif

    case SPECIFIER_COUNT:
      parameter->type = FORMAT_COUNT;
      break;

#if TRIO_FEATURE_HEXFLOAT
    case SPECIFIER_HEXFLOAT_UPPER:
      parameter->flags |= FLAGS_UPPER;
      /* FALLTHROUGH */
    case SPECIFIER_HEXFLOAT:
      parameter->baseSpecifier = BASE_HEX;
      parameter->type = FORMAT_DOUBLE;
      break;
#endif

#if TRIO_FEATURE_ERRNO
    case SPECIFIER_ERRNO:
      parameter->type = FORMAT_ERRNO;
      break;
#endif

#if TRIO_FEATURE_USER_DEFINED
    case SPECIFIER_USER_DEFINED_BEGIN:
      {
	unsigned int max;
	int without_namespace = TRUE;
	char* tmpformat = (char *)&format[offset];
	int ch;

	parameter->type = FORMAT_USER_DEFINED;
	parameter->user_defined.namespace[0] = NIL;

	while ((ch = format[offset]) != NIL)
	  {
	    offset++;
	    if ((ch == SPECIFIER_USER_DEFINED_END) || (ch == SPECIFIER_USER_DEFINED_EXTRA))
	      {
		if (without_namespace)
		  /* No namespace, handler will be passed as an argument */
		  parameter->flags |= FLAGS_USER_DEFINED_PARAMETER;

		/* Copy the user data */
		max = (unsigned int)(&format[offset] - tmpformat);
		if (max > MAX_USER_DATA)
		  max = MAX_USER_DATA;
		trio_copy_max(parameter->user_data, max, tmpformat);

		/* Skip extra data (which is only there to keep the compiler happy) */
		while ((ch != NIL) && (ch != SPECIFIER_USER_DEFINED_END))
		  ch = format[offset++];

		break; /* while */
	      }

	    if (ch == SPECIFIER_USER_DEFINED_SEPARATOR)
	      {
		without_namespace = FALSE;
		/* Copy the namespace for later looking-up */
		max = (int)(&format[offset] - tmpformat);
		if (max > MAX_USER_NAME)
		  max = MAX_USER_NAME;
		trio_copy_max(parameter->user_defined.namespace, max, tmpformat);
		tmpformat = (char *)&format[offset];
	      }
	  }

	if (ch != SPECIFIER_USER_DEFINED_END)
	  return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
      }
      break;
#endif /* TRIO_FEATURE_USER_DEFINED */

    default:
      /* Bail out completely to make the error more obvious */
      return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
  }

  parameter->endOffset = offset;

  return 0;
}

/*************************************************************************
 * TrioParse
 *
 * Description:
 *  Parse the format string
 */
TRIO_PRIVATE int
TrioParse
TRIO_ARGS5((type, format, parameters, arglist, argarray),
	   int type,
	   TRIO_CONST char *format,
	   trio_parameter_t *parameters,
	   va_list arglist,
	   trio_pointer_t *argarray)
{
  /* Count the number of times a parameter is referenced */
  unsigned short usedEntries[MAX_PARAMETERS];
  /* Parameter counters */
  int parameterPosition;
  int maxParam = -1;
  /* Utility variables */
  int offset;  /* Offset into formatting string */
  BOOLEAN_T positional;  /* Does the specifier have a positional? */
#if TRIO_FEATURE_STICKY
  BOOLEAN_T gotSticky = FALSE;  /* Are there any sticky modifiers at all? */
#endif
  /*
   * indices specifies the order in which the parameters must be
   * read from the va_args (this is necessary to handle positionals)
   */
  int indices[MAX_PARAMETERS];
  int pos = 0;
  /* Various variables */
#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
  int charlen;
#endif
  int save_errno;
  int i = -1;
  int num;
  trio_parameter_t workParameter;
  int status;

  /*
   * The 'parameters' array is not initialized, but we need to
   * know which entries we have used.
   */
  memset(usedEntries, 0, sizeof(usedEntries));

  save_errno = errno;
  offset = 0;
  parameterPosition = 0;
#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
  (void)mblen(NULL, 0);
#endif
  
  while (format[offset])
    {
      TrioInitializeParameter(&workParameter);

#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
      if (! isascii(format[offset]))
	{
	  /*
	   * Multibyte characters cannot be legal specifiers or
	   * modifiers, so we skip over them.
	   */
	  charlen = mblen(&format[offset], MB_LEN_MAX);
	  offset += (charlen > 0) ? charlen : 1;
	  continue; /* while */
	}
#endif /* TRIO_COMPILER_SUPPORTS_MULTIBYTE */

      switch(format[offset++]) {

      case CHAR_IDENTIFIER:
	{
	  if (CHAR_IDENTIFIER == format[offset])
	    {
	      /* skip double "%" */
	      offset++;
	      continue; /* while */
	    }

	  status = TrioParseQualifiers(type, format, offset, &workParameter);
	  if (status < 0)
	    return status; /* Return qualifier syntax error */

	  status = TrioParseSpecifier(type, format, workParameter.endOffset, &workParameter);
	  if (status < 0)
	    return status; /* Return specifier syntax error */
	}
	break;

#if TRIO_EXTENSION
      case CHAR_ALT_IDENTIFIER:
	{
	  status = TrioParseQualifiers(type, format, offset, &workParameter);
	  if (status < 0)
	    continue; /* False alert, not a user defined specifier */

	  status = TrioParseSpecifier(type, format, workParameter.endOffset, &workParameter);
	  if ((status < 0) || (FORMAT_USER_DEFINED != workParameter.type))
	    continue; /* False alert, not a user defined specifier */
	}
	break;
#endif

      default:
	continue; /* while */
      }

      /* now handle the parsed conversion specification */
      positional = (NO_POSITION != workParameter.position);

      /*
       * Parameters only need the type and value. The value is
       * read later.
       */
      if (workParameter.flags & FLAGS_WIDTH_PARAMETER)
        {
	  if (workParameter.width == NO_WIDTH)
	    {
	      workParameter.width = parameterPosition++;
	    }
	  else
	    {
	      if (! positional)
		  workParameter.position = workParameter.width + 1;
	    }

	  usedEntries[workParameter.width] += 1;
	  if (workParameter.width > maxParam)
	    maxParam = workParameter.width;
	  parameters[pos].type = FORMAT_PARAMETER;
	  parameters[pos].flags = 0;
	  indices[workParameter.width] = pos;
	  workParameter.width = pos++;
	}
      if (workParameter.flags & FLAGS_PRECISION_PARAMETER)
	{
	  if (workParameter.precision == NO_PRECISION)
	    {
	      workParameter.precision = parameterPosition++;
	    }
	  else
	    {
	      if (! positional)
		  workParameter.position = workParameter.precision + 1;
	    }

	  usedEntries[workParameter.precision] += 1;
	  if (workParameter.precision > maxParam)
	    maxParam = workParameter.precision;
	  parameters[pos].type = FORMAT_PARAMETER;
	  parameters[pos].flags = 0;
	  indices[workParameter.precision] = pos;
	  workParameter.precision = pos++;
	}
      if (workParameter.flags & FLAGS_BASE_PARAMETER)
	{
	  if (workParameter.base == NO_BASE)
	    {
	      workParameter.base = parameterPosition++;
	    }
	  else
	    {
	      if (! positional)
		  workParameter.position = workParameter.base + 1;
	    }

	  usedEntries[workParameter.base] += 1;
	  if (workParameter.base > maxParam)
	    maxParam = workParameter.base;
	  parameters[pos].type = FORMAT_PARAMETER;
	  parameters[pos].flags = 0;
	  indices[workParameter.base] = pos;
	  workParameter.base = pos++;
	}
#if TRIO_FEATURE_VARSIZE
      if (workParameter.flags & FLAGS_VARSIZE_PARAMETER)
	{
	  workParameter.varsize = parameterPosition++;

	  usedEntries[workParameter.varsize] += 1;
	  if (workParameter.varsize > maxParam)
	    maxParam = workParameter.varsize;
	  parameters[pos].type = FORMAT_PARAMETER;
	  parameters[pos].flags = 0;
	  indices[workParameter.varsize] = pos;
	  workParameter.varsize = pos++;
	}
#endif
#if TRIO_FEATURE_USER_DEFINED
      if (workParameter.flags & FLAGS_USER_DEFINED_PARAMETER)
	{
	  workParameter.user_defined.handler = parameterPosition++;

	  usedEntries[workParameter.user_defined.handler] += 1;
	  if (workParameter.user_defined.handler > maxParam)
	    maxParam = workParameter.user_defined.handler;
	  parameters[pos].type = FORMAT_PARAMETER;
	  parameters[pos].flags = FLAGS_USER_DEFINED;
	  indices[workParameter.user_defined.handler] = pos;
	  workParameter.user_defined.handler = pos++;
	}
#endif

      if (NO_POSITION == workParameter.position)
	{
	  workParameter.position = parameterPosition++;
	}

      if (workParameter.position > maxParam)
	maxParam = workParameter.position;

      if (workParameter.position >= MAX_PARAMETERS)
	{
	  /* Bail out completely to make the error more obvious */
	  return TRIO_ERROR_RETURN(TRIO_ETOOMANY, offset);
	}

      indices[workParameter.position] = pos;

      /*  Count the number of times this entry has been used */
      usedEntries[workParameter.position] += 1;

      /* Find last sticky parameters */
#if TRIO_FEATURE_STICKY
      if (workParameter.flags & FLAGS_STICKY)
	{
	  gotSticky = TRUE;
	}
      else if (gotSticky)
	{
	  for (i = pos - 1; i >= 0; i--)
	    {
	      if (parameters[i].type == FORMAT_PARAMETER)
		continue;
	      if ((parameters[i].flags & FLAGS_STICKY) &&
		  (parameters[i].type == workParameter.type))
		{
		  /* Do not overwrite current qualifiers */
		  workParameter.flags |= (parameters[i].flags & (unsigned long)~FLAGS_STICKY);
		  if (workParameter.width == NO_WIDTH)
		    workParameter.width = parameters[i].width;
		  if (workParameter.precision == NO_PRECISION)
		    workParameter.precision = parameters[i].precision;
		  if (workParameter.base == NO_BASE)
		    workParameter.base = parameters[i].base;
		  break;
		}
	    }
	}
#endif

      if (workParameter.base == NO_BASE)
	workParameter.base = BASE_DECIMAL;

      offset = workParameter.endOffset;

      TrioCopyParameter(&parameters[pos++], &workParameter);
    } /* while format characters left */

  parameters[pos].type = FORMAT_SENTINEL;  /* end parameter array with sentinel */
  parameters[pos].beginOffset = offset;

  for (num = 0; num <= maxParam; num++)
    {
      if (usedEntries[num] != 1)
	{
	  if (usedEntries[num] == 0) /* gap detected */
	    return TRIO_ERROR_RETURN(TRIO_EGAP, num);
	  else /* double references detected */
	    return TRIO_ERROR_RETURN(TRIO_EDBLREF, num);
	}
      
      i = indices[num];

      /*
       * FORMAT_PARAMETERS are only present if they must be read,
       * so it makes no sense to check the ignore flag (besides,
       * the flags variable is not set for that particular type)
       */
      if ((parameters[i].type != FORMAT_PARAMETER) &&
	  (parameters[i].flags & FLAGS_IGNORE))
	continue; /* for all arguments */

      /*
       * The stack arguments are read according to ANSI C89
       * default argument promotions:
       *
       *  char           = int
       *  short          = int
       *  unsigned char  = unsigned int
       *  unsigned short = unsigned int
       *  float          = double
       *
       * In addition to the ANSI C89 these types are read (the
       * default argument promotions of C99 has not been
       * considered yet)
       *
       *  long long
       *  long double
       *  size_t
       *  ptrdiff_t
       *  intmax_t
       */
      switch (parameters[i].type)
	{
	case FORMAT_GROUP:
	case FORMAT_STRING:
#if TRIO_FEATURE_WIDECHAR
	  if (parameters[i].flags & FLAGS_WIDECHAR)
	    {
	      parameters[i].data.wstring = (argarray == NULL)
		? va_arg(arglist, trio_wchar_t *)
		: (trio_wchar_t *)(argarray[num]);
	    }
	  else
#endif
	    {
	      parameters[i].data.string = (argarray == NULL)
		? va_arg(arglist, char *)
		: (char *)(argarray[num]);
	    }
	  break;

#if TRIO_FEATURE_USER_DEFINED
	case FORMAT_USER_DEFINED:
#endif
	case FORMAT_POINTER:
	case FORMAT_COUNT:
	case FORMAT_UNKNOWN:
	  parameters[i].data.pointer = (argarray == NULL)
	    ? va_arg(arglist, trio_pointer_t )
	    : argarray[num];
	  break;

	case FORMAT_CHAR:
	case FORMAT_INT:
#if TRIO_FEATURE_SCANF
	  if (TYPE_SCAN == type)
	    {
              if (argarray == NULL)
                parameters[i].data.pointer = 
                  (trio_pointer_t)va_arg(arglist, trio_pointer_t);
              else
                {
                  if (parameters[i].type == FORMAT_CHAR)
                    parameters[i].data.pointer =
                      (trio_pointer_t)((char *)argarray[num]);
                  else if (parameters[i].flags & FLAGS_SHORT)
                    parameters[i].data.pointer =
                      (trio_pointer_t)((short *)argarray[num]);
                  else
                    parameters[i].data.pointer =
                      (trio_pointer_t)((int *)argarray[num]);
                }
	    }
	  else
#endif /* TRIO_FEATURE_SCANF */
	    {
#if TRIO_FEATURE_VARSIZE || TRIO_FEATURE_FIXED_SIZE
	      if (parameters[i].flags
		  & (FLAGS_VARSIZE_PARAMETER | FLAGS_FIXED_SIZE))
		{
		  int varsize;
		  if (parameters[i].flags & FLAGS_VARSIZE_PARAMETER)
		    {
		      /*
		       * Variable sizes are mapped onto the fixed sizes, in
		       * accordance with integer promotion.
		       *
		       * Please note that this may not be portable, as we
		       * only guess the size, not the layout of the numbers.
		       * For example, if int is little-endian, and long is
		       * big-endian, then this will fail.
		       */
		      varsize = (int)parameters[parameters[i].varsize].data.number.as_unsigned;
		    }
		  else
		    {
		      /* Used for the I<bits> modifiers */
		      varsize = parameters[i].varsize;
		    }
		  parameters[i].flags &= ~FLAGS_ALL_VARSIZES;
		  
		  if (varsize <= (int)sizeof(int))
		    ;
		  else if (varsize <= (int)sizeof(long))
		    parameters[i].flags |= FLAGS_LONG;
#if TRIO_FEATURE_INTMAX_T
		  else if (varsize <= (int)sizeof(trio_longlong_t))
		    parameters[i].flags |= FLAGS_QUAD;
		  else
		    parameters[i].flags |= FLAGS_INTMAX_T;
#else
		  else
		    parameters[i].flags |= FLAGS_QUAD;
#endif
		}
#endif /* TRIO_FEATURE_VARSIZE */
#if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER
	      if (parameters[i].flags & FLAGS_SIZE_T)
		parameters[i].data.number.as_unsigned = (argarray == NULL)
		  ? (trio_uintmax_t)va_arg(arglist, size_t)
		  : (trio_uintmax_t)(*((size_t *)argarray[num]));
	      else
#endif
#if TRIO_FEATURE_PTRDIFF_T
	      if (parameters[i].flags & FLAGS_PTRDIFF_T)
		parameters[i].data.number.as_unsigned = (argarray == NULL)
		  ? (trio_uintmax_t)va_arg(arglist, ptrdiff_t)
		  : (trio_uintmax_t)(*((ptrdiff_t *)argarray[num]));
	      else
#endif
#if TRIO_FEATURE_INTMAX_T
	      if (parameters[i].flags & FLAGS_INTMAX_T)
		parameters[i].data.number.as_unsigned = (argarray == NULL)
		  ? (trio_uintmax_t)va_arg(arglist, trio_intmax_t)
		  : (trio_uintmax_t)(*((trio_intmax_t *)argarray[num]));
	      else
#endif
	      if (parameters[i].flags & FLAGS_QUAD)
		parameters[i].data.number.as_unsigned = (argarray == NULL)
		  ? (trio_uintmax_t)va_arg(arglist, trio_ulonglong_t)
		  : (trio_uintmax_t)(*((trio_ulonglong_t *)argarray[num]));
	      else if (parameters[i].flags & FLAGS_LONG)
		parameters[i].data.number.as_unsigned = (argarray == NULL)
		  ? (trio_uintmax_t)va_arg(arglist, long)
		  : (trio_uintmax_t)(*((long *)argarray[num]));
	      else
		{
		  if (argarray == NULL)
		    parameters[i].data.number.as_unsigned = (trio_uintmax_t)va_arg(arglist, int);
		  else
		    {
		      if (parameters[i].type == FORMAT_CHAR)
			parameters[i].data.number.as_unsigned = (trio_uintmax_t)(*((char *)argarray[num]));
		      else if (parameters[i].flags & FLAGS_SHORT)
			parameters[i].data.number.as_unsigned = (trio_uintmax_t)(*((short *)argarray[num]));
		      else
			parameters[i].data.number.as_unsigned = (trio_uintmax_t)(*((int *)argarray[num]));
		    }
		}
	    }
	  break;

	case FORMAT_PARAMETER:
	  /*
	   * The parameter for the user-defined specifier is a pointer,
	   * whereas the rest (width, precision, base) uses an integer.
	   */
	  if (parameters[i].flags & FLAGS_USER_DEFINED)
	    parameters[i].data.pointer = (argarray == NULL)
	      ? va_arg(arglist, trio_pointer_t )
	      : argarray[num];
	  else
	    parameters[i].data.number.as_unsigned = (argarray == NULL)
	      ? (trio_uintmax_t)va_arg(arglist, int)
	      : (trio_uintmax_t)(*((int *)argarray[num]));
	  break;

#if TRIO_FEATURE_FLOAT
	case FORMAT_DOUBLE:
# if TRIO_FEATURE_SCANF
	  if (TYPE_SCAN == type)
	    {
	      if (parameters[i].flags & FLAGS_LONGDOUBLE)
		parameters[i].data.longdoublePointer = (argarray == NULL)
		  ? va_arg(arglist, trio_long_double_t *)
		  : (trio_long_double_t *)argarray[num];
	      else
                {
		  if (parameters[i].flags & FLAGS_LONG)
		    parameters[i].data.doublePointer = (argarray == NULL)
		      ? va_arg(arglist, double *)
		      : (double *)argarray[num];
		  else
		    parameters[i].data.doublePointer = (argarray == NULL)
		      ? (double *)va_arg(arglist, float *)
		      : (double *)((float *)argarray[num]);
                }
	    }
	  else
# endif /* TRIO_FEATURE_SCANF */
	    {
	      if (parameters[i].flags & FLAGS_LONGDOUBLE)
		parameters[i].data.longdoubleNumber = (argarray == NULL)
		  ? va_arg(arglist, trio_long_double_t)
		  : (trio_long_double_t)(*((trio_long_double_t *)argarray[num]));
	      else
		{
		  if (argarray == NULL)
		    parameters[i].data.longdoubleNumber =
		      (trio_long_double_t)va_arg(arglist, double);
		  else
		    {
		      if (parameters[i].flags & FLAGS_SHORT)
			parameters[i].data.longdoubleNumber =
			  (trio_long_double_t)(*((float *)argarray[num]));
		      else
			parameters[i].data.longdoubleNumber =
			  (trio_long_double_t)(*((double *)argarray[num]));
		    }
		}
	    }
	  break;
#endif /* TRIO_FEATURE_FLOAT */

#if TRIO_FEATURE_ERRNO
	case FORMAT_ERRNO:
	  parameters[i].data.errorNumber = save_errno;
	  break;
#endif

	default:
	  break;
	}
    } /* for all specifiers */
  return num;
}


/*************************************************************************
 *
 * FORMATTING
 *
 ************************************************************************/


/*************************************************************************
 * TrioWriteNumber
 *
 * Description:
 *  Output a number.
 *  The complexity of this function is a result of the complexity
 *  of the dependencies of the flags.
 */
TRIO_PRIVATE void
TrioWriteNumber
TRIO_ARGS6((self, number, flags, width, precision, base),
	   trio_class_t *self,
	   trio_uintmax_t number,
	   trio_flags_t flags,
	   int width,
	   int precision,
	   int base)
{
  BOOLEAN_T isNegative;
  BOOLEAN_T isNumberZero;
  BOOLEAN_T isPrecisionZero;
  BOOLEAN_T ignoreNumber;
  char buffer[MAX_CHARS_IN(trio_uintmax_t) * (1 + MAX_LOCALE_SEPARATOR_LENGTH) + 1];
  char *bufferend;
  char *pointer;
  TRIO_CONST char *digits;
  int i;
#if TRIO_FEATURE_QUOTE
  int length;
  char *p;
#endif
  int count;
  int digitOffset;

  assert(VALID(self));
  assert(VALID(self->OutStream));
  assert(((base >= MIN_BASE) && (base <= MAX_BASE)) || (base == NO_BASE));

  digits = (flags & FLAGS_UPPER) ? internalDigitsUpper : internalDigitsLower;
  if (base == NO_BASE)
    base = BASE_DECIMAL;

  isNumberZero = (number == 0);
  isPrecisionZero = (precision == 0);
  ignoreNumber = (isNumberZero
		  && isPrecisionZero
		  && !((flags & FLAGS_ALTERNATIVE) && (base == BASE_OCTAL)));

  if (flags & FLAGS_UNSIGNED)
    {
      isNegative = FALSE;
      flags &= ~FLAGS_SHOWSIGN;
    }
  else
    {
      isNegative = ((trio_intmax_t)number < 0);
      if (isNegative)
	number = -((trio_intmax_t)number);
    }

  if (flags & FLAGS_QUAD)
    number &= (trio_ulonglong_t)-1;
  else if (flags & FLAGS_LONG)
    number &= (unsigned long)-1;
  else
    number &= (unsigned int)-1;
  
  /* Build number */
  pointer = bufferend = &buffer[sizeof(buffer) - 1];
  *pointer-- = NIL;
  for (i = 1; i < (int)sizeof(buffer); i++)
    {
      digitOffset = number % base;
      *pointer-- = digits[digitOffset];
      number /= base;
      if (number == 0)
	break;

#if TRIO_FEATURE_QUOTE
      if ((flags & FLAGS_QUOTE) && TrioFollowedBySeparator(i + 1))
	{
	  /*
	   * We are building the number from the least significant
	   * to the most significant digit, so we have to copy the
	   * thousand separator backwards
	   */
	  length = internalThousandSeparatorLength;
	  if (((int)(pointer - buffer) - length) > 0)
	    {
	      p = &internalThousandSeparator[length - 1];
	      while (length-- > 0)
		*pointer-- = *p--;
	    }
	}
#endif
    }

  if (! ignoreNumber)
    {
      /* Adjust width */
      width -= (bufferend - pointer) - 1;
    }

  /* Adjust precision */
  if (NO_PRECISION != precision)
    {
      precision -= (bufferend - pointer) - 1;
      if (precision < 0)
	precision = 0;
      flags |= FLAGS_NILPADDING;
    }

  /* Calculate padding */
  count = (! ((flags & FLAGS_LEFTADJUST) || (precision == NO_PRECISION)))
    ? precision
    : 0;
  
  /* Adjust width further */
  if (isNegative || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE))
    width--;
  if ((flags & FLAGS_ALTERNATIVE) && !isNumberZero)
    {
      switch (base)
	{
	case BASE_BINARY:
	case BASE_HEX:
	  width -= 2;
	  break;
	case BASE_OCTAL:
	  if (!(flags & FLAGS_NILPADDING) || (count == 0))
	    width--;
	  break;
	default:
	  break;
	}
    }

  /* Output prefixes spaces if needed */
  if (! ((flags & FLAGS_LEFTADJUST) ||
	 ((flags & FLAGS_NILPADDING) && (precision == NO_PRECISION))))
    {
      while (width-- > count)
	self->OutStream(self, CHAR_ADJUST);
    }

  /* width has been adjusted for signs and alternatives */
  if (isNegative)
    self->OutStream(self, '-');
  else if (flags & FLAGS_SHOWSIGN)
    self->OutStream(self, '+');
  else if (flags & FLAGS_SPACE)
    self->OutStream(self, ' ');

  /* Prefix is not written when the value is zero */
  if ((flags & FLAGS_ALTERNATIVE) && !isNumberZero)
    {
      switch (base)
	{
	case BASE_BINARY:
	  self->OutStream(self, '0');
	  self->OutStream(self, (flags & FLAGS_UPPER) ? 'B' : 'b');
	  break;

	case BASE_OCTAL:
	  if (!(flags & FLAGS_NILPADDING) || (count == 0))
	    self->OutStream(self, '0');
	  break;

	case BASE_HEX:
	  self->OutStream(self, '0');
	  self->OutStream(self, (flags & FLAGS_UPPER) ? 'X' : 'x');
	  break;

	default:
	  break;
	} /* switch base */
    }

  /* Output prefixed zero padding if needed */
  if (flags & FLAGS_NILPADDING)
    {
      if (precision == NO_PRECISION)
	precision = width;
      while (precision-- > 0)
	{
	  self->OutStream(self, '0');
	  width--;
	}
    }

  if (! ignoreNumber)
    {
      /* Output the number itself */
      while (*(++pointer))
	{
	  self->OutStream(self, *pointer);
	}
    }

  /* Output trailing spaces if needed */
  if (flags & FLAGS_LEFTADJUST)
    {
      while (width-- > 0)
	self->OutStream(self, CHAR_ADJUST);
    }
}

/*************************************************************************
 * TrioWriteStringCharacter
 *
 * Description:
 *  Output a single character of a string
 */
TRIO_PRIVATE void
TrioWriteStringCharacter
TRIO_ARGS3((self, ch, flags),
	   trio_class_t *self,
	   int ch,
	   trio_flags_t flags)
{
  if (flags & FLAGS_ALTERNATIVE)
    {
      if (! isprint(ch))
	{
	  /*
	   * Non-printable characters are converted to C escapes or
	   * \number, if no C escape exists.
	   */
	  self->OutStream(self, CHAR_BACKSLASH);
	  switch (ch)
	    {
	    case '\007': self->OutStream(self, 'a'); break;
	    case '\b': self->OutStream(self, 'b'); break;
	    case '\f': self->OutStream(self, 'f'); break;
	    case '\n': self->OutStream(self, 'n'); break;
	    case '\r': self->OutStream(self, 'r'); break;
	    case '\t': self->OutStream(self, 't'); break;
	    case '\v': self->OutStream(self, 'v'); break;
	    case '\\': self->OutStream(self, '\\'); break;
	    default:
	      self->OutStream(self, 'x');
	      TrioWriteNumber(self, (trio_uintmax_t)ch,
			      FLAGS_UNSIGNED | FLAGS_NILPADDING,
			      2, 2, BASE_HEX);
	      break;
	    }
	}
      else if (ch == CHAR_BACKSLASH)
	{
	  self->OutStream(self, CHAR_BACKSLASH);
	  self->OutStream(self, CHAR_BACKSLASH);
	}
      else
	{
	  self->OutStream(self, ch);
	}
    }
  else
    {
      self->OutStream(self, ch);
    }
}

/*************************************************************************
 * TrioWriteString
 *
 * Description:
 *  Output a string
 */
TRIO_PRIVATE void
TrioWriteString
TRIO_ARGS5((self, string, flags, width, precision),
	   trio_class_t *self,
	   TRIO_CONST char *string,
	   trio_flags_t flags,
	   int width,
	   int precision)
{
  int length;
  int ch;

  assert(VALID(self));
  assert(VALID(self->OutStream));

  if (string == NULL)
    {
      string = internalNullString;
      length = sizeof(internalNullString) - 1;
#if TRIO_FEATURE_QUOTE
      /* Disable quoting for the null pointer */
      flags &= (~FLAGS_QUOTE);
#endif
      width = 0;
    }
  else
    {
      if (precision == 0)
	{
	  length = trio_length(string);
	}
      else
	{
	  length = trio_length_max(string, precision);
	}
    }
  if ((NO_PRECISION != precision) &&
      (precision < length))
    {
      length = precision;
    }
  width -= length;

#if TRIO_FEATURE_QUOTE
  if (flags & FLAGS_QUOTE)
    self->OutStream(self, CHAR_QUOTE);
#endif

  if (! (flags & FLAGS_LEFTADJUST))
    {
      while (width-- > 0)
	self->OutStream(self, CHAR_ADJUST);
    }

  while (length-- > 0)
    {
      /* The ctype parameters must be an unsigned char (or EOF) */
      ch = (int)((unsigned char)(*string++));
      TrioWriteStringCharacter(self, ch, flags);
    }

  if (flags & FLAGS_LEFTADJUST)
    {
      while (width-- > 0)
	self->OutStream(self, CHAR_ADJUST);
    }
#if TRIO_FEATURE_QUOTE
  if (flags & FLAGS_QUOTE)
    self->OutStream(self, CHAR_QUOTE);
#endif
}

/*************************************************************************
 * TrioWriteWideStringCharacter
 *
 * Description:
 *  Output a wide string as a multi-byte sequence
 */
#if TRIO_FEATURE_WIDECHAR
TRIO_PRIVATE int
TrioWriteWideStringCharacter
TRIO_ARGS4((self, wch, flags, width),
	   trio_class_t *self,
	   trio_wchar_t wch,
	   trio_flags_t flags,
	   int width)
{
  int size;
  int i;
  int ch;
  char *string;
  char buffer[MB_LEN_MAX + 1];

  if (width == NO_WIDTH)
    width = sizeof(buffer);
  
  size = wctomb(buffer, wch);
  if ((size <= 0) || (size > width) || (buffer[0] == NIL))
    return 0;

  string = buffer;
  i = size;
  while ((width >= i) && (width-- > 0) && (i-- > 0))
    {
      /* The ctype parameters must be an unsigned char (or EOF) */
      ch = (int)((unsigned char)(*string++));
      TrioWriteStringCharacter(self, ch, flags);
    }
  return size;
}
#endif /* TRIO_FEATURE_WIDECHAR */

/*************************************************************************
 * TrioWriteWideString
 *
 * Description:
 *  Output a wide character string as a multi-byte string
 */
#if TRIO_FEATURE_WIDECHAR
TRIO_PRIVATE void
TrioWriteWideString
TRIO_ARGS5((self, wstring, flags, width, precision),
	   trio_class_t *self,
	   TRIO_CONST trio_wchar_t *wstring,
	   trio_flags_t flags,
	   int width,
	   int precision)
{
  int length;
  int size;

  assert(VALID(self));
  assert(VALID(self->OutStream));

#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
  /* Required by TrioWriteWideStringCharacter */
  (void)mblen(NULL, 0);
#endif
  
  if (wstring == NULL)
    {
      TrioWriteString(self, NULL, flags, width, precision);
      return;
    }
  
  if (NO_PRECISION == precision)
    {
      length = INT_MAX;
    }
  else
    {
      length = precision;
      width -= length;
    }

#if TRIO_FEATURE_QUOTE
  if (flags & FLAGS_QUOTE)
    self->OutStream(self, CHAR_QUOTE);
#endif

  if (! (flags & FLAGS_LEFTADJUST))
    {
      while (width-- > 0)
	self->OutStream(self, CHAR_ADJUST);
    }

  while (length > 0)
    {
      size = TrioWriteWideStringCharacter(self, *wstring++, flags, length);
      if (size == 0)
	break; /* while */
      length -= size;
    }

  if (flags & FLAGS_LEFTADJUST)
    {
      while (width-- > 0)
	self->OutStream(self, CHAR_ADJUST);
    }
#if TRIO_FEATURE_QUOTE
  if (flags & FLAGS_QUOTE)
    self->OutStream(self, CHAR_QUOTE);
#endif
}
#endif /* TRIO_FEATURE_WIDECHAR */

/*************************************************************************
 * TrioWriteDouble
 *
 * http://wwwold.dkuug.dk/JTC1/SC22/WG14/www/docs/dr_211.htm
 *
 * "5.2.4.2.2 paragraph #4
 *
 *  The accuracy [...] is implementation defined, as is the accuracy
 *  of the conversion between floating-point internal representations
 *  and string representations performed by the libray routine in
 *  <stdio.h>"
 */
/* FIXME: handle all instances of constant long-double number (L)
 *   and *l() math functions.
 */
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE void
TrioWriteDouble
TRIO_ARGS6((self, number, flags, width, precision, base),
	   trio_class_t *self,
	   trio_long_double_t number,
	   trio_flags_t flags,
	   int width,
	   int precision,
	   int base)
{
  trio_long_double_t integerNumber;
  trio_long_double_t fractionNumber;
  trio_long_double_t workNumber;
  int integerDigits;
  int fractionDigits;
  int exponentDigits;
  int workDigits;
  int baseDigits;
  int integerThreshold;
  int fractionThreshold;
  int expectedWidth;
  int exponent = 0;
  unsigned int uExponent = 0;
  int exponentBase;
  trio_long_double_t dblBase;
  trio_long_double_t dblFractionBase;
  trio_long_double_t integerAdjust;
  trio_long_double_t fractionAdjust;
  trio_long_double_t workFractionNumber;
  trio_long_double_t workFractionAdjust;
  int fractionDigitsInspect;
  BOOLEAN_T isNegative;
  BOOLEAN_T isExponentNegative = FALSE;
  BOOLEAN_T requireTwoDigitExponent;
  BOOLEAN_T isHex;
  TRIO_CONST char *digits;
# if TRIO_FEATURE_QUOTE
  char *groupingPointer;
# endif
  int i;
  int offset;
  BOOLEAN_T hasOnlyZeroes;
  int leadingFractionZeroes = -1;
  register int trailingZeroes;
  BOOLEAN_T keepTrailingZeroes;
  BOOLEAN_T keepDecimalPoint;
  trio_long_double_t epsilon;
  BOOLEAN_T adjustNumber = FALSE;
  
  assert(VALID(self));
  assert(VALID(self->OutStream));
  assert(((base >= MIN_BASE) && (base <= MAX_BASE)) || (base == NO_BASE));

  /* Determine sign and look for special quantities */
  switch (trio_fpclassify_and_signbit(number, &isNegative))
    {
    case TRIO_FP_NAN:
      TrioWriteString(self,
		      (flags & FLAGS_UPPER)
		      ? NAN_UPPER
		      : NAN_LOWER,
		      flags, width, precision);
      return;
      
    case TRIO_FP_INFINITE:
      if (isNegative)
	{
	  /* Negative infinity */
	  TrioWriteString(self,
			  (flags & FLAGS_UPPER)
			  ? "-" INFINITE_UPPER
			  : "-" INFINITE_LOWER,
			  flags, width, precision);
	  return;
	}
      else
	{
	  /* Positive infinity */
	  TrioWriteString(self,
			  (flags & FLAGS_UPPER)
			  ? INFINITE_UPPER
			  : INFINITE_LOWER,
			  flags, width, precision);
	  return;
	}

    default:
      /* Finitude */
      break;
    }
  
  /* Normal numbers */
  if (flags & FLAGS_LONGDOUBLE)
    {
      baseDigits = (base == 10)
	? LDBL_DIG
	: (int)trio_floor(LDBL_MANT_DIG / TrioLogarithmBase(base));
      epsilon = LDBL_EPSILON;
    }
  else if (flags & FLAGS_SHORT)
    {
      baseDigits = (base == BASE_DECIMAL)
	? FLT_DIG
	: (int)trio_floor(FLT_MANT_DIG / TrioLogarithmBase(base));
      epsilon = FLT_EPSILON;
    }
  else
    {
      baseDigits = (base == BASE_DECIMAL)
	? DBL_DIG
	: (int)trio_floor(DBL_MANT_DIG / TrioLogarithmBase(base));
      epsilon = DBL_EPSILON;
    }

  digits = (flags & FLAGS_UPPER) ? internalDigitsUpper : internalDigitsLower;
  isHex = (base == BASE_HEX);
  if (base == NO_BASE)
    base = BASE_DECIMAL;
  dblBase = (trio_long_double_t)base;
  keepTrailingZeroes = !( (flags & FLAGS_ROUNDING) ||
			  ( (flags & FLAGS_FLOAT_G) &&
			    !(flags & FLAGS_ALTERNATIVE) ) );

# if TRIO_FEATURE_ROUNDING
  if (flags & FLAGS_ROUNDING)
    {
      precision = baseDigits;
    }
# endif

  if (precision == NO_PRECISION)
    {
      if (isHex)
	{
	  keepTrailingZeroes = FALSE;
	  precision = FLT_MANT_DIG;
	}
      else
	{
	  precision = FLT_DIG;
	}
    }
  
  if (isNegative)
    {
      number = -number;
    }

  if (isHex)
    {
      flags |= FLAGS_FLOAT_E;
    }

 reprocess:

  if (flags & FLAGS_FLOAT_G)
    {
      if (precision == 0)
	precision = 1;

      if ( (number < TRIO_SUFFIX_LONG(1.0E-4)) ||
	   (number >= TrioPower(base, (trio_long_double_t)precision)) )
	{
	  /* Use scientific notation */
	  flags |= FLAGS_FLOAT_E;
	}
      else if (number < 1.0)
	{
	  /*
	   * Use normal notation. If the integer part of the number is
	   * zero, then adjust the precision to include leading fractional
	   * zeros.
	   */
	  workNumber = TrioLogarithm(number, base);
	  workNumber = TRIO_FABS(workNumber);
	  if (workNumber - trio_floor(workNumber) < epsilon)
	    workNumber--;
	  leadingFractionZeroes = (int)trio_floor(workNumber);
	}
    }

  if (flags & FLAGS_FLOAT_E)
    {
      /* Scale the number */
      workNumber = TrioLogarithm(number, base);
      if (trio_isinf(workNumber) == -1)
	{
	  exponent = 0;
	  /* Undo setting */
	  if (flags & FLAGS_FLOAT_G)
	    flags &= ~FLAGS_FLOAT_E;
	}
      else
	{
	  exponent = (int)trio_floor(workNumber);
	  workNumber = number;
	  /*
	   * The expression A * 10^-B is equivalent to A / 10^B but the former
	   * usually gives better accuracy.
	   */
	  workNumber *= TrioPower(dblBase, (trio_long_double_t)-exponent);
	  if (trio_isinf(workNumber)) {
	    /*
	     * Scaling is done it two steps to avoid problems with subnormal
	     * numbers.
	     */
	    workNumber /= TrioPower(dblBase, (trio_long_double_t)(exponent / 2));
	    workNumber /= TrioPower(dblBase, (trio_long_double_t)(exponent - (exponent / 2)));
	  }
	  number = workNumber;
	  isExponentNegative = (exponent < 0);
	  uExponent = (isExponentNegative) ? -exponent : exponent;
	  if (isHex)
	    uExponent *= 4; /* log16(2) */
#if TRIO_FEATURE_QUOTE
	  /* No thousand separators */
	  flags &= ~FLAGS_QUOTE;
#endif
	}
    }

  integerNumber = trio_floor(number);
  fractionNumber = number - integerNumber;

  /*
   * Truncated number.
   *
   * Precision is number of significant digits for FLOAT_G and number of
   * fractional digits for others.
   */
  integerDigits = 1;
  if (integerNumber > epsilon)
    {
      integerDigits += (int)TrioLogarithm(integerNumber, base);
    }

  fractionDigits = precision;
  if (flags & FLAGS_FLOAT_G)
    {
      if (leadingFractionZeroes > 0)
	{
	  fractionDigits += leadingFractionZeroes;
	}
      if ((integerNumber > epsilon) || (number <= epsilon))
	{
	  fractionDigits -= integerDigits;
	}
    }

  dblFractionBase = TrioPower(base, fractionDigits);

  if (integerNumber < 1.0)
    {
      workNumber = number * dblFractionBase + TRIO_SUFFIX_LONG(0.5);
      if (trio_floor(number * dblFractionBase) != trio_floor(workNumber))
	{
	  adjustNumber = TRUE;
	  /* Remove a leading fraction zero if fraction is rounded up */
	  if ((int)TrioLogarithm(number * dblFractionBase, base) != (int)TrioLogarithm(workNumber, base))
	    {
	      --leadingFractionZeroes;
	    }
	}
      workNumber /= dblFractionBase;
    }
  else
    {
      workNumber = number + TRIO_SUFFIX_LONG(0.5) / dblFractionBase;
      adjustNumber = (trio_floor(number) != trio_floor(workNumber));
    }
  if (adjustNumber)
    {
      if ((flags & FLAGS_FLOAT_G) && !(flags & FLAGS_FLOAT_E))
	{
	  /* The adjustment may require a change to scientific notation */
	  if ( (workNumber < TRIO_SUFFIX_LONG(1.0E-4)) ||
	       (workNumber >= TrioPower(base, (trio_long_double_t)precision)) )
	    {
	      /* Use scientific notation */
	      flags |= FLAGS_FLOAT_E;
	      goto reprocess;
	    }
	}
      
      if (flags & FLAGS_FLOAT_E)
	{
	  workDigits = 1 + TrioLogarithm(trio_floor(workNumber), base);
	  if (integerDigits == workDigits)
	    {
	      /* Adjust if the same number of digits are used */
	      number += TRIO_SUFFIX_LONG(0.5) / dblFractionBase;
	      integerNumber = trio_floor(number);
	      fractionNumber = number - integerNumber;
	    }
	  else
	    {
	      /* Adjust if number was rounded up one digit (ie. 0.99 to 1.00) */
	      exponent++;
	      isExponentNegative = (exponent < 0);
	      uExponent = (isExponentNegative) ? -exponent : exponent;
	      if (isHex)
		uExponent *= 4; /* log16(2) */
	      workNumber = (number + TRIO_SUFFIX_LONG(0.5) / dblFractionBase) / dblBase;
	      integerNumber = trio_floor(workNumber);
	      fractionNumber = workNumber - integerNumber;
	    }
	}
      else
	{
	  if (workNumber > 1.0)
	    {
	      /* Adjust if number was rounded up one digit (ie. 99 to 100) */
	      integerNumber = trio_floor(workNumber);
	      fractionNumber = 0.0;
	      integerDigits = (integerNumber > epsilon)
		? 1 + (int)TrioLogarithm(integerNumber, base)
		: 1;
	      if (flags & FLAGS_FLOAT_G)
		{
		  if (flags & FLAGS_ALTERNATIVE)
		    {
		      if ((integerNumber > epsilon) || (number <= epsilon))
			{
			  fractionDigits -= integerDigits;
			}
		    }
		  else
		    {
		      fractionDigits = 0;
		    }
		}
	    }
	  else
	    {
	      integerNumber = trio_floor(workNumber);
	      fractionNumber = workNumber - integerNumber;
	      if (flags & FLAGS_FLOAT_G)
		{
		  if (flags & FLAGS_ALTERNATIVE)
		    {
		      fractionDigits = precision;
		      if (leadingFractionZeroes > 0)
			{
			  fractionDigits += leadingFractionZeroes;
			}
		      if ((integerNumber > epsilon) || (number <= epsilon))
			{
			  fractionDigits -= integerDigits;
			}
		    }
		}
	    }
	}
    }

  /* Estimate accuracy */
  integerAdjust = fractionAdjust = TRIO_SUFFIX_LONG(0.5);
# if TRIO_FEATURE_ROUNDING
  if (flags & FLAGS_ROUNDING)
    {
      if (integerDigits > baseDigits)
	{
	  integerThreshold = baseDigits;
	  fractionDigits = 0;
	  dblFractionBase = 1.0;
	  fractionThreshold = 0;
	  precision = 0; /* Disable decimal-point */
	  integerAdjust = TrioPower(base, integerDigits - integerThreshold - 1);
	  fractionAdjust = 0.0;
	}
      else
	{
	  integerThreshold = integerDigits;
	  fractionThreshold = fractionDigits - integerThreshold;
	  fractionAdjust = 1.0;
	}
    }
  else
# endif
    {
      integerThreshold = INT_MAX;
      fractionThreshold = INT_MAX;
    }
  
  /*
   * Calculate expected width.
   *  sign + integer part + thousands separators + decimal point
   *  + fraction + exponent
   */
  fractionAdjust /= dblFractionBase;
  hasOnlyZeroes = (trio_floor((fractionNumber + fractionAdjust) *
			       dblFractionBase) < epsilon);
  keepDecimalPoint = ( (flags & FLAGS_ALTERNATIVE) ||
		       !((precision == 0) ||
			 (!keepTrailingZeroes && hasOnlyZeroes)) );

  expectedWidth = integerDigits + fractionDigits;

  if (!keepTrailingZeroes)
    {
      trailingZeroes = 0;
      workFractionNumber = fractionNumber;
      workFractionAdjust = fractionAdjust;
      fractionDigitsInspect = fractionDigits;

      if (integerDigits > integerThreshold)
	{
	  fractionDigitsInspect = 0;
	}
      else if (fractionThreshold  <= fractionDigits)
	{
	  fractionDigitsInspect = fractionThreshold + 1;
	}

      trailingZeroes = fractionDigits - fractionDigitsInspect;
      for (i = 0; i < fractionDigitsInspect; i++)
	{
	  workFractionNumber *= dblBase;
	  workFractionAdjust *= dblBase;
	  workNumber = trio_floor(workFractionNumber + workFractionAdjust);
	  workFractionNumber -= workNumber;
	  offset = (int)trio_fmod(workNumber, dblBase);
	  if (offset == 0)
	    {
	      trailingZeroes++;
	    }
	  else
	    {
	      trailingZeroes = 0;
	    }
	}
      expectedWidth -= trailingZeroes;
    }
  
  if (keepDecimalPoint)
    {
      expectedWidth += internalDecimalPointLength;
    }
  
#if TRIO_FEATURE_QUOTE
  if (flags & FLAGS_QUOTE)
    {
      expectedWidth += TrioCalcThousandSeparatorLength(integerDigits);
    }
#endif
  
  if (isNegative || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE))
    {
      expectedWidth += sizeof("-") - 1;
    }
  
  exponentDigits = 0;
  if (flags & FLAGS_FLOAT_E)
    {
      exponentDigits = (uExponent == 0)
	? 1
	: (int)trio_ceil(TrioLogarithm((double)(uExponent + 1),
				       (isHex) ? 10 : base));
    }
  requireTwoDigitExponent = ((base == BASE_DECIMAL) && (exponentDigits == 1));
  if (exponentDigits > 0)
    {
      expectedWidth += exponentDigits;
      expectedWidth += (requireTwoDigitExponent
			? sizeof("E+0") - 1
			: sizeof("E+") - 1);
    }
  
  if (isHex)
    {
      expectedWidth += sizeof("0X") - 1;
    }
  
  /* Output prefixing */
  if (flags & FLAGS_NILPADDING)
    {
      /* Leading zeros must be after sign */
      if (isNegative)
	self->OutStream(self, '-');
      else if (flags & FLAGS_SHOWSIGN)
	self->OutStream(self, '+');
      else if (flags & FLAGS_SPACE)
	self->OutStream(self, ' ');
      if (isHex)
	{
	  self->OutStream(self, '0');
	  self->OutStream(self, (flags & FLAGS_UPPER) ? 'X' : 'x');
	}
      if (!(flags & FLAGS_LEFTADJUST))
	{
	  for (i = expectedWidth; i < width; i++)
	    {
	      self->OutStream(self, '0');
	    }
	}
    }
  else
    {
      /* Leading spaces must be before sign */
      if (!(flags & FLAGS_LEFTADJUST))
	{
	  for (i = expectedWidth; i < width; i++)
	    {
	      self->OutStream(self, CHAR_ADJUST);
	    }
	}
      if (isNegative)
	self->OutStream(self, '-');
      else if (flags & FLAGS_SHOWSIGN)
	self->OutStream(self, '+');
      else if (flags & FLAGS_SPACE)
	self->OutStream(self, ' ');
      if (isHex)
	{
	  self->OutStream(self, '0');
	  self->OutStream(self, (flags & FLAGS_UPPER) ? 'X' : 'x');
	}
    }
  
  /* Output the integer part and thousand separators */
  for (i = 0; i < integerDigits; i++)
    {
      workNumber = trio_floor(((integerNumber + integerAdjust)
			       / TrioPower(base, integerDigits - i - 1)));
      if (i > integerThreshold)
	{
	  /* Beyond accuracy */
	  self->OutStream(self, digits[0]);
	}
      else
	{
	  self->OutStream(self, digits[(int)trio_fmod(workNumber, dblBase)]);
	}

#if TRIO_FEATURE_QUOTE
      if (((flags & (FLAGS_FLOAT_E | FLAGS_QUOTE)) == FLAGS_QUOTE)
	  && TrioFollowedBySeparator(integerDigits - i))
	{
	  for (groupingPointer = internalThousandSeparator;
	       *groupingPointer != NIL;
	       groupingPointer++)
	    {
	      self->OutStream(self, *groupingPointer);
	    }
	}
#endif
    }
  
  /* Insert decimal point and build the fraction part */
  trailingZeroes = 0;

  if (keepDecimalPoint)
    {
      if (internalDecimalPoint)
	{
	  self->OutStream(self, internalDecimalPoint);
	}
      else
	{
	  for (i = 0; i < internalDecimalPointLength; i++)
	    {
	      self->OutStream(self, internalDecimalPointString[i]);
	    }
	}
    }

  for (i = 0; i < fractionDigits; i++)
    {
      if ((integerDigits > integerThreshold) || (i > fractionThreshold))
	{
	  /* Beyond accuracy */
	  trailingZeroes++;
	}
      else
	{
	  fractionNumber *= dblBase;
	  fractionAdjust *= dblBase;
	  workNumber = trio_floor(fractionNumber + fractionAdjust);
	  if (workNumber > fractionNumber)
	    {
	      /* fractionNumber should never become negative */
	      fractionNumber = 0.0;
	      fractionAdjust = 0.0;
	    }
	  else
	    {
	      fractionNumber -= workNumber;
	    }
	  offset = (int)trio_fmod(workNumber, dblBase);
	  if (offset == 0)
	    {
	      trailingZeroes++;
	    }
	  else
	    {
	      while (trailingZeroes > 0)
		{
		  /* Not trailing zeroes after all */
		  self->OutStream(self, digits[0]);
		  trailingZeroes--;
		}
	      self->OutStream(self, digits[offset]);
	    }
	}
    }
  
  if (keepTrailingZeroes)
    {
      while (trailingZeroes > 0)
	{
	  self->OutStream(self, digits[0]);
	  trailingZeroes--;
	}
    }
  
  /* Output exponent */
  if (exponentDigits > 0)
    {
      self->OutStream(self,
		      isHex
		      ? ((flags & FLAGS_UPPER) ? 'P' : 'p')
		      : ((flags & FLAGS_UPPER) ? 'E' : 'e'));
      self->OutStream(self, (isExponentNegative) ? '-' : '+');

      /* The exponent must contain at least two digits */
      if (requireTwoDigitExponent)
        self->OutStream(self, '0');

      if (isHex)
	base = 10;
      exponentBase = (int)TrioPower(base, exponentDigits - 1);
      for (i = 0; i < exponentDigits; i++)
	{
	  self->OutStream(self, digits[(uExponent / exponentBase) % base]);
	  exponentBase /= base;
	}
    }
  /* Output trailing spaces */
  if (flags & FLAGS_LEFTADJUST)
    {
      for (i = expectedWidth; i < width; i++)
	{
	  self->OutStream(self, CHAR_ADJUST);
	}
    }
}
#endif /* TRIO_FEATURE_FLOAT */

/*************************************************************************
 * TrioFormatProcess
 *
 * Description:
 *  This is the main engine for formatting output
 */
TRIO_PRIVATE int
TrioFormatProcess
TRIO_ARGS3((data, format, parameters),
	   trio_class_t *data,
	   TRIO_CONST char *format,
	   trio_parameter_t *parameters)
{
  int i;
#if TRIO_FEATURE_ERRNO
  TRIO_CONST char *string;
#endif
  trio_pointer_t pointer;
  trio_flags_t flags;
  int width;
  int precision;
  int base;
  int offset;
  
  offset = 0;
  i = 0;

  for (;;)
    {
      /* Skip the parameter entries */
      while (parameters[i].type == FORMAT_PARAMETER)
	i++;

      /* Copy non conversion-specifier part of format string */
      while (offset < parameters[i].beginOffset)
        {
	  if (CHAR_IDENTIFIER == format[offset] && CHAR_IDENTIFIER == format[offset + 1])
	    {
	      data->OutStream(data, CHAR_IDENTIFIER);
	      offset += 2;
	    }
	  else
	    {
	      data->OutStream(data, format[offset++]);
	    }
	}

      /* Abort if we reached end of format string */
      if (parameters[i].type == FORMAT_SENTINEL)
	break;

      /* Ouput parameter */
      flags = parameters[i].flags;

      /* Find width */
      width = parameters[i].width;
      if (flags & FLAGS_WIDTH_PARAMETER)
	{
	  /* Get width from parameter list */
	  width = (int)parameters[width].data.number.as_signed;
	  if (width < 0)
	    {
	      /*
	       * A negative width is the same as the - flag and
	       * a positive width.
	       */
	      flags |= FLAGS_LEFTADJUST;
	      flags &= ~FLAGS_NILPADDING;
	      width = -width;
	    }
	}

      /* Find precision */
      if (flags & FLAGS_PRECISION)
	{
	  precision = parameters[i].precision;
	  if (flags & FLAGS_PRECISION_PARAMETER)
	    {
	      /* Get precision from parameter list */
	      precision = (int)parameters[precision].data.number.as_signed;
	      if (precision < 0)
		{
		  /*
		   * A negative precision is the same as no
		   * precision
		   */
		  precision = NO_PRECISION;
		}
	    }
	}
      else
	{
	  precision = NO_PRECISION;
	}

      /* Find base */
      if (NO_BASE != parameters[i].baseSpecifier)
	{
	  /* Base from specifier has priority */
	  base = parameters[i].baseSpecifier;
	}
      else if (flags & FLAGS_BASE_PARAMETER)
	{
	  /* Get base from parameter list */
	  base = parameters[i].base;
	  base = (int)parameters[base].data.number.as_signed;
	}
      else
	{
	  /* Use base from format string */
	  base = parameters[i].base;
	}

      switch (parameters[i].type)
        {
	case FORMAT_CHAR:
#if TRIO_FEATURE_QUOTE
	  if (flags & FLAGS_QUOTE)
	    data->OutStream(data, CHAR_QUOTE);
#endif
	  if (! (flags & FLAGS_LEFTADJUST))
	    {
	      while (--width > 0)
		data->OutStream(data, CHAR_ADJUST);
	    }
#if TRIO_FEATURE_WIDECHAR
	  if (flags & FLAGS_WIDECHAR)
	    {
	      TrioWriteWideStringCharacter(data,
					   (trio_wchar_t)parameters[i].data.number.as_signed,
					   flags,
					   NO_WIDTH);
	    }
	  else
#endif
	  {
	    TrioWriteStringCharacter(data,
				     (int)parameters[i].data.number.as_signed,
				     flags);
	  }

	  if (flags & FLAGS_LEFTADJUST)
	    {
	      while(--width > 0)
		data->OutStream(data, CHAR_ADJUST);
	    }
#if TRIO_FEATURE_QUOTE
	  if (flags & FLAGS_QUOTE)
	    data->OutStream(data, CHAR_QUOTE);
#endif

	  break; /* FORMAT_CHAR */

	case FORMAT_INT:
	  TrioWriteNumber(data,
			  parameters[i].data.number.as_unsigned,
			  flags,
			  width,
			  precision,
			  base);

	  break; /* FORMAT_INT */

#if TRIO_FEATURE_FLOAT
	case FORMAT_DOUBLE:
	  TrioWriteDouble(data,
			  parameters[i].data.longdoubleNumber,
			  flags,
			  width,
			  precision,
			  base);
	  break; /* FORMAT_DOUBLE */
#endif

	case FORMAT_STRING:
#if TRIO_FEATURE_WIDECHAR
	  if (flags & FLAGS_WIDECHAR)
	    {
	      TrioWriteWideString(data,
				  parameters[i].data.wstring,
				  flags,
				  width,
				  precision);
	    }
	  else
#endif
	    {
	      TrioWriteString(data,
			      parameters[i].data.string,
			      flags,
			      width,
			      precision);
	    }
	  break; /* FORMAT_STRING */

	case FORMAT_POINTER:
	  {
	    trio_reference_t reference;

	    reference.data = data;
	    reference.parameter = &parameters[i];
	    trio_print_pointer(&reference, parameters[i].data.pointer);
	  }
	  break; /* FORMAT_POINTER */

	case FORMAT_COUNT:
	  pointer = parameters[i].data.pointer;
	  if (NULL != pointer)
	    {
	      /*
	       * C99 paragraph 7.19.6.1.8 says "the number of
	       * characters written to the output stream so far by
	       * this call", which is data->actually.committed
	       */
#if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER
	      if (flags & FLAGS_SIZE_T)
		*(size_t *)pointer = (size_t)data->actually.committed;
	      else
#endif
#if TRIO_FEATURE_PTRDIFF_T
	      if (flags & FLAGS_PTRDIFF_T)
		*(ptrdiff_t *)pointer = (ptrdiff_t)data->actually.committed;
	      else
#endif
#if TRIO_FEATURE_INTMAX_T
	      if (flags & FLAGS_INTMAX_T)
		*(trio_intmax_t *)pointer = (trio_intmax_t)data->actually.committed;
	      else
#endif
	      if (flags & FLAGS_QUAD)
		{
		  *(trio_ulonglong_t *)pointer = (trio_ulonglong_t)data->actually.committed;
		}
	      else if (flags & FLAGS_LONG)
		{
		  *(long int *)pointer = (long int)data->actually.committed;
		}
	      else if (flags & FLAGS_SHORT)
		{
		  *(short int *)pointer = (short int)data->actually.committed;
		}
	      else
		{
		  *(int *)pointer = (int)data->actually.committed;
		}
	    }
	  break; /* FORMAT_COUNT */

	case FORMAT_PARAMETER:
	  break; /* FORMAT_PARAMETER */

#if TRIO_FEATURE_ERRNO
	case FORMAT_ERRNO:
	  string = trio_error(parameters[i].data.errorNumber);
	  if (string)
	    {
	      TrioWriteString(data,
			      string,
			      flags,
			      width,
			      precision);
	    }
	  else
	  {
	    data->OutStream(data, '#');
	    TrioWriteNumber(data,
			    (trio_uintmax_t)parameters[i].data.errorNumber,
			    flags,
			    width,
			    precision,
			    BASE_DECIMAL);
	  }
	  break; /* FORMAT_ERRNO */
#endif /* TRIO_FEATURE_ERRNO */

#if TRIO_FEATURE_USER_DEFINED
	case FORMAT_USER_DEFINED:
	  {
	    trio_reference_t reference;
	    trio_userdef_t *def = NULL;

	    if (parameters[i].flags & FLAGS_USER_DEFINED_PARAMETER)
	      {
		/* Use handle */
		if ((i > 0) ||
		    (parameters[i - 1].type == FORMAT_PARAMETER))
		  def = (trio_userdef_t *)parameters[i - 1].data.pointer;
	      }
	    else
	      {
		/* Look up namespace */
		def = TrioFindNamespace(parameters[i].user_defined.namespace, NULL);
	      }
	    if (def)
	      {
		reference.data = data;
		reference.parameter = &parameters[i];
		def->callback(&reference);
	      }
	  }
	  break;
#endif /* TRIO_FEATURE_USER_DEFINED */

	default:
	  break;
	} /* switch parameter type */

      /* Prepare for next */
      offset = parameters[i].endOffset;
      i++;
    }

  return data->processed;
}

/*************************************************************************
 * TrioFormatRef
 */
#if TRIO_EXTENSION
TRIO_PRIVATE int
TrioFormatRef
TRIO_ARGS4((reference, format, arglist, argarray),
	   trio_reference_t *reference,
	   TRIO_CONST char *format,
	   va_list arglist,
	   trio_pointer_t *argarray)
{
  int status;
  trio_parameter_t parameters[MAX_PARAMETERS];

  status = TrioParse(TYPE_PRINT, format, parameters, arglist, argarray);
  if (status < 0)
    return status;

  status = TrioFormatProcess(reference->data, format, parameters);
  if (reference->data->error != 0)
    {
      status = reference->data->error;
    }
  return status;
}
#endif /* TRIO_EXTENSION */

/*************************************************************************
 * TrioFormat
 */
TRIO_PRIVATE int
TrioFormat
TRIO_ARGS6((destination, destinationSize, OutStream, format, arglist, argarray),
	   trio_pointer_t destination,
	   size_t destinationSize,
	   void (*OutStream) TRIO_PROTO((trio_class_t *, int)),
	   TRIO_CONST char *format,
	   va_list arglist,
	   trio_pointer_t *argarray)
{
  int status;
  trio_class_t data;
  trio_parameter_t parameters[MAX_PARAMETERS];

  assert(VALID(OutStream));
  assert(VALID(format));

  memset(&data, 0, sizeof(data));
  data.OutStream = OutStream;
  data.location = destination;
  data.max = destinationSize;
  data.error = 0;

#if defined(USE_LOCALE)
  if (NULL == internalLocaleValues)
    {
      TrioSetLocale();
    }
#endif

  status = TrioParse(TYPE_PRINT, format, parameters, arglist, argarray);
  if (status < 0)
    return status;

  status = TrioFormatProcess(&data, format, parameters);
  if (data.error != 0)
    {
      status = data.error;
    }
  return status;
}

/*************************************************************************
 * TrioOutStreamFile
 */
#if TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO
TRIO_PRIVATE void
TrioOutStreamFile
TRIO_ARGS2((self, output),
	   trio_class_t *self,
	   int output)
{
  FILE *file;

  assert(VALID(self));
  assert(VALID(self->location));

  file = (FILE *)self->location;
  self->processed++;
  if (fputc(output, file) == EOF)
    {
      self->error = TRIO_ERROR_RETURN(TRIO_EOF, 0);
    }
  else
    {
      self->actually.committed++;
    }
}
#endif /* TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO */

/*************************************************************************
 * TrioOutStreamFileDescriptor
 */
#if TRIO_FEATURE_FD
TRIO_PRIVATE void
TrioOutStreamFileDescriptor
TRIO_ARGS2((self, output),
	   trio_class_t *self,
	   int output)
{
  int fd;
  char ch;

  assert(VALID(self));

  fd = *((int *)self->location);
  ch = (char)output;
  self->processed++;
  if (write(fd, &ch, sizeof(char)) == -1)
    {
      self->error = TRIO_ERROR_RETURN(TRIO_ERRNO, 0);
    }
  else
    {
      self->actually.committed++;
    }
}
#endif /* TRIO_FEATURE_FD */

/*************************************************************************
 * TrioOutStreamCustom
 */
#if TRIO_FEATURE_CLOSURE
TRIO_PRIVATE void
TrioOutStreamCustom
TRIO_ARGS2((self, output),
	   trio_class_t *self,
	   int output)
{
  int status;
  trio_custom_t *data;

  assert(VALID(self));
  assert(VALID(self->location));

  data = (trio_custom_t *)self->location;
  if (data->stream.out)
    {
      status = (data->stream.out)(data->closure, output);
      if (status >= 0)
	{
	  self->actually.committed++;
	}
      else
	{
	  if (self->error == 0)
	    {
	      self->error = TRIO_ERROR_RETURN(TRIO_ECUSTOM, -status);
	    }
	}
    }
  self->processed++;
}
#endif /* TRIO_FEATURE_CLOSURE */

/*************************************************************************
 * TrioOutStreamString
 */
TRIO_PRIVATE void
TrioOutStreamString
TRIO_ARGS2((self, output),
	   trio_class_t *self,
	   int output)
{
  char **buffer;

  assert(VALID(self));
  assert(VALID(self->location));

  buffer = (char **)self->location;
  **buffer = (char)output;
  (*buffer)++;
  self->processed++;
  self->actually.committed++;
}

/*************************************************************************
 * TrioOutStreamStringMax
 */
TRIO_PRIVATE void
TrioOutStreamStringMax
TRIO_ARGS2((self, output),
	   trio_class_t *self,
	   int output)
{
  char **buffer;

  assert(VALID(self));
  assert(VALID(self->location));
  
  buffer = (char **)self->location;

  if (self->processed < self->max)
    {
      **buffer = (char)output;
      (*buffer)++;
      self->actually.committed++;
    }
  self->processed++;
}

/*************************************************************************
 * TrioOutStreamStringDynamic
 */
#if TRIO_FEATURE_DYNAMICSTRING
TRIO_PRIVATE void
TrioOutStreamStringDynamic
TRIO_ARGS2((self, output),
	   trio_class_t *self,
	   int output)
{
  assert(VALID(self));
  assert(VALID(self->location));

  if (self->error == 0)
    {
      trio_xstring_append_char((trio_string_t *)self->location,
			       (char)output);
      self->actually.committed++;
    }
  /* The processed variable must always be increased */
  self->processed++;
}
#endif /* TRIO_FEATURE_DYNAMICSTRING */

/*************************************************************************
 *
 * Formatted printing functions
 *
 ************************************************************************/

#if defined(TRIO_DOCUMENTATION)
# include "doc/doc_printf.h"
#endif
/** @addtogroup Printf
    @{
*/

/*************************************************************************
 * printf
 */

/**
   Print to standard output stream.

   @param format Formatting string.
   @param ... Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int
trio_printf
TRIO_VARGS2((format, va_alist),
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;

  assert(VALID(format));
  
  TRIO_VA_START(args, format);
  status = TrioFormat(stdout, 0, TrioOutStreamFile, format, args, NULL);
  TRIO_VA_END(args);
  return status;
}
#endif /* TRIO_FEATURE_STDIO */

/**
   Print to standard output stream.

   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int
trio_vprintf
TRIO_ARGS2((format, args),
	   TRIO_CONST char *format,
	   va_list args)
{
  assert(VALID(format));

  return TrioFormat(stdout, 0, TrioOutStreamFile, format, args, NULL);
}
#endif /* TRIO_FEATURE_STDIO */

/**
   Print to standard output stream.

   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int
trio_printfv
TRIO_ARGS2((format, args),
	   TRIO_CONST char *format,
	   trio_pointer_t * args)
{
  static va_list unused;
  
  assert(VALID(format));

  return TrioFormat(stdout, 0, TrioOutStreamFile, format, unused, args);
}
#endif /* TRIO_FEATURE_STDIO */

/*************************************************************************
 * fprintf
 */

/**
   Print to file.

   @param file File pointer.
   @param format Formatting string.
   @param ... Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int
trio_fprintf
TRIO_VARGS3((file, format, va_alist),
	    FILE *file,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;

  assert(VALID(file));
  assert(VALID(format));
  
  TRIO_VA_START(args, format);
  status = TrioFormat(file, 0, TrioOutStreamFile, format, args, NULL);
  TRIO_VA_END(args);
  return status;
}
#endif /* TRIO_FEATURE_FILE */

/**
   Print to file.

   @param file File pointer.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int
trio_vfprintf
TRIO_ARGS3((file, format, args),
	   FILE *file,
	   TRIO_CONST char *format,
	   va_list args)
{
  assert(VALID(file));
  assert(VALID(format));
  
  return TrioFormat(file, 0, TrioOutStreamFile, format, args, NULL);
}
#endif /* TRIO_FEATURE_FILE */

/**
   Print to file.

   @param file File pointer.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int
trio_fprintfv
TRIO_ARGS3((file, format, args),
	   FILE *file,
	   TRIO_CONST char *format,
	   trio_pointer_t * args)
{
  static va_list unused;
  
  assert(VALID(file));
  assert(VALID(format));
  
  return TrioFormat(file, 0, TrioOutStreamFile, format, unused, args);
}
#endif /* TRIO_FEATURE_FILE */

/*************************************************************************
 * dprintf
 */

/**
   Print to file descriptor.

   @param fd File descriptor.
   @param format Formatting string.
   @param ... Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_FD
TRIO_PUBLIC int
trio_dprintf
TRIO_VARGS3((fd, format, va_alist),
	    int fd,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;

  assert(VALID(format));
  
  TRIO_VA_START(args, format);
  status = TrioFormat(&fd, 0, TrioOutStreamFileDescriptor, format, args, NULL);
  TRIO_VA_END(args);
  return status;
}
#endif /* TRIO_FEATURE_FD */

/**
   Print to file descriptor.

   @param fd File descriptor.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_FD
TRIO_PUBLIC int
trio_vdprintf
TRIO_ARGS3((fd, format, args),
	   int fd,
	   TRIO_CONST char *format,
	   va_list args)
{
  assert(VALID(format));
  
  return TrioFormat(&fd, 0, TrioOutStreamFileDescriptor, format, args, NULL);
}
#endif /* TRIO_FEATURE_FD */

/**
   Print to file descriptor.

   @param fd File descriptor.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_FD
TRIO_PUBLIC int
trio_dprintfv
TRIO_ARGS3((fd, format, args),
	   int fd,
	   TRIO_CONST char *format,
	   trio_pointer_t *args)
{
  static va_list unused;
  
  assert(VALID(format));
  
  return TrioFormat(&fd, 0, TrioOutStreamFileDescriptor, format, unused, args);
}
#endif /* TRIO_FEATURE_FD */

/*************************************************************************
 * cprintf
 */
#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int
trio_cprintf
TRIO_VARGS4((stream, closure, format, va_alist),
	    trio_outstream_t stream,
	    trio_pointer_t closure,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;
  trio_custom_t data;

  assert(VALID(stream));
  assert(VALID(format));

  TRIO_VA_START(args, format);
  data.stream.out = stream;
  data.closure = closure;
  status = TrioFormat(&data, 0, TrioOutStreamCustom, format, args, NULL);
  TRIO_VA_END(args);
  return status;
}
#endif /* TRIO_FEATURE_CLOSURE */

#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int
trio_vcprintf
TRIO_ARGS4((stream, closure, format, args),
	   trio_outstream_t stream,
	   trio_pointer_t closure,
	   TRIO_CONST char *format,
	   va_list args)
{
  trio_custom_t data;

  assert(VALID(stream));
  assert(VALID(format));

  data.stream.out = stream;
  data.closure = closure;
  return TrioFormat(&data, 0, TrioOutStreamCustom, format, args, NULL);
}
#endif /* TRIO_FEATURE_CLOSURE */

#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int
trio_cprintfv
TRIO_ARGS4((stream, closure, format, args),
	   trio_outstream_t stream,
	   trio_pointer_t closure,
	   TRIO_CONST char *format,
	   void **args)
{
  static va_list unused;
  trio_custom_t data;

  assert(VALID(stream));
  assert(VALID(format));

  data.stream.out = stream;
  data.closure = closure;
  return TrioFormat(&data, 0, TrioOutStreamCustom, format, unused, args);
}
#endif /* TRIO_FEATURE_CLOSURE */

/*************************************************************************
 * sprintf
 */

/**
   Print to string.

   @param buffer Output string.
   @param format Formatting string.
   @param ... Arguments.
   @return Number of printed characters.
 */
TRIO_PUBLIC int
trio_sprintf
TRIO_VARGS3((buffer, format, va_alist),
	    char *buffer,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;

  assert(VALID(buffer));
  assert(VALID(format));
  
  TRIO_VA_START(args, format);
  status = TrioFormat(&buffer, 0, TrioOutStreamString, format, args, NULL);
  *buffer = NIL; /* Terminate with NIL character */
  TRIO_VA_END(args);
  return status;
}

/**
   Print to string.

   @param buffer Output string.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
TRIO_PUBLIC int
trio_vsprintf
TRIO_ARGS3((buffer, format, args),
	   char *buffer,
	   TRIO_CONST char *format,
	   va_list args)
{
  int status;

  assert(VALID(buffer));
  assert(VALID(format));

  status = TrioFormat(&buffer, 0, TrioOutStreamString, format, args, NULL);
  *buffer = NIL;
  return status;
}

/**
   Print to string.

   @param buffer Output string.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
TRIO_PUBLIC int
trio_sprintfv
TRIO_ARGS3((buffer, format, args),
	   char *buffer,
	   TRIO_CONST char *format,
	   trio_pointer_t *args)
{
  static va_list unused;
  int status;
  
  assert(VALID(buffer));
  assert(VALID(format));

  status = TrioFormat(&buffer, 0, TrioOutStreamString, format, unused, args);
  *buffer = NIL;
  return status;
}

/*************************************************************************
 * snprintf
 */

/**
   Print at most @p max characters to string.

   @param buffer Output string.
   @param max Maximum number of characters to print.
   @param format Formatting string.
   @param ... Arguments.
   @return Number of printed characters.
 */
TRIO_PUBLIC int
trio_snprintf
TRIO_VARGS4((buffer, max, format, va_alist),
	    char *buffer,
	    size_t max,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;

  assert(VALID(buffer) || (max == 0));
  assert(VALID(format));

  TRIO_VA_START(args, format);
  status = TrioFormat(&buffer, max > 0 ? max - 1 : 0,
		      TrioOutStreamStringMax, format, args, NULL);
  if (max > 0)
    *buffer = NIL;
  TRIO_VA_END(args);
  return status;
}

/**
   Print at most @p max characters to string.

   @param buffer Output string.
   @param max Maximum number of characters to print.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
TRIO_PUBLIC int
trio_vsnprintf
TRIO_ARGS4((buffer, max, format, args),
	   char *buffer,
	   size_t max,
	   TRIO_CONST char *format,
	   va_list args)
{
  int status;

  assert(VALID(buffer) || (max == 0));
  assert(VALID(format));

  status = TrioFormat(&buffer, max > 0 ? max - 1 : 0,
		      TrioOutStreamStringMax, format, args, NULL);
  if (max > 0)
    *buffer = NIL;
  return status;
}

/**
   Print at most @p max characters to string.

   @param buffer Output string.
   @param max Maximum number of characters to print.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
TRIO_PUBLIC int
trio_snprintfv
TRIO_ARGS4((buffer, max, format, args),
	   char *buffer,
	   size_t max,
	   TRIO_CONST char *format,
	   trio_pointer_t *args)
{
  static va_list unused;
  int status;

  assert(VALID(buffer) || (max == 0));
  assert(VALID(format));

  status = TrioFormat(&buffer, max > 0 ? max - 1 : 0,
		      TrioOutStreamStringMax, format, unused, args);
  if (max > 0)
    *buffer = NIL;
  return status;
}

/*************************************************************************
 * snprintfcat
 * Appends the new string to the buffer string overwriting the '\0'
 * character at the end of buffer.
 */
#if TRIO_EXTENSION
TRIO_PUBLIC int
trio_snprintfcat
TRIO_VARGS4((buffer, max, format, va_alist),
	    char *buffer,
	    size_t max,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;
  size_t buf_len;

  TRIO_VA_START(args, format);

  assert(VALID(buffer));
  assert(VALID(format));

  buf_len = trio_length(buffer);
  buffer = &buffer[buf_len];

  status = TrioFormat(&buffer, max - 1 - buf_len,
		      TrioOutStreamStringMax, format, args, NULL);
  TRIO_VA_END(args);
  *buffer = NIL;
  return status;
}
#endif

#if TRIO_EXTENSION
TRIO_PUBLIC int
trio_vsnprintfcat
TRIO_ARGS4((buffer, max, format, args),
	   char *buffer,
	   size_t max,
	   TRIO_CONST char *format,
	   va_list args)
{
  int status;
  size_t buf_len;
  
  assert(VALID(buffer));
  assert(VALID(format));

  buf_len = trio_length(buffer);
  buffer = &buffer[buf_len];
  status = TrioFormat(&buffer, max - 1 - buf_len,
		      TrioOutStreamStringMax, format, args, NULL);
  *buffer = NIL;
  return status;
}
#endif

/*************************************************************************
 * trio_aprintf
 */

#if TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC char *
trio_aprintf
TRIO_VARGS2((format, va_alist),
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  va_list args;
  trio_string_t *info;
  char *result = NULL;

  assert(VALID(format));
  
  info = trio_xstring_duplicate("");
  if (info)
    {
      TRIO_VA_START(args, format);
      (void)TrioFormat(info, 0, TrioOutStreamStringDynamic,
		       format, args, NULL);
      TRIO_VA_END(args);

      trio_string_terminate(info);
      result = trio_string_extract(info);
      trio_string_destroy(info);
    }
  return result;
}
#endif /* TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING */

#if TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC char *
trio_vaprintf
TRIO_ARGS2((format, args),
	   TRIO_CONST char *format,
	   va_list args)
{
  trio_string_t *info;
  char *result = NULL;
  
  assert(VALID(format));
  
  info = trio_xstring_duplicate("");
  if (info)
    {
      (void)TrioFormat(info, 0, TrioOutStreamStringDynamic,
		       format, args, NULL);
      trio_string_terminate(info);
      result = trio_string_extract(info);
      trio_string_destroy(info);
    }
  return result;
}
#endif /* TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING */

/**
   Allocate and print to string.
   The memory allocated and returned by @p result must be freed by the
   calling application.

   @param result Output string.
   @param format Formatting string.
   @param ... Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC int
trio_asprintf
TRIO_VARGS3((result, format, va_alist),
	    char **result,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  va_list args;
  int status;
  trio_string_t *info;

  assert(VALID(format));

  *result = NULL;
  
  info = trio_xstring_duplicate("");
  if (info == NULL)
    {
      status = TRIO_ERROR_RETURN(TRIO_ENOMEM, 0);
    }
  else
    {
      TRIO_VA_START(args, format);
      status = TrioFormat(info, 0, TrioOutStreamStringDynamic,
			  format, args, NULL);
      TRIO_VA_END(args);
      if (status >= 0)
	{
	  trio_string_terminate(info);
	  *result = trio_string_extract(info);
	}
      trio_string_destroy(info);
    }
  return status;
}
#endif /* TRIO_FEATURE_DYNAMICSTRING */

/**
   Allocate and print to string.
   The memory allocated and returned by @p result must be freed by the
   calling application.

   @param result Output string.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC int
trio_vasprintf
TRIO_ARGS3((result, format, args),
	   char **result,
	   TRIO_CONST char *format,
	   va_list args)
{
  int status;
  trio_string_t *info;
  
  assert(VALID(format));

  *result = NULL;
  
  info = trio_xstring_duplicate("");
  if (info == NULL)
    {
      status = TRIO_ERROR_RETURN(TRIO_ENOMEM, 0);
    }
  else
    {
      status = TrioFormat(info, 0, TrioOutStreamStringDynamic,
			  format, args, NULL);
      if (status >= 0)
	{
	  trio_string_terminate(info);
	  *result = trio_string_extract(info);
	}
      trio_string_destroy(info);
    }
  return status;
}
#endif /* TRIO_FEATURE_DYNAMICSTRING */

/**
   Allocate and print to string.
   The memory allocated and returned by @p result must be freed by the
   calling application.

   @param result Output string.
   @param format Formatting string.
   @param args Arguments.
   @return Number of printed characters.
 */
#if TRIO_FEATURE_DYNAMICSTRING
TRIO_PUBLIC int
trio_asprintfv
TRIO_ARGS3((result, format, args),
           char **result,
           TRIO_CONST char *format,
           trio_pointer_t * args)
{
  static va_list unused;
  int status;
  trio_string_t *info;
  
  assert(VALID(format));

  *result = NULL;

  info = trio_xstring_duplicate("");
  if (info == NULL)
    {
      status = TRIO_ERROR_RETURN(TRIO_ENOMEM, 0);
    }
  else
    {
      status = TrioFormat(info, 0, TrioOutStreamStringDynamic,
                          format, unused, args);
      if (status >= 0)
        {
          trio_string_terminate(info);
          *result = trio_string_extract(info);
        }
      trio_string_destroy(info);
    }
  return status;
}
#endif /* TRIO_FEATURE_DYNAMICSTRING */

/** @} End of Printf documentation module */

/*************************************************************************
 *
 * CALLBACK
 *
 ************************************************************************/

#if defined(TRIO_DOCUMENTATION)
# include "doc/doc_register.h"
#endif
/**
   @addtogroup UserDefined
   @{
*/

#if TRIO_FEATURE_USER_DEFINED

/*************************************************************************
 * trio_register
 */

/**
   Register new user-defined specifier.

   @param callback
   @param name
   @return Handle.
 */
TRIO_PUBLIC trio_pointer_t 
trio_register
TRIO_ARGS2((callback, name),
	   trio_callback_t callback,
	   TRIO_CONST char *name)
{
  trio_userdef_t *def;
  trio_userdef_t *prev = NULL;

  if (callback == NULL)
    return NULL;

  if (name)
    {
      /* Handle built-in namespaces */
      if (name[0] == ':')
	{
	  if (trio_equal(name, ":enter"))
	    {
	      internalEnterCriticalRegion = callback;
	    }
	  else if (trio_equal(name, ":leave"))
	    {
	      internalLeaveCriticalRegion = callback;
	    }
	  return NULL;
	}
      
      /* Bail out if namespace is too long */
      if (trio_length(name) >= MAX_USER_NAME)
	return NULL;
      
      /* Bail out if namespace already is registered */
      def = TrioFindNamespace(name, &prev);
      if (def)
	return NULL;
    }
  
  def = (trio_userdef_t *)TRIO_MALLOC(sizeof(trio_userdef_t));
  if (def)
    {
      if (internalEnterCriticalRegion)
	(void)internalEnterCriticalRegion(NULL);
      
      if (name)
	{
	  /* Link into internal list */
	  if (prev == NULL)
	    internalUserDef = def;
	  else
	    prev->next = def;
	}
      /* Initialize */
      def->callback = callback;
      def->name = (name == NULL)
	? NULL
	: trio_duplicate(name);
      def->next = NULL;

      if (internalLeaveCriticalRegion)
	(void)internalLeaveCriticalRegion(NULL);
    }
  return (trio_pointer_t)def;
}

/**
   Unregister an existing user-defined specifier.

   @param handle
 */
void
trio_unregister
TRIO_ARGS1((handle),
	   trio_pointer_t handle)
{
  trio_userdef_t *self = (trio_userdef_t *)handle;
  trio_userdef_t *def;
  trio_userdef_t *prev = NULL;

  assert(VALID(self));

  if (self->name)
    {
      def = TrioFindNamespace(self->name, &prev);
      if (def)
	{
	  if (internalEnterCriticalRegion)
	    (void)internalEnterCriticalRegion(NULL);
	  
	  if (prev == NULL)
	    internalUserDef = internalUserDef->next;
	  else
	    prev->next = def->next;
	  
	  if (internalLeaveCriticalRegion)
	    (void)internalLeaveCriticalRegion(NULL);
	}
      trio_destroy(self->name);
    }
  TRIO_FREE(self);
}

/*************************************************************************
 * trio_get_format [public]
 */
TRIO_CONST char *
trio_get_format
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
#if TRIO_FEATURE_USER_DEFINED
  assert(((trio_reference_t *)ref)->parameter->type == FORMAT_USER_DEFINED);
#endif
  
  return (((trio_reference_t *)ref)->parameter->user_data);
}

/*************************************************************************
 * trio_get_argument [public]
 */
TRIO_CONST trio_pointer_t
trio_get_argument
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
#if TRIO_FEATURE_USER_DEFINED
  assert(((trio_reference_t *)ref)->parameter->type == FORMAT_USER_DEFINED);
#endif

  return ((trio_reference_t *)ref)->parameter->data.pointer;
}

/*************************************************************************
 * trio_get_width / trio_set_width [public]
 */
int
trio_get_width
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return ((trio_reference_t *)ref)->parameter->width;
}

void
trio_set_width
TRIO_ARGS2((ref, width),
	   trio_pointer_t ref,
	   int width)
{
  ((trio_reference_t *)ref)->parameter->width = width;
}

/*************************************************************************
 * trio_get_precision / trio_set_precision [public]
 */
int
trio_get_precision
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->precision);
}

void
trio_set_precision
TRIO_ARGS2((ref, precision),
	   trio_pointer_t ref,
	   int precision)
{
  ((trio_reference_t *)ref)->parameter->precision = precision;
}

/*************************************************************************
 * trio_get_base / trio_set_base [public]
 */
int
trio_get_base
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->base);
}

void
trio_set_base
TRIO_ARGS2((ref, base),
	   trio_pointer_t ref,
	   int base)
{
  ((trio_reference_t *)ref)->parameter->base = base;
}

/*************************************************************************
 * trio_get_long / trio_set_long [public]
 */
int
trio_get_long
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_LONG)
    ? TRUE
    : FALSE;
}

void
trio_set_long
TRIO_ARGS2((ref, is_long),
	   trio_pointer_t ref,
	   int is_long)
{
  if (is_long)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_LONG;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_LONG;
}

/*************************************************************************
 * trio_get_longlong / trio_set_longlong [public]
 */
int
trio_get_longlong
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_QUAD)
    ? TRUE
    : FALSE;
}

void
trio_set_longlong
TRIO_ARGS2((ref, is_longlong),
	   trio_pointer_t ref,
	   int is_longlong)
{
  if (is_longlong)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_QUAD;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_QUAD;
}

/*************************************************************************
 * trio_get_longdouble / trio_set_longdouble [public]
 */
# if TRIO_FEATURE_FLOAT
int
trio_get_longdouble
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_LONGDOUBLE)
    ? TRUE
    : FALSE;
}

void
trio_set_longdouble
TRIO_ARGS2((ref, is_longdouble),
	   trio_pointer_t ref,
	   int is_longdouble)
{
  if (is_longdouble)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_LONGDOUBLE;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_LONGDOUBLE;
}
# endif /* TRIO_FEATURE_FLOAT */

/*************************************************************************
 * trio_get_short / trio_set_short [public]
 */
int
trio_get_short
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_SHORT)
    ? TRUE
    : FALSE;
}

void
trio_set_short
TRIO_ARGS2((ref, is_short),
	   trio_pointer_t ref,
	   int is_short)
{
  if (is_short)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_SHORT;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_SHORT;
}

/*************************************************************************
 * trio_get_shortshort / trio_set_shortshort [public]
 */
int
trio_get_shortshort
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_SHORTSHORT)
    ? TRUE
    : FALSE;
}

void
trio_set_shortshort
TRIO_ARGS2((ref, is_shortshort),
	   trio_pointer_t ref,
	   int is_shortshort)
{
  if (is_shortshort)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_SHORTSHORT;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_SHORTSHORT;
}

/*************************************************************************
 * trio_get_alternative / trio_set_alternative [public]
 */
int
trio_get_alternative
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_ALTERNATIVE)
    ? TRUE
    : FALSE;
}

void
trio_set_alternative
TRIO_ARGS2((ref, is_alternative),
	   trio_pointer_t ref,
	   int is_alternative)
{
  if (is_alternative)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_ALTERNATIVE;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_ALTERNATIVE;
}

/*************************************************************************
 * trio_get_alignment / trio_set_alignment [public]
 */
int
trio_get_alignment
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_LEFTADJUST)
    ? TRUE
    : FALSE;
}

void
trio_set_alignment
TRIO_ARGS2((ref, is_leftaligned),
	   trio_pointer_t ref,
	   int is_leftaligned)
{
  if (is_leftaligned)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_LEFTADJUST;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_LEFTADJUST;
}

/*************************************************************************
 * trio_get_spacing /trio_set_spacing [public]
 */
int
trio_get_spacing
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_SPACE)
    ? TRUE
    : FALSE;
}

void
trio_set_spacing
TRIO_ARGS2((ref, is_space),
	   trio_pointer_t ref,
	   int is_space)
{
  if (is_space)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_SPACE;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_SPACE;
}

/*************************************************************************
 * trio_get_sign / trio_set_sign [public]
 */
int
trio_get_sign
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_SHOWSIGN)
    ? TRUE
    : FALSE;
}

void
trio_set_sign
TRIO_ARGS2((ref, is_sign),
	   trio_pointer_t ref,
	   int is_sign)
{
  if (is_sign)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_SHOWSIGN;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_SHOWSIGN;
}

/*************************************************************************
 * trio_get_padding / trio_set_padding [public]
 */
int
trio_get_padding
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_NILPADDING)
    ? TRUE
    : FALSE;
}

void
trio_set_padding
TRIO_ARGS2((ref, is_padding),
	   trio_pointer_t ref,
	   int is_padding)
{
  if (is_padding)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_NILPADDING;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_NILPADDING;
}

/*************************************************************************
 * trio_get_quote / trio_set_quote [public]
 */
# if TRIO_FEATURE_QUOTE
int
trio_get_quote
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_QUOTE)
    ? TRUE
    : FALSE;
}

void
trio_set_quote
TRIO_ARGS2((ref, is_quote),
	   trio_pointer_t ref,
	   int is_quote)
{
  if (is_quote)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_QUOTE;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_QUOTE;
}
#endif /* TRIO_FEATURE_QUOTE */

/*************************************************************************
 * trio_get_upper / trio_set_upper [public]
 */
int
trio_get_upper
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_UPPER)
    ? TRUE
    : FALSE;
}

void
trio_set_upper
TRIO_ARGS2((ref, is_upper),
	   trio_pointer_t ref,
	   int is_upper)
{
  if (is_upper)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_UPPER;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_UPPER;
}

/*************************************************************************
 * trio_get_largest / trio_set_largest [public]
 */
#if TRIO_FEATURE_INTMAX_T
int
trio_get_largest
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_INTMAX_T)
    ? TRUE
    : FALSE;
}

void
trio_set_largest
TRIO_ARGS2((ref, is_largest),
	   trio_pointer_t ref,
	   int is_largest)
{
  if (is_largest)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_INTMAX_T;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_INTMAX_T;
}
#endif /* TRIO_FEATURE_INTMAX_T */

/*************************************************************************
 * trio_get_ptrdiff / trio_set_ptrdiff [public]
 */
#if TRIO_FEATURE_PTRDIFF_T
int
trio_get_ptrdiff
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_PTRDIFF_T)
    ? TRUE
    : FALSE;
}

void
trio_set_ptrdiff
TRIO_ARGS2((ref, is_ptrdiff),
	   trio_pointer_t ref,
	   int is_ptrdiff)
{
  if (is_ptrdiff)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_PTRDIFF_T;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_PTRDIFF_T;
}
#endif /* TRIO_FEATURE_PTRDIFF_T */

/*************************************************************************
 * trio_get_size / trio_set_size [public]
 */
#if TRIO_FEATURE_SIZE_T
int
trio_get_size
TRIO_ARGS1((ref),
	   trio_pointer_t ref)
{
  return (((trio_reference_t *)ref)->parameter->flags & FLAGS_SIZE_T)
    ? TRUE
    : FALSE;
}

void
trio_set_size
TRIO_ARGS2((ref, is_size),
	   trio_pointer_t ref,
	   int is_size)
{
  if (is_size)
    ((trio_reference_t *)ref)->parameter->flags |= FLAGS_SIZE_T;
  else
    ((trio_reference_t *)ref)->parameter->flags &= ~FLAGS_SIZE_T;
}
#endif /* TRIO_FEATURE_SIZE_T */

/*************************************************************************
 * trio_print_int [public]
 */
void
trio_print_int
TRIO_ARGS2((ref, number),
	   trio_pointer_t ref,
	   int number)
{
  trio_reference_t *self = (trio_reference_t *)ref;

  TrioWriteNumber(self->data,
		  (trio_uintmax_t)number,
		  self->parameter->flags,
		  self->parameter->width,
		  self->parameter->precision,
		  self->parameter->base);
}

/*************************************************************************
 * trio_print_uint [public]
 */
void
trio_print_uint
TRIO_ARGS2((ref, number),
	   trio_pointer_t ref,
	   unsigned int number)
{
  trio_reference_t *self = (trio_reference_t *)ref;

  TrioWriteNumber(self->data,
		  (trio_uintmax_t)number,
		  self->parameter->flags | FLAGS_UNSIGNED,
		  self->parameter->width,
		  self->parameter->precision,
		  self->parameter->base);
}

/*************************************************************************
 * trio_print_double [public]
 */
#if TRIO_FEATURE_FLOAT
void
trio_print_double
TRIO_ARGS2((ref, number),
	   trio_pointer_t ref,
	   double number)
{
  trio_reference_t *self = (trio_reference_t *)ref;

  TrioWriteDouble(self->data,
		  number,
		  self->parameter->flags,
		  self->parameter->width,
		  self->parameter->precision,
		  self->parameter->base);
}
#endif /* TRIO_FEATURE_FLOAT */

/*************************************************************************
 * trio_print_string [public]
 */
void
trio_print_string
TRIO_ARGS2((ref, string),
	   trio_pointer_t ref,
	   TRIO_CONST char *string)
{
  trio_reference_t *self = (trio_reference_t *)ref;

  TrioWriteString(self->data,
		  string,
		  self->parameter->flags,
		  self->parameter->width,
		  self->parameter->precision);
}

/*************************************************************************
 * trio_print_ref [public]
 */
int
trio_print_ref
TRIO_VARGS3((ref, format, va_alist),
	    trio_pointer_t ref,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list arglist;

  assert(VALID(format));
  
  TRIO_VA_START(arglist, format);
  status = TrioFormatRef((trio_reference_t *)ref, format, arglist, NULL);
  TRIO_VA_END(arglist);
  return status;
}

/*************************************************************************
 * trio_vprint_ref [public]
 */
int
trio_vprint_ref
TRIO_ARGS3((ref, format, arglist),
	   trio_pointer_t ref,
	   TRIO_CONST char *format,
	   va_list arglist)
{
  assert(VALID(format));
  
  return TrioFormatRef((trio_reference_t *)ref, format, arglist, NULL);
}

/*************************************************************************
 * trio_printv_ref [public]
 */
int
trio_printv_ref
TRIO_ARGS3((ref, format, argarray),
	   trio_pointer_t ref,
	   TRIO_CONST char *format,
	   trio_pointer_t *argarray)
{
  static va_list unused;
  
  assert(VALID(format));
  
  return TrioFormatRef((trio_reference_t *)ref, format, unused, argarray);
}

#endif

/*************************************************************************
 * trio_print_pointer [public]
 */
void
trio_print_pointer
TRIO_ARGS2((ref, pointer),
	   trio_pointer_t ref,
	   trio_pointer_t pointer)
{
  trio_reference_t *self = (trio_reference_t *)ref;
  trio_flags_t flags;
  trio_uintmax_t number;

  if (NULL == pointer)
    {
      TRIO_CONST char *string = internalNullString;
      while (*string)
	self->data->OutStream(self->data, *string++);
    }
  else
    {
      /*
       * The subtraction of the null pointer is a workaround
       * to avoid a compiler warning. The performance overhead
       * is negligible (and likely to be removed by an
       * optimizing compiler). The (char *) casting is done
       * to please ANSI C++.
       */
      number = (trio_uintmax_t)((char *)pointer - (char *)0);
      /* Shrink to size of pointer */
      number &= (trio_uintmax_t)-1;
      flags = self->parameter->flags;
      flags |= (FLAGS_UNSIGNED | FLAGS_ALTERNATIVE |
	        FLAGS_NILPADDING);
      TrioWriteNumber(self->data,
		      number,
		      flags,
		      POINTER_WIDTH,
		      NO_PRECISION,
		      BASE_HEX);
    }
}

/** @} End of UserDefined documentation module */

/*************************************************************************
 *
 * LOCALES
 *
 ************************************************************************/

/*************************************************************************
 * trio_locale_set_decimal_point
 *
 * Decimal point can only be one character. The input argument is a
 * string to enable multibyte characters. At most MB_LEN_MAX characters
 * will be used.
 */
#if TRIO_FEATURE_LOCALE
TRIO_PUBLIC void
trio_locale_set_decimal_point
TRIO_ARGS1((decimalPoint),
	   char *decimalPoint)
{
#if defined(USE_LOCALE)
  if (NULL == internalLocaleValues)
    {
      TrioSetLocale();
    }
#endif
  internalDecimalPointLength = trio_length(decimalPoint);
  if (internalDecimalPointLength == 1)
    {
      internalDecimalPoint = *decimalPoint;
    }
  else
    {
      internalDecimalPoint = NIL;
      trio_copy_max(internalDecimalPointString,
		    sizeof(internalDecimalPointString),
		    decimalPoint);
    }
}
#endif

/*************************************************************************
 * trio_locale_set_thousand_separator
 *
 * See trio_locale_set_decimal_point
 */
#if TRIO_FEATURE_LOCALE || TRIO_EXTENSION
TRIO_PUBLIC void
trio_locale_set_thousand_separator
TRIO_ARGS1((thousandSeparator),
	   char *thousandSeparator)
{
# if defined(USE_LOCALE)
  if (NULL == internalLocaleValues)
    {
      TrioSetLocale();
    }
# endif
  trio_copy_max(internalThousandSeparator,
		sizeof(internalThousandSeparator),
		thousandSeparator);
  internalThousandSeparatorLength = trio_length(internalThousandSeparator);
}
#endif

/*************************************************************************
 * trio_locale_set_grouping
 *
 * Array of bytes. Reversed order.
 *
 *  CHAR_MAX : No further grouping
 *  0        : Repeat last group for the remaining digits (not necessary
 *             as C strings are zero-terminated)
 *  n        : Set current group to n
 *
 * Same order as the grouping attribute in LC_NUMERIC.
 */
#if TRIO_FEATURE_LOCALE || TRIO_EXTENSION
TRIO_PUBLIC void
trio_locale_set_grouping
TRIO_ARGS1((grouping),
	   char *grouping)
{
# if defined(USE_LOCALE)
  if (NULL == internalLocaleValues)
    {
      TrioSetLocale();
    }
# endif
  trio_copy_max(internalGrouping,
		sizeof(internalGrouping),
		grouping);
}
#endif


/*************************************************************************
 *
 * SCANNING
 *
 ************************************************************************/

#if TRIO_FEATURE_SCANF

/*************************************************************************
 * TrioSkipWhitespaces
 */
TRIO_PRIVATE int
TrioSkipWhitespaces
TRIO_ARGS1((self),
	   trio_class_t *self)
{
  int ch;

  ch = self->current;
  while (isspace(ch))
    {
      self->InStream(self, &ch);
    }
  return ch;
}

/*************************************************************************
 * TrioGetCollation
 */
#if TRIO_EXTENSION
TRIO_PRIVATE void
TrioGetCollation(TRIO_NOARGS)
{
  int i;
  int j;
  int k;
  char first[2];
  char second[2];

  /* This is computationally expensive */
  first[1] = NIL;
  second[1] = NIL;
  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
    {
      k = 0;
      first[0] = (char)i;
      for (j = 0; j < MAX_CHARACTER_CLASS; j++)
	{
	  second[0] = (char)j;
	  if (trio_equal_locale(first, second))
	    internalCollationArray[i][k++] = (char)j;
	}
      internalCollationArray[i][k] = NIL;
    }
}
#endif

/*************************************************************************
 * TrioGetCharacterClass
 *
 * FIXME:
 *  multibyte
 */
TRIO_PRIVATE int
TrioGetCharacterClass
TRIO_ARGS4((format, offsetPointer, flagsPointer, characterclass),
	   TRIO_CONST char *format,
	   int *offsetPointer,
	   trio_flags_t *flagsPointer,
	   int *characterclass)
{
  int offset = *offsetPointer;
  int i;
  char ch;
  char range_begin;
  char range_end;

  *flagsPointer &= ~FLAGS_EXCLUDE;

  if (format[offset] == QUALIFIER_CIRCUMFLEX)
    {
      *flagsPointer |= FLAGS_EXCLUDE;
      offset++;
    }
  /*
   * If the ungroup character is at the beginning of the scanlist,
   * it will be part of the class, and a second ungroup character
   * must follow to end the group.
   */
  if (format[offset] == SPECIFIER_UNGROUP)
    {
      characterclass[(int)SPECIFIER_UNGROUP]++;
      offset++;
    }
  /*
   * Minus is used to specify ranges. To include minus in the class,
   * it must be at the beginning of the list
   */
  if (format[offset] == QUALIFIER_MINUS)
    {
      characterclass[(int)QUALIFIER_MINUS]++;
      offset++;
    }
  /* Collect characters */
  for (ch = format[offset];
       (ch != SPECIFIER_UNGROUP) && (ch != NIL);
       ch = format[++offset])
    {
      switch (ch)
	{
	case QUALIFIER_MINUS: /* Scanlist ranges */
	  
	  /*
	   * Both C99 and UNIX98 describes ranges as implementation-
	   * defined.
	   *
	   * We support the following behaviour (although this may
	   * change as we become wiser)
	   * - only increasing ranges, ie. [a-b] but not [b-a]
	   * - transitive ranges, ie. [a-b-c] == [a-c]
	   * - trailing minus, ie. [a-] is interpreted as an 'a'
	   *   and a '-'
	   * - duplicates (although we can easily convert these
	   *   into errors)
	   */
	  range_begin = format[offset - 1];
	  range_end = format[++offset];
	  if (range_end == SPECIFIER_UNGROUP)
	    {
	      /* Trailing minus is included */
	      characterclass[(int)ch]++;
	      ch = range_end;
	      break; /* for */
	    }
	  if (range_end == NIL)
	    return TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
	  if (range_begin > range_end)
	    return TRIO_ERROR_RETURN(TRIO_ERANGE, offset);
	    
	  for (i = (int)range_begin; i <= (int)range_end; i++)
	    characterclass[i]++;
	    
	  ch = range_end;
	  break;
	  
#if TRIO_EXTENSION

	case SPECIFIER_GROUP:
	  
	  switch (format[offset + 1])
	    {
	    case QUALIFIER_DOT: /* Collating symbol */
	      /*
	       * FIXME: This will be easier to implement when multibyte
	       * characters have been implemented. Until now, we ignore
	       * this feature.
	       */
	      for (i = offset + 2; ; i++)
		{
		  if (format[i] == NIL)
		    /* Error in syntax */
		    return -1;
		  else if (format[i] == QUALIFIER_DOT)
		    break; /* for */
		}
	      if (format[++i] != SPECIFIER_UNGROUP)
		return -1;
	      
	      offset = i;
	      break;
	  
	    case QUALIFIER_EQUAL: /* Equivalence class expressions */
	      {
		unsigned int j;
		unsigned int k;
	    
		if (internalCollationUnconverted)
		  {
		    /* Lazy evaluation of collation array */
		    TrioGetCollation();
		    internalCollationUnconverted = FALSE;
		  }
		for (i = offset + 2; ; i++)
		  {
		    if (format[i] == NIL)
		      /* Error in syntax */
		      return -1;
		    else if (format[i] == QUALIFIER_EQUAL)
		      break; /* for */
		    else
		      {
			/* Mark any equivalent character */
			k = (unsigned int)format[i];
			for (j = 0; internalCollationArray[k][j] != NIL; j++)
			  characterclass[(int)internalCollationArray[k][j]]++;
		      }
		  }
		if (format[++i] != SPECIFIER_UNGROUP)
		  return -1;
		
		offset = i;
	      }
	      break;
	  
	    case QUALIFIER_COLON: /* Character class expressions */
	  
	      if (trio_equal_max(CLASS_ALNUM, sizeof(CLASS_ALNUM) - 1,
				 &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (isalnum(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_ALNUM) - 1;
		}
	      else if (trio_equal_max(CLASS_ALPHA, sizeof(CLASS_ALPHA) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (isalpha(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_ALPHA) - 1;
		}
	      else if (trio_equal_max(CLASS_CNTRL, sizeof(CLASS_CNTRL) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (iscntrl(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_CNTRL) - 1;
		}
	      else if (trio_equal_max(CLASS_DIGIT, sizeof(CLASS_DIGIT) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (isdigit(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_DIGIT) - 1;
		}
	      else if (trio_equal_max(CLASS_GRAPH, sizeof(CLASS_GRAPH) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (isgraph(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_GRAPH) - 1;
		}
	      else if (trio_equal_max(CLASS_LOWER, sizeof(CLASS_LOWER) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (islower(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_LOWER) - 1;
		}
	      else if (trio_equal_max(CLASS_PRINT, sizeof(CLASS_PRINT) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (isprint(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_PRINT) - 1;
		}
	      else if (trio_equal_max(CLASS_PUNCT, sizeof(CLASS_PUNCT) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (ispunct(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_PUNCT) - 1;
		}
	      else if (trio_equal_max(CLASS_SPACE, sizeof(CLASS_SPACE) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (isspace(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_SPACE) - 1;
		}
	      else if (trio_equal_max(CLASS_UPPER, sizeof(CLASS_UPPER) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (isupper(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_UPPER) - 1;
		}
	      else if (trio_equal_max(CLASS_XDIGIT, sizeof(CLASS_XDIGIT) - 1,
				      &format[offset]))
		{
		  for (i = 0; i < MAX_CHARACTER_CLASS; i++)
		    if (isxdigit(i))
		      characterclass[i]++;
		  offset += sizeof(CLASS_XDIGIT) - 1;
		}
	      else
		{
		  characterclass[(int)ch]++;
		}
	      break;

	    default:
	      characterclass[(int)ch]++;
	      break;
	    }
	  break;
	  
#endif /* TRIO_EXTENSION */
	  
	default:
	  characterclass[(int)ch]++;
	  break;
	}
    }
  return 0;
}

/*************************************************************************
 * TrioReadNumber
 *
 * We implement our own number conversion in preference of strtol and
 * strtoul, because we must handle 'long long' and thousand separators.
 */
TRIO_PRIVATE BOOLEAN_T
TrioReadNumber
TRIO_ARGS5((self, target, flags, width, base),
	   trio_class_t *self,
	   trio_uintmax_t *target,
	   trio_flags_t flags,
	   int width,
	   int base)
{
  trio_uintmax_t number = 0;
  int digit;
  int count;
  BOOLEAN_T isNegative = FALSE;
  BOOLEAN_T gotNumber = FALSE;
  int j;

  assert(VALID(self));
  assert(VALID(self->InStream));
  assert((base >= MIN_BASE && base <= MAX_BASE) || (base == NO_BASE));

  if (internalDigitsUnconverted)
    {
      /* Lazy evaluation of digits array */
      memset(internalDigitArray, -1, sizeof(internalDigitArray));
      for (j = 0; j < (int)sizeof(internalDigitsLower) - 1; j++)
	{
	  internalDigitArray[(int)internalDigitsLower[j]] = j;
	  internalDigitArray[(int)internalDigitsUpper[j]] = j;
	}
      internalDigitsUnconverted = FALSE;
    }
  
  TrioSkipWhitespaces(self);
  
  /* Leading sign */
  if (self->current == '+')
    {
      self->InStream(self, NULL);
    }
  else if (self->current == '-')
    {
      self->InStream(self, NULL);
      isNegative = TRUE;
    }
  
  count = self->processed;
  
  if (flags & FLAGS_ALTERNATIVE)
    {
      switch (base)
	{
	case NO_BASE:
	case BASE_OCTAL:
	case BASE_HEX:
	case BASE_BINARY:
	  if (self->current == '0')
	    {
	      self->InStream(self, NULL);
	      if (self->current)
		{
		  if ((base == BASE_HEX) &&
		      (trio_to_upper(self->current) == 'X'))
		    {
		      self->InStream(self, NULL);
		    }
		  else if ((base == BASE_BINARY) &&
			   (trio_to_upper(self->current) == 'B'))
		    {
		      self->InStream(self, NULL);
		    }
		}
	    }
	  else
	    return FALSE;
	  break;
	default:
	  break;
	}
    }

  while (((width == NO_WIDTH) || (self->processed - count < width)) &&
	 (! ((self->current == EOF) || isspace(self->current))))
    {
      if (isascii(self->current))
	{
	  digit = internalDigitArray[self->current];
	  /* Abort if digit is not allowed in the specified base */
	  if ((digit == -1) || (digit >= base))
	    break;
	}
#if TRIO_FEATURE_QUOTE
      else if (flags & FLAGS_QUOTE)
	{
	  /* Compare with thousands separator */
	  for (j = 0; internalThousandSeparator[j] && self->current; j++)
	    {
	      if (internalThousandSeparator[j] != self->current)
		break;

	      self->InStream(self, NULL);
	    }
	  if (internalThousandSeparator[j])
	    break; /* Mismatch */
	  else
	    continue; /* Match */
	}
#endif
      else
	break;
            
      number *= base;
      number += digit;
      gotNumber = TRUE; /* we need at least one digit */

      self->InStream(self, NULL);
    }

  /* Was anything read at all? */
  if (!gotNumber)
    return FALSE;
  
  if (target)
    *target = (isNegative) ? (trio_uintmax_t)(-((trio_intmax_t)number)) : number;
  return TRUE;
}

/*************************************************************************
 * TrioReadChar
 */
TRIO_PRIVATE int
TrioReadChar
TRIO_ARGS4((self, target, flags, width),
	   trio_class_t *self,
	   char *target,
	   trio_flags_t flags,
	   int width)
{
  int i;
  char ch;
  trio_uintmax_t number;
  
  assert(VALID(self));
  assert(VALID(self->InStream));

  for (i = 0;
       (self->current != EOF) && (i < width);
       i++)
    {
      ch = (char)self->current;
      self->InStream(self, NULL);
      if ((flags & FLAGS_ALTERNATIVE) && (ch == CHAR_BACKSLASH))
	{
	  switch (self->current)
	    {
	    case '\\': ch = '\\'; break;
	    case 'a': ch = '\007'; break;
	    case 'b': ch = '\b'; break;
	    case 'f': ch = '\f'; break;
	    case 'n': ch = '\n'; break;
	    case 'r': ch = '\r'; break;
	    case 't': ch = '\t'; break;
	    case 'v': ch = '\v'; break;
	    default:
	      if (isdigit(self->current))
		{
		  /* Read octal number */
		  if (!TrioReadNumber(self, &number, 0, 3, BASE_OCTAL))
		    return 0;
		  ch = (char)number;
		}
	      else if (trio_to_upper(self->current) == 'X')
		{
		  /* Read hexadecimal number */
		  self->InStream(self, NULL);
		  if (!TrioReadNumber(self, &number, 0, 2, BASE_HEX))
		    return 0;
		  ch = (char)number;
		}
	      else
		{
		  ch = (char)self->current;
		}
	      break;
	    }
	}
      
      if (target)
	target[i] = ch;
    }
  return i + 1;
}

/*************************************************************************
 * TrioReadString
 */
TRIO_PRIVATE BOOLEAN_T
TrioReadString
TRIO_ARGS4((self, target, flags, width),
	   trio_class_t *self,
	   char *target,
	   trio_flags_t flags,
	   int width)
{
  int i;
  
  assert(VALID(self));
  assert(VALID(self->InStream));

  TrioSkipWhitespaces(self);
    
  /*
   * Continue until end of string is reached, a whitespace is encountered,
   * or width is exceeded
   */
  for (i = 0;
       ((width == NO_WIDTH) || (i < width)) &&
       (! ((self->current == EOF) || isspace(self->current)));
       i++)
    {
      if (TrioReadChar(self, (target ? &target[i] : 0), flags, 1) == 0)
	break; /* for */
    }
  if (target)
    target[i] = NIL;
  return TRUE;
}

/*************************************************************************
 * TrioReadWideChar
 */
#if TRIO_FEATURE_WIDECHAR
TRIO_PRIVATE int
TrioReadWideChar
TRIO_ARGS4((self, target, flags, width),
	   trio_class_t *self,
	   trio_wchar_t *target,
	   trio_flags_t flags,
	   int width)
{
  int i;
  int j;
  int size;
  int amount = 0;
  trio_wchar_t wch;
  char buffer[MB_LEN_MAX + 1];
  
  assert(VALID(self));
  assert(VALID(self->InStream));

  for (i = 0;
       (self->current != EOF) && (i < width);
       i++)
    {
      if (isascii(self->current))
	{
	  if (TrioReadChar(self, buffer, flags, 1) == 0)
	    return 0;
	  buffer[1] = NIL;
	}
      else
	{
	  /*
	   * Collect a multibyte character, by enlarging buffer until
	   * it contains a fully legal multibyte character, or the
	   * buffer is full.
	   */
	  j = 0;
	  do
	    {
	      buffer[j++] = (char)self->current;
	      buffer[j] = NIL;
	      self->InStream(self, NULL);
	    }
	  while ((j < (int)sizeof(buffer)) && (mblen(buffer, (size_t)j) != j));
	}
      if (target)
	{
	  size = mbtowc(&wch, buffer, sizeof(buffer));
	  if (size > 0)
	    target[i] = wch;
	}
      amount += size;
      self->InStream(self, NULL);
    }
  return amount;
}
#endif /* TRIO_FEATURE_WIDECHAR */

/*************************************************************************
 * TrioReadWideString
 */
#if TRIO_FEATURE_WIDECHAR
TRIO_PRIVATE BOOLEAN_T
TrioReadWideString
TRIO_ARGS4((self, target, flags, width),
	   trio_class_t *self,
	   trio_wchar_t *target,
	   trio_flags_t flags,
	   int width)
{
  int i;
  int size;
  
  assert(VALID(self));
  assert(VALID(self->InStream));

  TrioSkipWhitespaces(self);

#if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE)
  /* Required by TrioReadWideChar */
  (void)mblen(NULL, 0);
#endif
  
  /*
   * Continue until end of string is reached, a whitespace is encountered,
   * or width is exceeded
   */
  for (i = 0;
       ((width == NO_WIDTH) || (i < width)) &&
       (! ((self->current == EOF) || isspace(self->current)));
       )
    {
      size = TrioReadWideChar(self, &target[i], flags, 1);
      if (size == 0)
	break; /* for */

      i += size;
    }
  if (target)
    target[i] = WCONST('\0');
  return TRUE;
}
#endif /* TRIO_FEATURE_WIDECHAR */

/*************************************************************************
 * TrioReadGroup
 *
 * Reads non-empty character groups.
 *
 * FIXME: characterclass does not work with multibyte characters
 */
TRIO_PRIVATE BOOLEAN_T
TrioReadGroup
TRIO_ARGS5((self, target, characterclass, flags, width),
	   trio_class_t *self,
	   char *target,
	   int *characterclass,
	   trio_flags_t flags,
	   int width)
{
  int ch;
  int i;
  
  assert(VALID(self));
  assert(VALID(self->InStream));

  ch = self->current;
  for (i = 0;
       ((width == NO_WIDTH) || (i < width)) &&
       (! ((ch == EOF) ||
	   (((flags & FLAGS_EXCLUDE) != 0) ^ (characterclass[ch] == 0))));
       i++)
    {
      if (target)
	target[i] = (char)ch;
      self->InStream(self, &ch);
    }

  if (i == 0)
    return FALSE;

  /* Terminate the string if input saved */
  if (target)
    target[i] = NIL;
  return TRUE;
}

/*************************************************************************
 * TrioReadDouble
 *
 * FIXME:
 *  add long double
 *  handle base
 */
#if TRIO_FEATURE_FLOAT
TRIO_PRIVATE BOOLEAN_T
TrioReadDouble
TRIO_ARGS4((self, target, flags, width),
	   trio_class_t *self,
	   trio_pointer_t target,
	   trio_flags_t flags,
	   int width)
{
  int ch;
  char doubleString[512];
  int offset = 0;
  int start;
# if TRIO_FEATURE_QUOTE
  int j;
# endif
  BOOLEAN_T isHex = FALSE;
  trio_long_double_t infinity;

  doubleString[0] = 0;
  
  if ((width == NO_WIDTH) || (width > (int)sizeof(doubleString) - 1))
    width = sizeof(doubleString) - 1;
  
  TrioSkipWhitespaces(self);
  
  /*
   * Read entire double number from stream. trio_to_double requires
   * a string as input, but InStream can be anything, so we have to
   * collect all characters.
   */
  ch = self->current;
  if ((ch == '+') || (ch == '-'))
    {
      doubleString[offset++] = (char)ch;
      self->InStream(self, &ch);
      width--;
    }

  start = offset;
  switch (ch)
    {
    case 'n':
    case 'N':
      /* Not-a-number */
      if (offset != 0)
	break;
      /* FALLTHROUGH */
    case 'i':
    case 'I':
      /* Infinity */
      while (isalpha(ch) && (offset - start < width))
	{
	  doubleString[offset++] = (char)ch;
	  self->InStream(self, &ch);
	}
      doubleString[offset] = NIL;

      /* Case insensitive string comparison */
      if (trio_equal(&doubleString[start], INFINITE_UPPER) ||
	  trio_equal(&doubleString[start], LONG_INFINITE_UPPER))
	{
	  infinity = ((start == 1) && (doubleString[0] == '-'))
	    ? trio_ninf()
	    : trio_pinf();
	  if (flags & FLAGS_LONGDOUBLE)
	    {
	      *((trio_long_double_t *)target) = infinity;
	    }
	  else if (flags & FLAGS_LONG)
	    {
	      *((double *)target) = infinity;
	    }
	  else
	    {
	      *((float *)target) = infinity;
	    }
	  return TRUE;
	}
      if (trio_equal(doubleString, NAN_UPPER))
	{
	  /* NaN must not have a preceeding + nor - */
	  if (flags & FLAGS_LONGDOUBLE)
	    {
	      *((trio_long_double_t *)target) = trio_nan();
	    }
	  else if (flags & FLAGS_LONG)
	    {
	      *((double *)target) = trio_nan();
	    }
	  else
	    {
	      *((float *)target) = trio_nan();
	    }
	  return TRUE;
	}
      return FALSE;

    case '0':
      doubleString[offset++] = (char)ch;
      self->InStream(self, &ch);
      if (trio_to_upper(ch) == 'X')
	{
	  isHex = TRUE;
	  doubleString[offset++] = (char)ch;
	  self->InStream(self, &ch);
	}
      break;
      
    default:
      break;
    }
  
  while ((ch != EOF) && (offset - start < width))
    {
      /* Integer part */
      if (isHex ? isxdigit(ch) : isdigit(ch))
	{
	  doubleString[offset++] = (char)ch;
	  self->InStream(self, &ch);
	}
# if TRIO_FEATURE_QUOTE
      else if (flags & FLAGS_QUOTE)
	{
	  /* Compare with thousands separator */
	  for (j = 0; internalThousandSeparator[j] && self->current; j++)
	    {
	      if (internalThousandSeparator[j] != self->current)
		break;

	      self->InStream(self, &ch);
	    }
	  if (internalThousandSeparator[j])
	    break; /* Mismatch */
	  else
	    continue; /* Match */
	}
# endif
      else
	break; /* while */
    }
  if (ch == '.')
    {
      /* Decimal part */
      doubleString[offset++] = (char)ch;
      self->InStream(self, &ch);
      while ((isHex ? isxdigit(ch) : isdigit(ch)) &&
	     (offset - start < width))
	{
	  doubleString[offset++] = (char)ch;
	  self->InStream(self, &ch);
	}
    }
  if (isHex ? (trio_to_upper(ch) == 'P') : (trio_to_upper(ch) == 'E'))
    {
      /* Exponent */
      doubleString[offset++] = (char)ch;
      self->InStream(self, &ch);
      if ((ch == '+') || (ch == '-'))
	{
	  doubleString[offset++] = (char)ch;
	  self->InStream(self, &ch);
	}
      while (isdigit(ch) && (offset - start < width))
	{
	  doubleString[offset++] = (char)ch;
	  self->InStream(self, &ch);
	}
    }

  if ((offset == start) || (*doubleString == NIL))
    return FALSE;

  doubleString[offset] = 0;
  
  if (flags & FLAGS_LONGDOUBLE)
    {
      *((trio_long_double_t *)target) = trio_to_long_double(doubleString, NULL);
    }
  else if (flags & FLAGS_LONG)
    {
      *((double *)target) = trio_to_double(doubleString, NULL);
    }
  else
    {
      *((float *)target) = trio_to_float(doubleString, NULL);
    }
  return TRUE;
}
#endif /* TRIO_FEATURE_FLOAT */

/*************************************************************************
 * TrioReadPointer
 */
TRIO_PRIVATE BOOLEAN_T
TrioReadPointer
TRIO_ARGS3((self, target, flags),
	   trio_class_t *self,
	   trio_pointer_t *target,
	   trio_flags_t flags)
{
  trio_uintmax_t number;
  char buffer[sizeof(internalNullString)];

  flags |= (FLAGS_UNSIGNED | FLAGS_ALTERNATIVE | FLAGS_NILPADDING);
  
  if (TrioReadNumber(self,
		     &number,
		     flags,
		     POINTER_WIDTH,
		     BASE_HEX))
    {
      if (target)
	{
#if defined(TRIO_COMPILER_GCC) || defined(TRIO_COMPILER_MIPSPRO)
	  /*
	   * The strange assignment of number is a workaround for a compiler
	   * warning
	   */
	  *target = &((char *)0)[number];
#else
	  *target = (trio_pointer_t)number;
#endif
	}
      return TRUE;
    }
  else if (TrioReadString(self,
			  (flags & FLAGS_IGNORE)
			  ? NULL
			  : buffer,
			  0,
			  sizeof(internalNullString) - 1))
    {
      if (trio_equal_case(buffer, internalNullString))
	{
	  if (target)
	    *target = NULL;
	  return TRUE;
	}
    }
  return FALSE;
}

/*************************************************************************
 * TrioScanProcess
 */
TRIO_PRIVATE int
TrioScanProcess
TRIO_ARGS3((data, format, parameters),
	   trio_class_t *data,
	   TRIO_CONST char *format,
	   trio_parameter_t *parameters)
{
  int status;
  int assignment;
  int ch;
  int offset; /* Offset of format string */
  int i; /* Offset of current parameter */
  trio_flags_t flags;
  int width;
  int base;
  trio_pointer_t pointer;

  /* Return on empty format string */
  if (format[0] == NIL)
    return 0;

  status = 0;
  assignment = 0;
  i = 0;
  offset = 0;
  data->InStream(data, &ch);

  for (;;)
    {
      /* Skip the parameter entries */
      while (parameters[i].type == FORMAT_PARAMETER)
	{
	  assert(i <= MAX_PARAMETERS);
	  i++;
	}

      /* Compare non conversion-specifier part of format string */
      while (offset < parameters[i].beginOffset)
	{
	  if ((CHAR_IDENTIFIER == format[offset]) &&
	      (CHAR_IDENTIFIER == format[offset + 1]))
	    {
	      /* Two % in format matches one % in input stream */
	      if (CHAR_IDENTIFIER == ch)
		{
		  data->InStream(data, &ch);
		  offset += 2;
		  continue; /* while format chars left */
		}
	      else
		{
		  status = TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
		  goto end;
		}
	    }
	  else /* Not an % identifier */
	    {
	      if (isspace((int)format[offset]))
		{
		  /* Whitespaces may match any amount of whitespaces */
		  ch = TrioSkipWhitespaces(data);
		}
	      else if (ch == format[offset])
		{
		  data->InStream(data, &ch);
		}
	      else
		{
		  status = assignment;
		  goto end;
		}

	      offset++;
	    }
	}

      if (parameters[i].type == FORMAT_SENTINEL)
	break;

      if ((EOF == ch) && (parameters[i].type != FORMAT_COUNT))
	{
	  status = (assignment > 0) ? assignment : EOF;
	  goto end;
	}

      flags = parameters[i].flags;

      /* Find width */
      width = parameters[i].width;
      if (flags & FLAGS_WIDTH_PARAMETER)
	{
	  /* Get width from parameter list */
	  width = (int)parameters[width].data.number.as_signed;
	}

      /* Find base */
      if (NO_BASE != parameters[i].baseSpecifier)
	{
	  /* Base from specifier has priority */
	  base = parameters[i].baseSpecifier;
	}
      else if (flags & FLAGS_BASE_PARAMETER)
	{
	  /* Get base from parameter list */
	  base = parameters[i].base;
	  base = (int)parameters[base].data.number.as_signed;
	}
      else
	{
	  /* Use base from format string */
	  base = parameters[i].base;
	}

      switch (parameters[i].type)
	{
	case FORMAT_INT:
	  {
	    trio_uintmax_t number;

	    if (0 == base)
	      base = BASE_DECIMAL;

	    if (!TrioReadNumber(data,
				&number,
				flags,
				width,
				base))
	      {
		status = assignment;
		goto end;
	      }

	    if (!(flags & FLAGS_IGNORE))
	      {
		assignment++;

		pointer = parameters[i].data.pointer;
#if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER
		if (flags & FLAGS_SIZE_T)
		  *(size_t *)pointer = (size_t)number;
		else
#endif
#if TRIO_FEATURE_PTRDIFF_T
		if (flags & FLAGS_PTRDIFF_T)
		  *(ptrdiff_t *)pointer = (ptrdiff_t)number;
		else
#endif
#if TRIO_FEATURE_INTMAX_T
		if (flags & FLAGS_INTMAX_T)
		  *(trio_intmax_t *)pointer = (trio_intmax_t)number;
		else
#endif
		if (flags & FLAGS_QUAD)
		  *(trio_ulonglong_t *)pointer = (trio_ulonglong_t)number;
		else if (flags & FLAGS_LONG)
		  *(long int *)pointer = (long int)number;
		else if (flags & FLAGS_SHORT)
		  *(short int *)pointer = (short int)number;
		else
		  *(int *)pointer = (int)number;
	      }
	  }
	  break; /* FORMAT_INT */

	case FORMAT_STRING:
#if TRIO_FEATURE_WIDECHAR
	  if (flags & FLAGS_WIDECHAR)
	    {
	      if (!TrioReadWideString(data,
				      (flags & FLAGS_IGNORE)
				      ? NULL
				      : parameters[i].data.wstring,
				      flags,
				      width))
		{
		  status = assignment;
		  goto end;
		}
	    }
	  else
#endif
	    {
	      if (!TrioReadString(data,
				  (flags & FLAGS_IGNORE)
				  ? NULL
				  : parameters[i].data.string,
				  flags,
				  width))
		{
		  status = assignment;
		  goto end;
		}
	    }
	  if (!(flags & FLAGS_IGNORE))
	    assignment++;
	  break; /* FORMAT_STRING */

#if TRIO_FEATURE_FLOAT
	case FORMAT_DOUBLE:
	  {
	    if (flags & FLAGS_IGNORE)
	      {
		pointer = NULL;
	      }
	    else
	      {
		pointer = (flags & FLAGS_LONGDOUBLE)
		  ? (trio_pointer_t)parameters[i].data.longdoublePointer
		  : (trio_pointer_t)parameters[i].data.doublePointer;
	      }
	    if (!TrioReadDouble(data, pointer, flags, width))
	      {
		status = assignment;
		goto end;
	      }
	    if (!(flags & FLAGS_IGNORE))
	      {
		assignment++;
	      }
	    break; /* FORMAT_DOUBLE */
	  }
#endif

	case FORMAT_GROUP:
	  {
	    int characterclass[MAX_CHARACTER_CLASS + 1];

	    /* Skip over modifiers */
	    while (format[offset] != SPECIFIER_GROUP)
	      {
		offset++;
	      }
	    /* Skip over group specifier */
	    offset++;

	    memset(characterclass, 0, sizeof(characterclass));
	    status = TrioGetCharacterClass(format,
					   &offset,
					   &flags,
					   characterclass);
	    if (status < 0)
	      goto end;

	    if (!TrioReadGroup(data,
			       (flags & FLAGS_IGNORE)
			       ? NULL
			       : parameters[i].data.string,
			       characterclass,
			       flags,
			       parameters[i].width))
	      {
		status = assignment;
		goto end;
	      }
	    if (!(flags & FLAGS_IGNORE))
	      assignment++;
	  }
	  break; /* FORMAT_GROUP */

	case FORMAT_COUNT:
	  pointer = parameters[i].data.pointer;
	  if (NULL != pointer)
	    {
	      int count = data->processed;
	      if (ch != EOF)
		count--; /* a character is read, but is not consumed yet */
#if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER
	      if (flags & FLAGS_SIZE_T)
		*(size_t *)pointer = (size_t)count;
	      else
#endif
#if TRIO_FEATURE_PTRDIFF_T
	      if (flags & FLAGS_PTRDIFF_T)
		*(ptrdiff_t *)pointer = (ptrdiff_t)count;
	      else
#endif
#if TRIO_FEATURE_INTMAX_T
	      if (flags & FLAGS_INTMAX_T)
		*(trio_intmax_t *)pointer = (trio_intmax_t)count;
	      else
#endif
	      if (flags & FLAGS_QUAD)
		{
		  *(trio_ulonglong_t *)pointer = (trio_ulonglong_t)count;
		}
	      else if (flags & FLAGS_LONG)
		{
		  *(long int *)pointer = (long int)count;
		}
	      else if (flags & FLAGS_SHORT)
		{
		  *(short int *)pointer = (short int)count;
		}
	      else
		{
		  *(int *)pointer = (int)count;
		}
	    }
	  break; /* FORMAT_COUNT */

	case FORMAT_CHAR:
#if TRIO_FEATURE_WIDECHAR
	  if (flags & FLAGS_WIDECHAR)
	    {
	      if (TrioReadWideChar(data,
				   (flags & FLAGS_IGNORE)
				   ? NULL
				   : parameters[i].data.wstring,
				   flags,
				   (width == NO_WIDTH) ? 1 : width) == 0)
		{
		  status = assignment;
		  goto end;
		}
	    }
	  else
#endif
	    {
	      if (TrioReadChar(data,
			       (flags & FLAGS_IGNORE)
			       ? NULL
			       : parameters[i].data.string,
			       flags,
			       (width == NO_WIDTH) ? 1 : width) == 0)
		{
		  status = assignment;
		  goto end;
		}
	    }
	  if (!(flags & FLAGS_IGNORE))
	    assignment++;
	  break; /* FORMAT_CHAR */

	case FORMAT_POINTER:
	  if (!TrioReadPointer(data,
			       (flags & FLAGS_IGNORE)
			       ? NULL
			       : (trio_pointer_t *)parameters[i].data.pointer,
			       flags))
	    {
	      status = assignment;
	      goto end;
	    }
	  if (!(flags & FLAGS_IGNORE))
	    assignment++;
	  break; /* FORMAT_POINTER */

	case FORMAT_PARAMETER:
	  break; /* FORMAT_PARAMETER */

	default:
	  status = TRIO_ERROR_RETURN(TRIO_EINVAL, offset);
	  goto end;
	}

      ch = data->current;
      offset = parameters[i].endOffset;
      i++;
    }

  status = assignment;
 end:
  if (data->UndoStream)
    data->UndoStream(data);
  return status;
}

/*************************************************************************
 * TrioScan
 */
TRIO_PRIVATE int
TrioScan
TRIO_ARGS7((source, sourceSize, InStream, UndoStream, format, arglist, argarray),
	   trio_pointer_t source,
	   size_t sourceSize,
	   void (*InStream) TRIO_PROTO((trio_class_t *, int *)),
	   void (*UndoStream) TRIO_PROTO((trio_class_t *)),
	   TRIO_CONST char *format,
	   va_list arglist,
	   trio_pointer_t *argarray)
{
  int status;
  trio_parameter_t parameters[MAX_PARAMETERS];
  trio_class_t data;

  assert(VALID(InStream));
  assert(VALID(format));

  memset(&data, 0, sizeof(data));
  data.InStream = InStream;
  data.UndoStream = UndoStream;
  data.location = (trio_pointer_t)source;
  data.max = sourceSize;
  data.error = 0;

#if defined(USE_LOCALE)
  if (NULL == internalLocaleValues)
    {
      TrioSetLocale();
    }
#endif

  status = TrioParse(TYPE_SCAN, format, parameters, arglist, argarray);
  if (status < 0)
    return status;

  status = TrioScanProcess(&data, format, parameters);
  if (data.error != 0)
    {
      status = data.error;
    }
  return status;
}

/*************************************************************************
 * TrioInStreamFile
 */
#if TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO
TRIO_PRIVATE void
TrioInStreamFile
TRIO_ARGS2((self, intPointer),
	   trio_class_t *self,
	   int *intPointer)
{
  FILE *file = (FILE *)self->location;

  assert(VALID(self));
  assert(VALID(file));

  self->actually.cached = 0;

  /* The initial value of self->current is zero */
  if (self->current == EOF)
    {
      self->error = (ferror(file))
	? TRIO_ERROR_RETURN(TRIO_ERRNO, 0)
	: TRIO_ERROR_RETURN(TRIO_EOF, 0);
    }
  else
    {
      self->processed++;
      self->actually.cached++;
    }

  self->current = fgetc(file);

  if (VALID(intPointer))
    {
      *intPointer = self->current;
    }
}
#endif /* TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO */

/*************************************************************************
 * TrioUndoStreamFile
 */
#if TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO
TRIO_PRIVATE void
TrioUndoStreamFile
TRIO_ARGS1((self),
	   trio_class_t *self)
{
  FILE *file = (FILE *)self->location;

  assert(VALID(self));
  assert(VALID(file));

  if (self->actually.cached > 0)
    {
      assert(self->actually.cached == 1);

      self->current = ungetc(self->current, file);
      self->actually.cached = 0;
    }
}
#endif /* TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO */

/*************************************************************************
 * TrioInStreamFileDescriptor
 */
#if TRIO_FEATURE_FD
TRIO_PRIVATE void
TrioInStreamFileDescriptor
TRIO_ARGS2((self, intPointer),
	   trio_class_t *self,
	   int *intPointer)
{
  int fd = *((int *)self->location);
  int size;
  unsigned char input;

  assert(VALID(self));

  self->actually.cached = 0;

  size = read(fd, &input, sizeof(char));
  if (size == -1)
    {
      self->error = TRIO_ERROR_RETURN(TRIO_ERRNO, 0);
      self->current = EOF;
    }
  else
    {
      self->current = (size == 0) ? EOF : input;
    }
  if (self->current != EOF)
    {
      self->actually.cached++;
      self->processed++;
    }

  if (VALID(intPointer))
    {
      *intPointer = self->current;
    }
}
#endif /* TRIO_FEATURE_FD */

/*************************************************************************
 * TrioInStreamCustom
 */
#if TRIO_FEATURE_CLOSURE
TRIO_PRIVATE void
TrioInStreamCustom
TRIO_ARGS2((self, intPointer),
	   trio_class_t *self,
	   int *intPointer)
{
  trio_custom_t *data;

  assert(VALID(self));
  assert(VALID(self->location));

  self->actually.cached = 0;

  data = (trio_custom_t *)self->location;

  self->current = (data->stream.in == NULL)
    ? NIL
    : (data->stream.in)(data->closure);

  if (self->current == NIL)
    {
      self->current = EOF;
    }
  else
    {
      self->processed++;
      self->actually.cached++;
    }

  if (VALID(intPointer))
    {
      *intPointer = self->current;
    }
}
#endif /* TRIO_FEATURE_CLOSURE */

/*************************************************************************
 * TrioInStreamString
 */
TRIO_PRIVATE void
TrioInStreamString
TRIO_ARGS2((self, intPointer),
	   trio_class_t *self,
	   int *intPointer)
{
  unsigned char **buffer;

  assert(VALID(self));
  assert(VALID(self->location));

  self->actually.cached = 0;

  buffer = (unsigned char **)self->location;
  self->current = (*buffer)[0];
  if (self->current == NIL)
    {
      self->current = EOF;
    }
  else
    {
      (*buffer)++;
      self->processed++;
      self->actually.cached++;
    }

  if (VALID(intPointer))
    {
      *intPointer = self->current;
    }
}

/*************************************************************************
 *
 * Formatted scanning functions
 *
 ************************************************************************/

#if defined(TRIO_DOCUMENTATION)
# include "doc/doc_scanf.h"
#endif
/** @addtogroup Scanf
    @{
*/

/*************************************************************************
 * scanf
 */

/**
   Scan characters from standard input stream.

   @param format Formatting string.
   @param ... Arguments.
   @return Number of scanned characters.
 */
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int
trio_scanf
TRIO_VARGS2((format, va_alist),
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;

  assert(VALID(format));
  
  TRIO_VA_START(args, format);
  status = TrioScan((trio_pointer_t)stdin, 0,
		    TrioInStreamFile,
		    TrioUndoStreamFile,
		    format, args, NULL);
  TRIO_VA_END(args);
  return status;
}
#endif /* TRIO_FEATURE_STDIO */

/**
   Scan characters from standard input stream.

   @param format Formatting string.
   @param args Arguments.
   @return Number of scanned characters.
 */
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int
trio_vscanf
TRIO_ARGS2((format, args),
	   TRIO_CONST char *format,
	   va_list args)
{
  assert(VALID(format));
  
  return TrioScan((trio_pointer_t)stdin, 0,
		  TrioInStreamFile,
		  TrioUndoStreamFile,
		  format, args, NULL);
}
#endif /* TRIO_FEATURE_STDIO */

/**
   Scan characters from standard input stream.

   @param format Formatting string.
   @param args Arguments.
   @return Number of scanned characters.
 */
#if TRIO_FEATURE_STDIO
TRIO_PUBLIC int
trio_scanfv
TRIO_ARGS2((format, args),
	   TRIO_CONST char *format,
	   trio_pointer_t *args)
{
  static va_list unused;
  
  assert(VALID(format));
  
  return TrioScan((trio_pointer_t)stdin, 0,
		  TrioInStreamFile,
		  TrioUndoStreamFile,
		  format, unused, args);
}
#endif /* TRIO_FEATURE_STDIO */

/*************************************************************************
 * fscanf
 */

/**
   Scan characters from file.

   @param file File pointer.
   @param format Formatting string.
   @param ... Arguments.
   @return Number of scanned characters.
 */
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int
trio_fscanf
TRIO_VARGS3((file, format, va_alist),
	    FILE *file,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;

  assert(VALID(file));
  assert(VALID(format));
  
  TRIO_VA_START(args, format);
  status = TrioScan((trio_pointer_t)file, 0,
		    TrioInStreamFile,
		    TrioUndoStreamFile,
		    format, args, NULL);
  TRIO_VA_END(args);
  return status;
}
#endif /* TRIO_FEATURE_FILE */

/**
   Scan characters from file.

   @param file File pointer.
   @param format Formatting string.
   @param args Arguments.
   @return Number of scanned characters.
 */
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int
trio_vfscanf
TRIO_ARGS3((file, format, args),
	   FILE *file,
	   TRIO_CONST char *format,
	   va_list args)
{
  assert(VALID(file));
  assert(VALID(format));
  
  return TrioScan((trio_pointer_t)file, 0,
		  TrioInStreamFile,
		  TrioUndoStreamFile,
		  format, args, NULL);
}
#endif /* TRIO_FEATURE_FILE */

/**
   Scan characters from file.

   @param file File pointer.
   @param format Formatting string.
   @param args Arguments.
   @return Number of scanned characters.
 */
#if TRIO_FEATURE_FILE
TRIO_PUBLIC int
trio_fscanfv
TRIO_ARGS3((file, format, args),
	   FILE *file,
	   TRIO_CONST char *format,
	   trio_pointer_t *args)
{
  static va_list unused;
  
  assert(VALID(file));
  assert(VALID(format));
  
  return TrioScan((trio_pointer_t)file, 0,
		  TrioInStreamFile,
		  TrioUndoStreamFile,
		  format, unused, args);
}
#endif /* TRIO_FEATURE_FILE */

/*************************************************************************
 * dscanf
 */

/**
   Scan characters from file descriptor.

   @param fd File descriptor.
   @param format Formatting string.
   @param ... Arguments.
   @return Number of scanned characters.
 */
#if TRIO_FEATURE_FD
TRIO_PUBLIC int
trio_dscanf
TRIO_VARGS3((fd, format, va_alist),
	    int fd,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;

  assert(VALID(format));
  
  TRIO_VA_START(args, format);
  status = TrioScan((trio_pointer_t)&fd, 0,
		    TrioInStreamFileDescriptor,
		    NULL,
		    format, args, NULL);
  TRIO_VA_END(args);
  return status;
}
#endif /* TRIO_FEATURE_FD */

/**
   Scan characters from file descriptor.

   @param fd File descriptor.
   @param format Formatting string.
   @param args Arguments.
   @return Number of scanned characters.
 */
#if TRIO_FEATURE_FD
TRIO_PUBLIC int
trio_vdscanf
TRIO_ARGS3((fd, format, args),
	   int fd,
	   TRIO_CONST char *format,
	   va_list args)
{
  assert(VALID(format));
  
  return TrioScan((trio_pointer_t)&fd, 0,
		  TrioInStreamFileDescriptor,
		  NULL,
		  format, args, NULL);
}
#endif /* TRIO_FEATURE_FD */

/**
   Scan characters from file descriptor.

   @param fd File descriptor.
   @param format Formatting string.
   @param args Arguments.
   @return Number of scanned characters.
 */
#if TRIO_FEATURE_FD
TRIO_PUBLIC int
trio_dscanfv
TRIO_ARGS3((fd, format, args),
	   int fd,
	   TRIO_CONST char *format,
	   trio_pointer_t *args)
{
  static va_list unused;
  
  assert(VALID(format));
  
  return TrioScan((trio_pointer_t)&fd, 0,
		  TrioInStreamFileDescriptor,
		  NULL,
		  format, unused, args);
}
#endif /* TRIO_FEATURE_FD */

/*************************************************************************
 * cscanf
 */
#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int
trio_cscanf
TRIO_VARGS4((stream, closure, format, va_alist),
	    trio_instream_t stream,
	    trio_pointer_t closure,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;
  trio_custom_t data;

  assert(VALID(stream));
  assert(VALID(format));
  
  TRIO_VA_START(args, format);
  data.stream.in = stream;
  data.closure = closure;
  status = TrioScan(&data, 0, TrioInStreamCustom, NULL, format, args, NULL);
  TRIO_VA_END(args);
  return status;
}
#endif /* TRIO_FEATURE_CLOSURE */

#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int
trio_vcscanf
TRIO_ARGS4((stream, closure, format, args),
	   trio_instream_t stream,
	   trio_pointer_t closure,
	   TRIO_CONST char *format,
	   va_list args)
{
  trio_custom_t data;
  
  assert(VALID(stream));
  assert(VALID(format));

  data.stream.in = stream;
  data.closure = closure;
  return TrioScan(&data, 0, TrioInStreamCustom, NULL, format, args, NULL);
}
#endif /* TRIO_FEATURE_CLOSURE */

#if TRIO_FEATURE_CLOSURE
TRIO_PUBLIC int
trio_cscanfv
TRIO_ARGS4((stream, closure, format, args),
	   trio_instream_t stream,
	   trio_pointer_t closure,
	   TRIO_CONST char *format,
	   trio_pointer_t *args)
{
  static va_list unused;
  trio_custom_t data;
  
  assert(VALID(stream));
  assert(VALID(format));

  data.stream.in = stream;
  data.closure = closure;
  return TrioScan(&data, 0, TrioInStreamCustom, NULL, format, unused, args);
}
#endif /* TRIO_FEATURE_CLOSURE */

/*************************************************************************
 * sscanf
 */

/**
   Scan characters from string.

   @param buffer Input string.
   @param format Formatting string.
   @param ... Arguments.
   @return Number of scanned characters.
 */
TRIO_PUBLIC int
trio_sscanf
TRIO_VARGS3((buffer, format, va_alist),
	    TRIO_CONST char *buffer,
	    TRIO_CONST char *format,
	    TRIO_VA_DECL)
{
  int status;
  va_list args;

  assert(VALID(buffer));
  assert(VALID(format));
  
  TRIO_VA_START(args, format);
  status = TrioScan((trio_pointer_t)&buffer, 0,
		    TrioInStreamString,
		    NULL,
		    format, args, NULL);
  TRIO_VA_END(args);
  return status;
}

/**
   Scan characters from string.

   @param buffer Input string.
   @param format Formatting string.
   @param args Arguments.
   @return Number of scanned characters.
 */
TRIO_PUBLIC int
trio_vsscanf
TRIO_ARGS3((buffer, format, args),
	   TRIO_CONST char *buffer,
	   TRIO_CONST char *format,
	   va_list args)
{
  assert(VALID(buffer));
  assert(VALID(format));
  
  return TrioScan((trio_pointer_t)&buffer, 0,
		  TrioInStreamString,
		  NULL,
		  format, args, NULL);
}

/**
   Scan characters from string.

   @param buffer Input string.
   @param format Formatting string.
   @param args Arguments.
   @return Number of scanned characters.
 */
TRIO_PUBLIC int
trio_sscanfv
TRIO_ARGS3((buffer, format, args),
	   TRIO_CONST char *buffer,
	   TRIO_CONST char *format,
	   trio_pointer_t *args)
{
  static va_list unused;
  
  assert(VALID(buffer));
  assert(VALID(format));
  
  return TrioScan((trio_pointer_t)&buffer, 0,
		  TrioInStreamString,
		  NULL,
		  format, unused, args);
}

#endif /* TRIO_FEATURE_SCANF */

/** @} End of Scanf documentation module */

/*************************************************************************
 * trio_strerror
 */
TRIO_PUBLIC TRIO_CONST char *
trio_strerror
TRIO_ARGS1((errorcode),
	   int errorcode)
{
#if TRIO_FEATURE_STRERR
  /* Textual versions of the error codes */
  switch (TRIO_ERROR_CODE(errorcode))
    {
    case TRIO_EOF:
      return "End of file";
    case TRIO_EINVAL:
      return "Invalid argument";
    case TRIO_ETOOMANY:
      return "Too many arguments";
    case TRIO_EDBLREF:
      return "Double reference";
    case TRIO_EGAP:
      return "Reference gap";
    case TRIO_ENOMEM:
      return "Out of memory";
    case TRIO_ERANGE:
      return "Invalid range";
    case TRIO_ECUSTOM:
      return "Custom error";
    default:
      return "Unknown";
    }
#else
  return "Unknown";
#endif
}