summaryrefslogtreecommitdiff
path: root/src/amount.cc
blob: 9c41885e769cd5d2332a2238c9c1dac0e0a63104 (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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
/*
 * Copyright (c) 2003-2009, John Wiegley.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of New Artisans LLC nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "amount.h"
#include "binary.h"

namespace ledger {

commodity_pool_t * amount_t::current_pool = NULL;

bool amount_t::keep_base = false;

bool amount_t::keep_price = false;
bool amount_t::keep_date  = false;
bool amount_t::keep_tag	  = false;

bool amount_t::stream_fullstrings = false;

#if !defined(THREADSAFE)
// These global temporaries are pre-initialized for the sake of
// efficiency, and are reused over and over again.
static mpz_t temp;
static mpfr_t tempf;
#ifdef INTEGER_MATH
static mpz_t divisor;
#else
static mpq_t tempq;
#endif
#endif

struct amount_t::bigint_t : public supports_flags<>
{
#define BIGINT_BULK_ALLOC 0x01
#define BIGINT_KEEP_PREC  0x02

#ifdef INTEGER_MATH
  mpz_t		 val;
#else
  mpq_t		 val;
#endif
  precision_t	 prec;		// this is only an estimate
  uint_least16_t ref;
  uint_fast32_t	 index;

#define MP(bigint) ((bigint)->val)

  bigint_t() : prec(0), ref(1), index(0) {
    TRACE_CTOR(bigint_t, "");
#ifdef INTEGER_MATH
    mpz_init(val);
#else
    mpq_init(val);
#endif
  }
#ifdef INTEGER_MATH
  bigint_t(mpz_t _val) : prec(0), ref(1), index(0) {
    TRACE_CTOR(bigint_t, "mpz_t");
    mpz_init_set(val, _val);
  }
#else
#if 0
  bigint_t(mpq_t _val) : prec(0), ref(1), index(0) {
    TRACE_CTOR(bigint_t, "mpq_t");
    mpq_init(val, _val);
    mpq_set(val, _val);
  }
#endif
#endif
  bigint_t(const bigint_t& other)
    : supports_flags<>(other.flags() & ~BIGINT_BULK_ALLOC),
      prec(other.prec), ref(1), index(0) {
    TRACE_CTOR(bigint_t, "copy");
#ifdef INTEGER_MATH
    mpz_init_set(val, other.val);
#else
    mpq_init(val);
    mpq_set(val, other.val);
#endif
  }
  ~bigint_t() {
    TRACE_DTOR(bigint_t);
    assert(ref == 0);
#ifdef INTEGER_MATH
    mpz_clear(val);
#else
    mpq_clear(val);
#endif
  }

  bool valid() const {
    if (prec > 128) {
      DEBUG("ledger.validate", "amount_t::bigint_t: prec > 128");
      return false;
    }
    if (ref > 16535) {
      DEBUG("ledger.validate", "amount_t::bigint_t: ref > 16535");
      return false;
    }
    return true;
  }
};

uint_fast32_t amount_t::sizeof_bigint_t()
{
  return sizeof(bigint_t);
}

amount_t * one = NULL;

void amount_t::initialize()
{
  mpz_init(temp);
  mpfr_init(tempf);
#ifdef INTEGER_MATH
  mpz_init(divisor);
#else
  mpq_init(tempq);
#endif

  one = new amount_t(amount_t(1L).unround());

  if (! current_pool)
    current_pool = new commodity_pool_t;

  // Add time commodity conversions, so that timelog's may be parsed
  // in terms of seconds, but reported as minutes or hours.
  if (commodity_t * commodity = current_pool->create("s")) {
    commodity->add_flags(COMMODITY_BUILTIN | COMMODITY_NOMARKET);

    parse_conversion("1.0m", "60s");
    parse_conversion("1.0h", "60m");
  } else {
    assert(false);
  }
}

void amount_t::shutdown()
{
  mpz_clear(temp);
  mpfr_clear(tempf);
#ifdef INTEGER_MATH
  mpz_clear(divisor);
#else
  mpq_clear(tempq);
#endif

  checked_delete(one);

  if (current_pool) {
    checked_delete(current_pool);
    current_pool = NULL;
  }
}

void amount_t::_copy(const amount_t& amt)
{
  assert(amt.valid());

  if (quantity != amt.quantity) {
    if (quantity)
      _release();

    // Never maintain a pointer into a bulk allocation pool; such
    // pointers are not guaranteed to remain.
    if (amt.quantity->has_flags(BIGINT_BULK_ALLOC)) {
      quantity = new bigint_t(*amt.quantity);
    } else {
      quantity = amt.quantity;
      DEBUG("amounts.refs",
	     quantity << " ref++, now " << (quantity->ref + 1));
      quantity->ref++;
    }
  }
  commodity_ = amt.commodity_;

  assert(valid());
}

void amount_t::_dup()
{
  assert(valid());

  if (quantity->ref > 1) {
    bigint_t * q = new bigint_t(*quantity);
    _release();
    quantity = q;
  }

  assert(valid());
}

#ifdef INTEGER_MATH

void amount_t::_resize(precision_t prec)
{
  assert(prec < 256);

  if (! quantity || prec == quantity->prec)
    return;

  _dup();

  assert(prec > quantity->prec);
  mpz_ui_pow_ui(divisor, 10, prec - quantity->prec);
  mpz_mul(MP(quantity), MP(quantity), divisor);

  quantity->prec = prec;

  assert(valid());
}

#endif // INTEGER_MATH

void amount_t::_clear()
{
  if (quantity) {
    _release();
    quantity   = NULL;
    commodity_ = NULL;
  } else {
    assert(! commodity_);
  }
}

void amount_t::_release()
{
  assert(valid());

  DEBUG("amounts.refs", quantity << " ref--, now " << (quantity->ref - 1));

  if (--quantity->ref == 0) {
    if (quantity->has_flags(BIGINT_BULK_ALLOC))
      quantity->~bigint_t();
    else
      checked_delete(quantity);
    quantity   = NULL;
    commodity_ = NULL;
  }

  assert(valid());
}


amount_t::amount_t(const double val) : commodity_(NULL)
{
  TRACE_CTOR(amount_t, "const double");
  quantity = new bigint_t;
#ifdef INTEGER_MATH
  mpfr_set_d(tempf, val, GMP_RNDN);
#else
  mpq_set_d(MP(quantity), val);
#endif
  quantity->prec = extend_by_digits; // an approximation
}

amount_t::amount_t(const unsigned long val) : commodity_(NULL)
{
  TRACE_CTOR(amount_t, "const unsigned long");
  quantity = new bigint_t;
#ifdef INTEGER_MATH
  mpz_set_ui(MP(quantity), val);
#else
  mpq_set_ui(MP(quantity), val, 1);
#endif
}

amount_t::amount_t(const long val) : commodity_(NULL)
{
  TRACE_CTOR(amount_t, "const long");
  quantity = new bigint_t;
#ifdef INTEGER_MATH
  mpz_set_si(MP(quantity), val);
#else
  mpq_set_si(MP(quantity), val, 1);
#endif
}


amount_t& amount_t::operator=(const amount_t& amt)
{
  if (this != &amt) {
    if (amt.quantity)
      _copy(amt);
    else if (quantity)
      _clear();
  }
  return *this;
}


int amount_t::compare(const amount_t& amt) const
{
  assert(amt.valid());

  if (! quantity || ! amt.quantity) {
    if (quantity)
      throw_(amount_error, "Cannot compare an amount to an uninitialized amount");
    else if (amt.quantity)
      throw_(amount_error, "Cannot compare an uninitialized amount to an amount");
    else
      throw_(amount_error, "Cannot compare two uninitialized amounts");
  }

  if (has_commodity() && amt.has_commodity() &&
      commodity() != amt.commodity())
    throw_(amount_error,
	   "Cannot compare amounts with different commodities: " <<
	   commodity().symbol() << " and " << amt.commodity().symbol());

#ifdef INTEGER_MATH
  if (quantity->prec == amt.quantity->prec) {
    return mpz_cmp(MP(quantity), MP(amt.quantity));
  }
  else if (quantity->prec < amt.quantity->prec) {
    amount_t t(*this);
    t._resize(amt.quantity->prec);
    return mpz_cmp(MP(t.quantity), MP(amt.quantity));
  }
  else {
    amount_t t = amt;
    t._resize(quantity->prec);
    return mpz_cmp(MP(quantity), MP(t.quantity));
  }
#else
  return mpq_cmp(MP(quantity), MP(amt.quantity));
#endif
}


amount_t& amount_t::operator+=(const amount_t& amt)
{
  assert(amt.valid());

  if (! quantity || ! amt.quantity) {
    if (quantity)
      throw_(amount_error, "Cannot add an amount to an uninitialized amount");
    else if (amt.quantity)
      throw_(amount_error, "Cannot add an uninitialized amount to an amount");
    else
      throw_(amount_error, "Cannot add two uninitialized amounts");
  }

  if (commodity() != amt.commodity())
    throw_(amount_error,
	   "Adding amounts with different commodities: " <<
	   (has_commodity() ? commodity().symbol() : "NONE") <<
	   " != " <<
	   (amt.has_commodity() ? amt.commodity().symbol() : "NONE"));

  _dup();

#ifdef INTEGER_MATH
  if (quantity->prec == amt.quantity->prec) {
    mpz_add(MP(quantity), MP(quantity), MP(amt.quantity));
  }
  else if (quantity->prec < amt.quantity->prec) {
    _resize(amt.quantity->prec);
    mpz_add(MP(quantity), MP(quantity), MP(amt.quantity));
  }
  else {
    amount_t t = amt;
    t._resize(quantity->prec);
    mpz_add(MP(quantity), MP(quantity), MP(t.quantity));
  }
#else
  mpq_add(MP(quantity), MP(quantity), MP(amt.quantity));

  if (quantity->prec < amt.quantity->prec)
    quantity->prec = amt.quantity->prec;
#endif

  return *this;
}

amount_t& amount_t::operator-=(const amount_t& amt)
{
  assert(amt.valid());

  if (! quantity || ! amt.quantity) {
    if (quantity)
      throw_(amount_error, "Cannot subtract an amount from an uninitialized amount");
    else if (amt.quantity)
      throw_(amount_error, "Cannot subtract an uninitialized amount from an amount");
    else
      throw_(amount_error, "Cannot subtract two uninitialized amounts");
  }

  if (commodity() != amt.commodity())
    throw_(amount_error,
	   "Subtracting amounts with different commodities: " <<
	   (has_commodity() ? commodity().symbol() : "NONE") <<
	   " != " <<
	   (amt.has_commodity() ? amt.commodity().symbol() : "NONE"));

  _dup();

#ifdef INTEGER_MATH
  if (quantity->prec == amt.quantity->prec) {
    mpz_sub(MP(quantity), MP(quantity), MP(amt.quantity));
  }
  else if (quantity->prec < amt.quantity->prec) {
    _resize(amt.quantity->prec);
    mpz_sub(MP(quantity), MP(quantity), MP(amt.quantity));
  }
  else {
    amount_t t = amt;
    t._resize(quantity->prec);
    mpz_sub(MP(quantity), MP(quantity), MP(t.quantity));
  }
#else
  mpq_sub(MP(quantity), MP(quantity), MP(amt.quantity));

  if (quantity->prec < amt.quantity->prec)
    quantity->prec = amt.quantity->prec;
#endif

  return *this;
}

#ifdef INTEGER_MATH

namespace {
  void mpz_round(mpz_t out, mpz_t value, int value_prec, int round_prec)
  {
    // Round `value', with an encoding precision of `value_prec', to a
    // rounded value with precision `round_prec'.  Result is stored in
    // `out'.

    assert(value_prec > round_prec);

    mpz_t quotient;
    mpz_t remainder;

    mpz_init(quotient);
    mpz_init(remainder);

    mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
    mpz_tdiv_qr(quotient, remainder, value, divisor);
    mpz_divexact_ui(divisor, divisor, 10);
    mpz_mul_ui(divisor, divisor, 5);

    if (mpz_sgn(remainder) < 0) {
      mpz_neg(divisor, divisor);
      if (mpz_cmp(remainder, divisor) < 0) {
	mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
	mpz_add(remainder, divisor, remainder);
	mpz_ui_sub(remainder, 0, remainder);
	mpz_add(out, value, remainder);
      } else {
	mpz_sub(out, value, remainder);
      }
    } else {
      if (mpz_cmp(remainder, divisor) >= 0) {
	mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
	mpz_sub(remainder, divisor, remainder);
	mpz_add(out, value, remainder);
      } else {
	mpz_sub(out, value, remainder);
      }
    }
    mpz_clear(quotient);
    mpz_clear(remainder);

    // chop off the rounded bits
    mpz_ui_pow_ui(divisor, 10, value_prec - round_prec);
    mpz_tdiv_q(out, out, divisor);
  }
}

#endif // INTEGER_MATH

amount_t& amount_t::operator*=(const amount_t& amt)
{
  assert(amt.valid());

  if (! quantity || ! amt.quantity) {
    if (quantity)
      throw_(amount_error, "Cannot multiply an amount by an uninitialized amount");
    else if (amt.quantity)
      throw_(amount_error, "Cannot multiply an uninitialized amount by an amount");
    else
      throw_(amount_error, "Cannot multiply two uninitialized amounts");
  }

  _dup();

#ifdef INTEGER_MATH
  mpz_mul(MP(quantity), MP(quantity), MP(amt.quantity));
#else
  mpq_mul(MP(quantity), MP(quantity), MP(amt.quantity));
#endif
  quantity->prec += amt.quantity->prec;

  if (! has_commodity())
    commodity_ = amt.commodity_;

  if (has_commodity() && ! keep_precision()) {
    precision_t comm_prec = commodity().precision();
    if (quantity->prec > comm_prec + extend_by_digits) {
#ifdef INTEGER_MATH
      mpz_round(MP(quantity), MP(quantity), quantity->prec,
		comm_prec + extend_by_digits);
#endif // INTEGER_MATH
      quantity->prec = comm_prec + extend_by_digits;
    }
  }

  return *this;
}

amount_t& amount_t::operator/=(const amount_t& amt)
{
  assert(amt.valid());

  if (! quantity || ! amt.quantity) {
    if (quantity)
      throw_(amount_error, "Cannot divide an amount by an uninitialized amount");
    else if (amt.quantity)
      throw_(amount_error, "Cannot divide an uninitialized amount by an amount");
    else
      throw_(amount_error, "Cannot divide two uninitialized amounts");
  }

  if (! amt)
    throw_(amount_error, "Divide by zero");

  _dup();

  // Increase the value's precision, to capture fractional parts after
  // the divide.  Round up in the last position.

#ifdef INTEGER_MATH
  mpz_ui_pow_ui(divisor, 10, (2 * amt.quantity->prec) + quantity->prec +
		extend_by_digits + 1U);
  mpz_mul(MP(quantity), MP(quantity), divisor);
  mpz_tdiv_q(MP(quantity), MP(quantity), MP(amt.quantity));
  quantity->prec += amt.quantity->prec + quantity->prec + extend_by_digits + 1U;

  mpz_round(MP(quantity), MP(quantity), quantity->prec, quantity->prec - 1);
  quantity->prec -= 1;
#else
  mpq_div(MP(quantity), MP(quantity), MP(amt.quantity));
  quantity->prec += amt.quantity->prec + quantity->prec + extend_by_digits;
#endif

  if (! has_commodity())
    commodity_ = amt.commodity_;

  // If this amount has a commodity, and we're not dealing with plain
  // numbers, or internal numbers (which keep full precision at all
  // times), then round the number to within the commodity's precision
  // plus six places.

  if (has_commodity() && ! keep_precision()) {
    precision_t comm_prec = commodity().precision();
    if (quantity->prec > comm_prec + extend_by_digits) {
#ifdef INTEGER_MATH
      mpz_round(MP(quantity), MP(quantity), quantity->prec,
		comm_prec + extend_by_digits);
#endif // INTEGER_MATH
      quantity->prec = comm_prec + extend_by_digits;
    }
  }

  return *this;
}


amount_t::precision_t amount_t::precision() const
{
  if (! quantity)
    throw_(amount_error,
	   "Cannot determine precision of an uninitialized amount");

  return quantity->prec;
}

bool amount_t::keep_precision() const
{
  if (! quantity)
    throw_(amount_error,
	   "Cannot determine if precision of an uninitialized amount is kept");

  return quantity->has_flags(BIGINT_KEEP_PREC);
}

void amount_t::set_keep_precision(const bool keep) const
{
  if (! quantity)
    throw_(amount_error,
	   "Cannot set whether to keep the precision of an uninitialized amount");

  if (keep)
    quantity->add_flags(BIGINT_KEEP_PREC);
  else
    quantity->drop_flags(BIGINT_KEEP_PREC);
}

amount_t::precision_t amount_t::display_precision(const bool full_precision) const
{
  if (! quantity)
    throw_(amount_error,
	   "Cannot determine display precision of an uninitialized amount");

  commodity_t& comm(commodity());

  if (! comm || full_precision || keep_precision())
    return quantity->prec;
  else if (comm.precision() != quantity->prec)
    return comm.precision();
  else if (quantity->prec)
    return quantity->prec;

  return 0;
}

amount_t& amount_t::in_place_negate()
{
  if (quantity) {
    _dup();
#ifdef INTEGER_MATH
    mpz_neg(MP(quantity), MP(quantity));
#else
    mpq_neg(MP(quantity), MP(quantity));
#endif
  } else {
    throw_(amount_error, "Cannot negate an uninitialized amount");
  }
  return *this;
}

#ifdef INTEGER_MATH

amount_t& amount_t::in_place_round()
{
  if (! quantity)
    throw_(amount_error, "Cannot round an uninitialized amount");

  if (has_commodity())
    in_place_round(commodity().precision());

  return *this;
}

amount_t& amount_t::in_place_round(precision_t prec)
{
  if (! quantity)
    throw_(amount_error, "Cannot round an uninitialized amount");

  if (quantity && quantity->prec <= prec) {
    if (keep_precision()) {
      _dup();
      set_keep_precision(false);
    }
    return *this;
  }

  DEBUG("amount.round", "Rounding " << *this << " to precision " << prec);

  _dup();
  mpz_round(MP(quantity), MP(quantity), quantity->prec, prec);

  quantity->prec = prec;
  set_keep_precision(false);

  DEBUG("amount.round", "  result = " << *this);

  return *this;
}

#endif // INTEGER_MATH

amount_t amount_t::unround() const
{
  if (! quantity)
    throw_(amount_error, "Cannot unround an uninitialized amount");
  else if (keep_precision())
    return *this;

  amount_t t(*this);
  t._dup();
  t.set_keep_precision(true);

  return t;
}

amount_t& amount_t::in_place_reduce()
{
  if (! quantity)
    throw_(amount_error, "Cannot reduce an uninitialized amount");

  while (commodity_ && commodity().smaller()) {
    *this *= commodity().smaller()->number();
    commodity_ = commodity().smaller()->commodity_;
  }
  return *this;
}

amount_t& amount_t::in_place_unreduce()
{
  if (! quantity)
    throw_(amount_error, "Cannot unreduce an uninitialized amount");

  while (commodity_ && commodity().larger()) {
    *this /= commodity().larger()->number();
    commodity_ = commodity().larger()->commodity_;
    if (abs() < amount_t(1L))
      break;
  }
  return *this;
}

optional<amount_t> amount_t::value(const optional<datetime_t>&   moment,
				   const optional<commodity_t&>& in_terms_of) const
{
  if (quantity) {
    optional<price_point_t> point(commodity().find_price(in_terms_of, moment));
    if (point)
#ifdef INTEGER_MATH
      return (point->price * number()).round();
#else
      return point->price * number();
#endif
  } else {
    throw_(amount_error, "Cannot determine value of an uninitialized amount");
  }
  return none;
}


int amount_t::sign() const
{
  if (! quantity)
    throw_(amount_error, "Cannot determine sign of an uninitialized amount");

#ifdef INTEGER_MATH
  return mpz_sgn(MP(quantity));
#else
  return mpq_sgn(MP(quantity));
#endif
}

bool amount_t::is_zero() const
{
  if (! quantity)
    throw_(amount_error, "Cannot determine if an uninitialized amount is zero");

  if (has_commodity()) {
    if (quantity->prec <= commodity().precision() || keep_precision()) {
      return is_realzero();
    } else {
#ifdef INTEGER_MATH
      return round(commodity().precision()).sign() == 0;
#else
      char * buf;

      mpfr_set_q(tempf, MP(quantity), GMP_RNDN);
      mpfr_asprintf(&buf, "%.*RNf", commodity().precision(), tempf);

      bool all_zeroes = true;
      for (const char * p = buf; *p; p++) {
	if (*p != '0' || *p != '.') {
	  all_zeroes = false;
	  break;
	}
      }

      mpfr_free_str(buf);
      return all_zeroes;
#endif
    }
  }
  return is_realzero();
}


double amount_t::to_double(bool no_check) const
{
  if (! quantity)
    throw_(amount_error, "Cannot convert an uninitialized amount to a double");

#ifdef INTEGER_MATH
  mpz_t remainder;
  mpz_init(remainder);

  mpz_set(temp, MP(quantity));
  mpz_ui_pow_ui(divisor, 10, quantity->prec);
  mpz_tdiv_qr(temp, remainder, temp, divisor);

  char * quotient_s  = mpz_get_str(NULL, 10, temp);
  char * remainder_s = mpz_get_str(NULL, 10, remainder);

  std::ostringstream num;
  num << quotient_s << '.' << remainder_s;

  std::free(quotient_s);
  std::free(remainder_s);

  mpz_clear(remainder);

  double value = lexical_cast<double>(num.str());

  if (! no_check && *this != value)
    throw_(amount_error, "Conversion of amount to_double loses precision");

  return value;
#else
  mpfr_set_q(tempf, MP(quantity), GMP_RNDN);
  return mpfr_get_d(tempf, GMP_RNDN);
#endif
}

long amount_t::to_long(bool no_check) const
{
  if (! quantity)
    throw_(amount_error, "Cannot convert an uninitialized amount to a long");

#ifdef INTEGER_MATH
  mpz_set(temp, MP(quantity));
  mpz_ui_pow_ui(divisor, 10, quantity->prec);
  mpz_tdiv_q(temp, temp, divisor);
#else
  mpfr_set_q(tempf, MP(quantity), GMP_RNDN);
  mpfr_get_z(temp, tempf, GMP_RNDN);
#endif
  long value = mpz_get_si(temp);

  if (! no_check && *this != value)
    throw_(amount_error, "Conversion of amount to_long loses precision");

  return value;
}

bool amount_t::fits_in_double() const
{
  double value = to_double(true);
  return *this == amount_t(value);
}

bool amount_t::fits_in_long() const
{
  long value = to_long(true);
  return *this == amount_t(value);
}


void amount_t::annotate(const annotation_t& details)
{
  commodity_t *		  this_base;
  annotated_commodity_t * this_ann = NULL;

  if (! quantity)
    throw_(amount_error, "Cannot annotate the commodity of an uninitialized amount");
  else if (! has_commodity())
    throw_(amount_error, "Cannot annotate an amount with no commodity");

  if (commodity().annotated) {
    this_ann  = &as_annotated_commodity(commodity());
    this_base = &this_ann->referent();
  } else {
    this_base = &commodity();
  }
  assert(this_base);

  DEBUG("amounts.commodities", "Annotating commodity for amount "
	<< *this << std::endl << details);

  if (commodity_t * ann_comm =
      this_base->parent().find_or_create(*this_base, details))
    set_commodity(*ann_comm);
#ifdef ASSERTS_ON
  else
    assert(false);
#endif

  DEBUG("amounts.commodities", "  Annotated amount is " << *this);
}

bool amount_t::is_annotated() const
{
  if (! quantity)
    throw_(amount_error,
	   "Cannot determine if an uninitialized amount's commodity is annotated");

  assert(! commodity().annotated || as_annotated_commodity(commodity()).details);
  return commodity().annotated;
}

annotation_t& amount_t::annotation()
{
  if (! quantity)
    throw_(amount_error,
	   "Cannot return commodity annotation details of an uninitialized amount");

  if (! commodity().is_annotated())
    throw_(amount_error,
	   "Request for annotation details from an unannotated amount");

  annotated_commodity_t& ann_comm(as_annotated_commodity(commodity()));
  return ann_comm.details;
}

amount_t amount_t::strip_annotations(const bool _keep_price,
				     const bool _keep_date,
				     const bool _keep_tag) const
{
  if (! quantity)
    throw_(amount_error,
	   "Cannot strip commodity annotations from an uninitialized amount");

  if (! commodity().annotated ||
      (_keep_price && _keep_date && _keep_tag))
    return *this;

  amount_t t(*this);
  t.set_commodity(as_annotated_commodity(commodity()).
		  strip_annotations(_keep_price, _keep_date, _keep_tag));
  return t;
}


namespace {
  void parse_quantity(std::istream& in, string& value)
  {
    char buf[256];
    char c = peek_next_nonws(in);
    READ_INTO(in, buf, 255, c,
	      std::isdigit(c) || c == '-' || c == '.' || c == ',');

    int len = std::strlen(buf);
    while (len > 0 && ! std::isdigit(buf[len - 1])) {
      buf[--len] = '\0';
      in.unget();
    }

    value = buf;
  }
}

bool amount_t::parse(std::istream& in, const parse_flags_t& flags)
{
  // The possible syntax for an amount is:
  //
  //   [-]NUM[ ]SYM [@ AMOUNT]
  //   SYM[ ][-]NUM [@ AMOUNT]

  string       symbol;
  string       quant;
  annotation_t details;
  bool	       negative	  = false;

  commodity_t::flags_t comm_flags = COMMODITY_STYLE_DEFAULTS;

  char c = peek_next_nonws(in);
  if (c == '-') {
    negative = true;
    in.get(c);
    c = peek_next_nonws(in);
  }

  char n;
  if (std::isdigit(c)) {
    parse_quantity(in, quant);

    if (! in.eof() && ((n = in.peek()) != '\n')) {
      if (std::isspace(n))
	comm_flags |= COMMODITY_STYLE_SEPARATED;

      commodity_t::parse_symbol(in, symbol);

      if (! symbol.empty())
	comm_flags |= COMMODITY_STYLE_SUFFIXED;

      if (! in.eof() && ((n = in.peek()) != '\n'))
	details.parse(in);
    }
  } else {
    commodity_t::parse_symbol(in, symbol);

    if (! in.eof() && ((n = in.peek()) != '\n')) {
      if (std::isspace(in.peek()))
	comm_flags |= COMMODITY_STYLE_SEPARATED;

      parse_quantity(in, quant);

      if (! quant.empty() && ! in.eof() && ((n = in.peek()) != '\n'))
	details.parse(in);
    }
  }

  if (quant.empty()) {
    if (flags.has_flags(PARSE_SOFT_FAIL))
      return false;
    else
      throw_(amount_error, "No quantity specified for amount");
  }

  // Allocate memory for the amount's quantity value.  We have to
  // monitor the allocation in an auto_ptr because this function gets
  // called sometimes from amount_t's constructor; and if there is an
  // exeception thrown by any of the function calls after this point,
  // the destructor will never be called and the memory never freed.

  std::auto_ptr<bigint_t> safe_holder;

  if (! quantity) {
    quantity = new bigint_t;
    safe_holder.reset(quantity);
  }
  else if (quantity->ref > 1) {
    _release();
    quantity = new bigint_t;
    safe_holder.reset(quantity);
  }

  // Create the commodity if has not already been seen, and update the
  // precision if something greater was used for the quantity.

  bool newly_created = false;

  if (symbol.empty()) {
    commodity_ = NULL;
  } else {
    commodity_ = current_pool->find(symbol);
    if (! commodity_) {
      commodity_ = current_pool->create(symbol);
      newly_created = true;
    }
    assert(commodity_);

    if (details)
      commodity_ = current_pool->find_or_create(*commodity_, details);
  }

  // Determine the precision of the amount, based on the usage of
  // comma or period.

  string::size_type last_comma  = quant.rfind(',');
  string::size_type last_period = quant.rfind('.');

  if (last_comma != string::npos && last_period != string::npos) {
    comm_flags |= COMMODITY_STYLE_THOUSANDS;
    if (last_comma > last_period) {
      comm_flags |= COMMODITY_STYLE_EUROPEAN;
      quantity->prec = quant.length() - last_comma - 1;
    } else {
      quantity->prec = quant.length() - last_period - 1;
    }
  }
  else if (last_comma != string::npos &&
	   commodity().has_flags(COMMODITY_STYLE_EUROPEAN)) {
    comm_flags |= COMMODITY_STYLE_EUROPEAN;
    quantity->prec = quant.length() - last_comma - 1;
  }
  else if (last_period != string::npos &&
	   ! (commodity().has_flags(COMMODITY_STYLE_EUROPEAN))) {
    quantity->prec = quant.length() - last_period - 1;
  }
  else {
    quantity->prec = 0;
  }

  // Set the commodity's flags and precision accordingly

  if (commodity_ && ! flags.has_flags(PARSE_NO_MIGRATE)) {
    commodity().add_flags(comm_flags);

    if (quantity->prec > commodity().precision())
      commodity().set_precision(quantity->prec);
  }

  // Setup the amount's own flags

  if (flags.has_flags(PARSE_NO_MIGRATE))
    set_keep_precision(true);

  // Now we have the final number.  Remove commas and periods, if
  // necessary.

  if (last_comma != string::npos || last_period != string::npos) {
    int		       len = quant.length();
    scoped_array<char> buf(new char[len + 1]);
    const char *       p   = quant.c_str();
    char *	       t   = buf.get();

    while (*p) {
      if (*p == ',' || *p == '.')
	p++;
      *t++ = *p++;
    }
    *t = '\0';

#ifdef INTEGER_MATH
    mpz_set_str(MP(quantity), buf.get(), 10);
#else
    mpq_set_str(MP(quantity), buf.get(), 10);
    mpz_ui_pow_ui(temp, 10, quantity->prec);
    mpq_set_z(tempq, temp);
    mpq_div(MP(quantity), MP(quantity), tempq);
#endif
  } else {
#ifdef INTEGER_MATH
    mpz_set_str(MP(quantity), quant.c_str(), 10);
#else
    mpq_set_str(MP(quantity), quant.c_str(), 10);
#endif
  }

  if (negative)
    in_place_negate();

  if (! flags.has_flags(PARSE_NO_REDUCE))
    in_place_reduce();

  safe_holder.release();	// `this->quantity' owns the pointer

  assert(valid());

  return true;
}

void amount_t::parse_conversion(const string& larger_str,
				const string& smaller_str)
{
  amount_t larger, smaller;

  larger.parse(larger_str, PARSE_NO_REDUCE);
  smaller.parse(smaller_str, PARSE_NO_REDUCE);

  larger *= smaller.number();

  if (larger.commodity()) {
    larger.commodity().set_smaller(smaller);
    larger.commodity().add_flags(smaller.commodity().flags() |
				 COMMODITY_NOMARKET);
  }
  if (smaller.commodity())
    smaller.commodity().set_larger(larger);
}

void amount_t::print(std::ostream& _out, bool omit_commodity,
		     bool full_precision) const
{
  assert(valid());

  if (! quantity) {
    _out << "<null>";
    return;
  }

  amount_t base(*this);
  if (! amount_t::keep_base)
    base.in_place_unreduce();

  std::ostringstream out;

  commodity_t& comm(base.commodity());
  precision_t  precision = 0;

#ifdef INTEGER_MATH

  mpz_t quotient;
  mpz_t rquotient;
  mpz_t remainder;

  mpz_init(quotient);
  mpz_init(rquotient);
  mpz_init(remainder);

  bool negative = false;

  // Ensure the value is rounded to the commodity's precision before
  // outputting it.  NOTE: `rquotient' is used here as a temp variable!

  if (quantity) {
    if (! comm || full_precision || base.keep_precision()) {
      mpz_ui_pow_ui(divisor, 10, base.quantity->prec);
      mpz_tdiv_qr(quotient, remainder, MP(base.quantity), divisor);
      precision = base.quantity->prec;
    }
    else if (comm.precision() < base.quantity->prec) {
      mpz_round(rquotient, MP(base.quantity), base.quantity->prec,
		comm.precision());
      mpz_ui_pow_ui(divisor, 10, comm.precision());
      mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
      precision = comm.precision();
    }
    else if (comm.precision() > base.quantity->prec) {
      mpz_ui_pow_ui(divisor, 10, comm.precision() - base.quantity->prec);
      mpz_mul(rquotient, MP(base.quantity), divisor);
      mpz_ui_pow_ui(divisor, 10, comm.precision());
      mpz_tdiv_qr(quotient, remainder, rquotient, divisor);
      precision = comm.precision();
    }
    else if (base.quantity->prec) {
      mpz_ui_pow_ui(divisor, 10, base.quantity->prec);
      mpz_tdiv_qr(quotient, remainder, MP(base.quantity), divisor);
      precision = base.quantity->prec;
    }
    else {
      mpz_set(quotient, MP(base.quantity));
      mpz_set_ui(remainder, 0);
      precision = 0;
    }

    if (mpz_sgn(quotient) < 0 || mpz_sgn(remainder) < 0) {
      negative = true;

      mpz_abs(quotient, quotient);
      mpz_abs(remainder, remainder);
    }
    mpz_set(rquotient, remainder);
  }

  if (! omit_commodity && ! comm.has_flags(COMMODITY_STYLE_SUFFIXED)) {
    comm.print(out);
    if (comm.has_flags(COMMODITY_STYLE_SEPARATED))
      out << " ";
  }

  if (negative)
    out << "-";

  if (! quantity || mpz_sgn(quotient) == 0) {
    out << '0';
  }
  else if (omit_commodity || ! comm.has_flags(COMMODITY_STYLE_THOUSANDS)) {
    char * p = mpz_get_str(NULL, 10, quotient);
    out << p;
    std::free(p);
  }
  else {
    std::list<string> strs;
    char buf[4];

    for (int powers = 0; true; powers += 3) {
      if (powers > 0) {
	mpz_ui_pow_ui(divisor, 10, powers);
	mpz_tdiv_q(temp, quotient, divisor);
	if (mpz_sgn(temp) == 0)
	  break;
	mpz_tdiv_r_ui(temp, temp, 1000);
      } else {
	mpz_tdiv_r_ui(temp, quotient, 1000);
      }
      mpz_get_str(buf, 10, temp);
      strs.push_back(buf);
    }

    bool printed = false;

    for (std::list<string>::reverse_iterator i = strs.rbegin();
	 i != strs.rend();
	 i++) {
      if (printed) {
	out << (comm.has_flags(COMMODITY_STYLE_EUROPEAN) ? '.' : ',');
	out.width(3);
	out.fill('0');
      }
      out << *i;

      printed = true;
    }
  }

  if (quantity && precision) {
    std::ostringstream final;
    final.width(precision);
    final.fill('0');
    char * p = mpz_get_str(NULL, 10, rquotient);
    final << p;
    std::free(p);

    const string& str(final.str());
    int i, len = str.length();
    const char * q = str.c_str();
    for (i = len; i > 0; i--)
      if (q[i - 1] != '0')
	break;

    string ender;
    if (i == len)
      ender = str;
    else if (i < comm.precision())
      ender = string(str, 0, comm.precision());
    else
      ender = string(str, 0, i);

    if (! ender.empty()) {
      if (omit_commodity)
	out << '.';
      else
	out << (comm.has_flags(COMMODITY_STYLE_EUROPEAN) ? ',' : '.');
      out << ender;
    }
  }

  if (! omit_commodity && comm.has_flags(COMMODITY_STYLE_SUFFIXED)) {
    if (comm.has_flags(COMMODITY_STYLE_SEPARATED))
      out << " ";
    comm.print(out);
  }

  mpz_clear(quotient);
  mpz_clear(rquotient);
  mpz_clear(remainder);

#else // INTEGER_MATH

  char * buf;
  mpfr_set_q(tempf, MP(quantity), GMP_RNDN);
  mpfr_asprintf(&buf, "%.*RNf", base.display_precision(full_precision), tempf);
  DEBUG("amount.print", "mpfr_print = " << buf);

  try {
    if (! omit_commodity && ! comm.has_flags(COMMODITY_STYLE_SUFFIXED)) {
      comm.print(out);
      if (comm.has_flags(COMMODITY_STYLE_SEPARATED))
	out << " ";
    }

    if (omit_commodity || ! comm.has_flags(COMMODITY_STYLE_THOUSANDS)) {
      if (! comm.has_flags(COMMODITY_STYLE_EUROPEAN))
	out << buf;
      else
	for (const char * p = buf; *p; p++)
	  if (*p == '.')
	    out << ',';
	  else
	    out << *p;
    } else {
      // Count the number of integer digits
      int integer_digits = 0;
      for (const char * p = buf; *p; p++) {
	if (*p == '.')
	  break;
	else if (std::isdigit(*p))
	  integer_digits++;
      }

      for (const char * p = buf; *p; p++) {
	if (*p == '.' && comm.has_flags(COMMODITY_STYLE_EUROPEAN))
	  out << ',';
	else
	  out << *p;

	if (std::isdigit(*p) && integer_digits > 3 &&
	    --integer_digits % 3 == 0)
	  out << ',';
      }
    }
  }
  catch (...) {
    mpfr_free_str(buf);
    throw;
  }
  mpfr_free_str(buf);

  if (! omit_commodity && comm.has_flags(COMMODITY_STYLE_SUFFIXED)) {
    if (comm.has_flags(COMMODITY_STYLE_SEPARATED))
      out << " ";
    comm.print(out);
  }

#endif // INTEGER_MATH

  // If there are any annotations associated with this commodity,
  // output them now.

  if (! omit_commodity && comm.annotated) {
    annotated_commodity_t& ann(static_cast<annotated_commodity_t&>(comm));
    assert(&*ann.details.price != this);
    ann.write_annotations(out);
  }

  // Things are output to a string first, so that if anyone has
  // specified a width or fill for _out, it will be applied to the
  // entire amount string, and not just the first part.

  _out << out.str();
}

void amount_t::read(std::istream& in)
{
  using namespace ledger::binary;

  // Read in the commodity for this amount

  commodity_t::ident_t ident;
  read_long(in, ident);
  if (ident == 0xffffffff)
    commodity_ = NULL;
  else if (ident == 0)
    commodity_ = current_pool->null_commodity;
  else {
    commodity_ = current_pool->find(ident);
    assert(commodity_);
  }

  // Read in the quantity

  char byte;
  in.read(&byte, sizeof(byte));

  if (byte < 3) {
    quantity = new bigint_t;

#ifndef INTEGER_MATH
    mpz_t numerator;
    mpz_t denominator;
#endif

    unsigned short len;
    in.read(reinterpret_cast<char *>(&len), sizeof(len));
    assert(len < 4096);
    static char buf[4096];
    in.read(buf, len);
#ifdef INTEGER_MATH
    mpz_import(MP(quantity), len / sizeof(short), 1, sizeof(short),
	       0, 0, buf);
#else
    mpz_init(numerator);
    mpz_import(numerator, len / sizeof(short), 1, sizeof(short),
	       0, 0, buf);

    in.read(reinterpret_cast<char *>(&len), sizeof(len));
    assert(len < 4096);
    in.read(buf, len);
    mpz_init(denominator);
    mpz_import(denominator, len / sizeof(short), 1, sizeof(short),
	       0, 0, buf);

    mpq_set_num(MP(quantity), numerator);
    mpq_set_den(MP(quantity), denominator);
#endif

    char negative;
    in.read(&negative, sizeof(negative));
    if (negative)
#ifdef INTEGER_MATH
      mpz_neg(MP(quantity), MP(quantity));
#else
      mpq_neg(MP(quantity), MP(quantity));
#endif

    in.read(reinterpret_cast<char *>(&quantity->prec), sizeof(quantity->prec));

    bigint_t::flags_t tflags;
    in.read(reinterpret_cast<char *>(&tflags), sizeof(tflags));
    quantity->set_flags(tflags);
  }
  else {
    assert(false);
  }
}

void amount_t::read(const char *& data,
		    char **	  pool,
		    char **       pool_next)
{
  using namespace ledger::binary;

  // Read in the commodity for this amount

  commodity_t::ident_t ident;
  read_long(data, ident);
  if (ident == 0xffffffff)
    commodity_ = NULL;
  else if (ident == 0)
    commodity_ = current_pool->null_commodity;
  else {
    commodity_ = current_pool->find(ident);
    assert(commodity_);
  }

  // Read in the quantity

  char byte = *data++;;

  if (byte < 3) {
    if (byte == 2) {
      quantity = new(reinterpret_cast<bigint_t *>(*pool_next)) bigint_t;
      *pool_next += sizeof(bigint_t);
    } else {
      quantity = new bigint_t;
    }

#ifndef INTEGER_MATH
    mpz_t numerator;
    mpz_t denominator;
#endif

    unsigned short len =
      *reinterpret_cast<unsigned short *>(const_cast<char *>(data));
    data += sizeof(unsigned short);
#ifdef INTEGER_MATH
    mpz_import(MP(quantity), len / sizeof(short), 1, sizeof(short),
	       0, 0, data);
#else
    mpz_init(numerator);
    mpz_import(numerator, len / sizeof(short), 1, sizeof(short),
	       0, 0, data);

    len = *reinterpret_cast<unsigned short *>(const_cast<char *>(data));
    data += sizeof(unsigned short);
    mpz_init(denominator);
    mpz_import(denominator, len / sizeof(short), 1, sizeof(short),
	       0, 0, data);

    mpq_set_num(MP(quantity), numerator);
    mpq_set_den(MP(quantity), denominator);
#endif
    data += len;

    char negative = *data++;
    if (negative)
#ifdef INTEGER_MATH
      mpz_neg(MP(quantity), MP(quantity));
#else
      mpq_neg(MP(quantity), MP(quantity));
#endif

    quantity->prec = *reinterpret_cast<precision_t *>(const_cast<char *>(data));
    data += sizeof(precision_t);
    quantity->set_flags(*reinterpret_cast<bigint_t::flags_t *>(const_cast<char *>(data)));
    data += sizeof(bigint_t::flags_t);

    if (byte == 2)
      quantity->add_flags(BIGINT_BULK_ALLOC);
  } else {
    uint_fast32_t index = *reinterpret_cast<uint_fast32_t *>(const_cast<char *>(data));
    data += sizeof(uint_fast32_t);

    quantity = reinterpret_cast<bigint_t *>(*pool + (index - 1) * sizeof(bigint_t));

    DEBUG("amounts.refs",
	   quantity << " ref++, now " << (quantity->ref + 1));
    quantity->ref++;
  }
}

void amount_t::write(std::ostream& out, std::size_t index) const
{
  using namespace ledger::binary;

  // Write out the commodity for this amount

  if (! quantity)
    throw_(amount_error, "Cannot serialize an uninitialized amount");

  if (commodity_)
    write_long(out, commodity_->ident);
  else
    write_long<commodity_t::ident_t>(out, 0xffffffff);

  // Write out the quantity

  char byte;

  if (index == 0 || quantity->index == 0) {
    if (index != 0) {
      quantity->index = index;	// if !optimized, this is garbage
      byte = 2;
    } else {
      byte = 1;
    }
    out.write(&byte, sizeof(byte));

    std::size_t size;
    static char buf[4096];
#ifdef INTEGER_MATH
    mpz_export(buf, &size, 1, sizeof(short), 0, 0, MP(quantity));
#else
    mpz_t numerator;
    mpz_t denominator;

    mpz_init(numerator);
    mpq_get_num(numerator, MP(quantity));
    mpz_export(buf, &size, 1, sizeof(short), 0, 0, numerator);

    mpz_init(denominator);
    mpq_get_den(denominator, MP(quantity));
    mpz_export(buf, &size, 1, sizeof(short), 0, 0, denominator);
#endif
    unsigned short len = size * sizeof(short);
    out.write(reinterpret_cast<char *>(&len), sizeof(len));
    if (len) {
      assert(len < 4096);
      out.write(buf, len);
    }

#ifdef INTEGER_MATH
    byte = mpz_sgn(MP(quantity)) < 0 ? 1 : 0;
#else
    byte = mpq_sgn(MP(quantity)) < 0 ? 1 : 0;
#endif
    out.write(&byte, sizeof(byte));

    out.write(reinterpret_cast<char *>(&quantity->prec), sizeof(quantity->prec));
    bigint_t::flags_t tflags = quantity->flags() & ~BIGINT_BULK_ALLOC;
    assert(sizeof(tflags) == sizeof(bigint_t::flags_t));
    out.write(reinterpret_cast<char *>(&tflags), sizeof(tflags));
  } else {
    assert(quantity->ref > 1);

    // Since this value has already been written, we simply write
    // out a reference to which one it was.
    byte = 3;
    out.write(&byte, sizeof(byte));
    out.write(reinterpret_cast<char *>(&quantity->index), sizeof(quantity->index));
  }
}

void amount_t::read_xml(std::istream& in)
{
}

void amount_t::write_xml(std::ostream& out, const int depth) const
{
  xml_print(out, "<amount>\n", depth);

  commodity().write_xml(out, depth + 1);

  xml_print(out, "<quantity>", depth + 1);
  out << quantity_string() << "</quantity>\n";

  xml_print(out, "</amount>\n", depth);
}

bool amount_t::valid() const
{
  if (quantity) {
    if (! quantity->valid())
      return false;

    if (quantity->ref == 0) {
      DEBUG("ledger.validate", "amount_t: quantity->ref == 0");
      return false;
    }
  }
  else if (commodity_) {
    DEBUG("ledger.validate", "amount_t: commodity_ != NULL");
    return false;
  }
  return true;
}

} // namespace ledger