summaryrefslogtreecommitdiffstats
path: root/kmymoney2/reports/pivottable.cpp
blob: c12ca57c0edc5b06f468b6176e1c8bb06dca719e (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
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
/***************************************************************************
                          pivottable.cpp
                             -------------------
    begin                : Mon May 17 2004
    copyright            : (C) 2004-2005 by Ace Jones
    email                : <ace.j@hotpop.com>
                           Thomas Baumgart <ipwizard@users.sourceforge.net>
                           Alvaro Soliverez <asoliverez@gmail.com>
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

// ----------------------------------------------------------------------------
// QT Includes
#include <qlayout.h>
#include <qdatetime.h>
#include <qregexp.h>
#include <qdragobject.h>
#include <qclipboard.h>
#include <qapplication.h>
#include <qprinter.h>
#include <qpainter.h>
#include <qfile.h>
#include <qdom.h>

// ----------------------------------------------------------------------------
// KDE Includes
// This is just needed for i18n() and weekStartDay().
// Once I figure out how to handle i18n
// without using this macro directly, I'll be freed of KDE dependency.  This
// is a minor problem because we use these terms when rendering to HTML,
// and a more major problem because we need it to translate account types
// (e.g. MyMoneyAccount::Checkings) into their text representation.  We also
// use that text representation in the core data structure of the report. (Ace)

#include <kglobal.h>
#include <klocale.h>
#include <kdebug.h>
#include <kcalendarsystem.h>

// ----------------------------------------------------------------------------
// Project Includes

#include "pivottable.h"
#include "pivotgrid.h"
#include "reportdebug.h"
#include "kreportchartview.h"
#include "../kmymoneyglobalsettings.h"
#include "../kmymoneyutils.h"
#include "../mymoney/mymoneyforecast.h"


#include <kmymoney/kmymoneyutils.h>

namespace reports {

QString Debug::m_sTabs;
bool Debug::m_sEnabled = DEBUG_ENABLED_BY_DEFAULT;
QString Debug::m_sEnableKey;

Debug::Debug( const QString& _name ): m_methodName( _name ), m_enabled( m_sEnabled )
{
  if (!m_enabled && _name == m_sEnableKey)
    m_enabled = true;

  if (m_enabled)
  {
    qDebug( "%s%s(): ENTER", m_sTabs.latin1(), m_methodName.latin1() );
    m_sTabs.append("--");
  }
}

Debug::~Debug()
{
  if ( m_enabled )
  {
    m_sTabs.remove(0,2);
    qDebug( "%s%s(): EXIT", m_sTabs.latin1(), m_methodName.latin1() );

    if (m_methodName == m_sEnableKey)
      m_enabled = false;
  }
}

void Debug::output( const QString& _text )
{
  if ( m_enabled )
    qDebug( "%s%s(): %s", m_sTabs.latin1(), m_methodName.latin1(), _text.latin1() );
}

PivotTable::PivotTable( const MyMoneyReport& _config_f ):
  m_runningSumsCalculated(false),
  m_config_f( _config_f )
{
  init();
}

void PivotTable::init(void)
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  //
  // Initialize locals
  //

  MyMoneyFile* file = MyMoneyFile::instance();

  //
  // Initialize member variables
  //

  //make sure we have all subaccounts of investment accounts
  includeInvestmentSubAccounts();

  m_config_f.validDateRange( m_beginDate, m_endDate );

  // If we need to calculate running sums, it does not make sense
  // to show a row total column
  if ( m_config_f.isRunningSum() )
    m_config_f.setShowingRowTotals(false);

  // if this is a months-based report
  if (! m_config_f.isColumnsAreDays())
  {
    // strip out the 'days' component of the begin and end dates.
    // we're only using these variables to contain year and month.
    m_beginDate =  QDate( m_beginDate.year(), m_beginDate.month(), 1 );
    m_endDate = QDate( m_endDate.year(), m_endDate.month(), 1 );
  }

  m_numColumns = columnValue(m_endDate) - columnValue(m_beginDate) + 2;

  //Load what types of row the report is going to show
  loadRowTypeList();

  //
  // Initialize outer groups of the grid
  //
  if ( m_config_f.rowType() == MyMoneyReport::eAssetLiability )
  {
    m_grid.insert(KMyMoneyUtils::accountTypeToString(MyMoneyAccount::Asset),PivotOuterGroup(m_numColumns));
    m_grid.insert(KMyMoneyUtils::accountTypeToString(MyMoneyAccount::Liability),PivotOuterGroup(m_numColumns,PivotOuterGroup::m_kDefaultSortOrder,true /* inverted */));
  }
  else
  {
    m_grid.insert(KMyMoneyUtils::accountTypeToString(MyMoneyAccount::Income),PivotOuterGroup(m_numColumns,PivotOuterGroup::m_kDefaultSortOrder-2));
    m_grid.insert(KMyMoneyUtils::accountTypeToString(MyMoneyAccount::Expense),PivotOuterGroup(m_numColumns,PivotOuterGroup::m_kDefaultSortOrder-1,true /* inverted */));
    //
    // Create rows for income/expense reports with all accounts included
    //
    if(m_config_f.isIncludingUnusedAccounts())
      createAccountRows();
  }

  //
  // Initialize grid totals
  //

  m_grid.m_total = PivotGridRowSet(m_numColumns);

  //
  // Get opening balances
  // (for running sum reports only)
  //

  if ( m_config_f.isRunningSum() )
    calculateOpeningBalances();

  //
  // Calculate budget mapping
  // (for budget-vs-actual reports only)
  //
  if ( m_config_f.hasBudget())
    calculateBudgetMapping();

  //
  // Populate all transactions into the row/column pivot grid
  //

  QValueList<MyMoneyTransaction> transactions;
  m_config_f.setReportAllSplits(false);
  m_config_f.setConsiderCategory(true);
  try {
    transactions = file->transactionList(m_config_f);
  } catch(MyMoneyException *e) {
    qDebug("ERR: %s thrown in %s(%ld)", e->what().data(), e->file().data(), e->line());
    throw e;
  }
  DEBUG_OUTPUT(QString("Found %1 matching transactions").arg(transactions.count()));


  // Include scheduled transactions if required
  if ( m_config_f.isIncludingSchedules() )
  {
    // Create a custom version of the report filter, excluding date
    // We'll use this to compare the transaction against
    MyMoneyTransactionFilter schedulefilter(m_config_f);
    schedulefilter.setDateFilter(QDate(),QDate());

    // Get the real dates from the config filter
    QDate configbegin, configend;
    m_config_f.validDateRange(configbegin, configend);

    QValueList<MyMoneySchedule> schedules = file->scheduleList();
    QValueList<MyMoneySchedule>::const_iterator it_schedule = schedules.begin();
    while ( it_schedule != schedules.end() )
    {
      // If the transaction meets the filter
      MyMoneyTransaction tx = (*it_schedule).transaction();
      if (!(*it_schedule).isFinished() && schedulefilter.match(tx) )
      {
        // Keep the id of the schedule with the transaction so that
        // we can do the autocalc later on in case of a loan payment
        tx.setValue("kmm-schedule-id", (*it_schedule).id());

        // Get the dates when a payment will be made within the report window
        QDate nextpayment = (*it_schedule).adjustedNextPayment(configbegin);
        if ( nextpayment.isValid() )
        {
          // Add one transaction for each date
          QValueList<QDate> paymentDates = (*it_schedule).paymentDates(nextpayment,configend);
          QValueList<QDate>::const_iterator it_date = paymentDates.begin();
          while ( it_date != paymentDates.end() )
          {
            //if the payment occurs in the past, enter it tomorrow
            if(QDate::currentDate() >= *it_date) {
              tx.setPostDate(QDate::currentDate().addDays(1));
            } else {
              tx.setPostDate(*it_date);
            }
            if ( tx.postDate() <= configend
               && tx.postDate() >= configbegin ) {
              transactions += tx;
            }

            DEBUG_OUTPUT(QString("Added transaction for schedule %1 on %2").arg((*it_schedule).id()).arg((*it_date).toString()));

            ++it_date;
          }
        }
      }

      ++it_schedule;
    }
  }

  // whether asset & liability transactions are actually to be considered
  // transfers
  bool al_transfers = ( m_config_f.rowType() == MyMoneyReport::eExpenseIncome ) && ( m_config_f.isIncludingTransfers() );

  //this is to store balance for loan accounts when not included in the report
  QMap<QString, MyMoneyMoney> loanBalances;

  QValueList<MyMoneyTransaction>::const_iterator it_transaction = transactions.begin();
  unsigned colofs = columnValue(m_beginDate) - 1;
  while ( it_transaction != transactions.end() )
  {
    QDate postdate = (*it_transaction).postDate();
    unsigned column = columnValue(postdate) - colofs;

    MyMoneyTransaction tx = (*it_transaction);

    // check if we need to call the autocalculation routine
    if(tx.isLoanPayment() && tx.hasAutoCalcSplit() && (tx.value("kmm-schedule-id").length() > 0)) {
      // make sure to consider any autocalculation for loan payments
      MyMoneySchedule sched = file->schedule(tx.value("kmm-schedule-id"));
      const MyMoneySplit& split = tx.amortizationSplit();
      if(!split.id().isEmpty()) {
        ReportAccount splitAccount = file->account(split.accountId());
        MyMoneyAccount::accountTypeE type = splitAccount.accountGroup();
        QString outergroup = KMyMoneyUtils::accountTypeToString(type);

        //if the account is included in the report, calculate the balance from the cells
        if(m_config_f.includes( splitAccount )) {
          loanBalances[splitAccount.id()] = cellBalance(outergroup, splitAccount, column, false);
        } else {
          //if it is not in the report and also not in loanBalances, get the balance from the file
          if(!loanBalances.contains(splitAccount.id())) {
            QDate dueDate = sched.nextDueDate();

            //if the payment is overdue, use current date
            if(dueDate < QDate::currentDate())
              dueDate = QDate::currentDate();

            //get the balance from the file for the date
            loanBalances[splitAccount.id()] = file->balance(splitAccount.id(), dueDate.addDays(-1));
          }
        }

        KMyMoneyUtils::calculateAutoLoan(sched, tx, loanBalances);

        //if the loan split is not included in the report, update the balance for the next occurrence
        if(!m_config_f.includes( splitAccount )) {
          QValueList<MyMoneySplit>::ConstIterator it_loanSplits;
          for(it_loanSplits = tx.splits().begin(); it_loanSplits != tx.splits().end(); ++it_loanSplits) {
            if((*it_loanSplits).isAmortizationSplit() && (*it_loanSplits).accountId() == splitAccount.id() )
              loanBalances[splitAccount.id()] = loanBalances[splitAccount.id()] + (*it_loanSplits).shares();
          }
        }
      }
    }

    QValueList<MyMoneySplit> splits = tx.splits();
    QValueList<MyMoneySplit>::const_iterator it_split = splits.begin();
    while ( it_split != splits.end() )
    {
      ReportAccount splitAccount = (*it_split).accountId();

      // Each split must be further filtered, because if even one split matches,
      // the ENTIRE transaction is returned with all splits (even non-matching ones)
      if ( m_config_f.includes( splitAccount ) && m_config_f.match(&(*it_split)))
      {
        // reverse sign to match common notation for cash flow direction, only for expense/income splits
        MyMoneyMoney reverse(splitAccount.isIncomeExpense() ? -1 : 1, 1);

        MyMoneyMoney value;
        // the outer group is the account class (major account type)
        MyMoneyAccount::accountTypeE type = splitAccount.accountGroup();
        QString outergroup = KMyMoneyUtils::accountTypeToString(type);

        value = (*it_split).shares();
        bool stockSplit = tx.isStockSplit();
        if(!stockSplit) {
          // retrieve the value in the account's underlying currency
          if(value != MyMoneyMoney::autoCalc) {
            value = value * reverse;
          } else {
            qDebug("PivotTable::PivotTable(): This must not happen");
            value = MyMoneyMoney();  // keep it 0 so far
          }

          // Except in the case of transfers on an income/expense report
          if ( al_transfers && ( type == MyMoneyAccount::Asset || type == MyMoneyAccount::Liability ) )
          {
            outergroup = i18n("Transfers");
            value = -value;
          }
        }
        // add the value to its correct position in the pivot table
        assignCell( outergroup, splitAccount, column, value, false, stockSplit );
      }
      ++it_split;
    }

    ++it_transaction;
  }

  //
  // Get forecast data
  //
  if(m_config_f.isIncludingForecast())
    calculateForecast();

  //
  //Insert Price data
  //
  if(m_config_f.isIncludingPrice())
    fillBasePriceUnit(ePrice);

  //
  //Insert Average Price data
  //
  if(m_config_f.isIncludingAveragePrice()) {
    fillBasePriceUnit(eActual);
    calculateMovingAverage();
  }

  //
  // Collapse columns to match column type
  //


  if ( m_config_f.columnPitch() > 1 )
    collapseColumns();

  //
  // Calculate the running sums
  // (for running sum reports only)
  //

  if ( m_config_f.isRunningSum() )
    calculateRunningSums();

  //
  // Calculate Moving Average
  //
  if ( m_config_f.isIncludingMovingAverage() )
    calculateMovingAverage();

  //
  // Calculate Budget Difference
  //

  if ( m_config_f.isIncludingBudgetActuals() )
    calculateBudgetDiff();

  //
  // Convert all values to the deep currency
  //

  convertToDeepCurrency();

  //
  // Convert all values to the base currency
  //

  if ( m_config_f.isConvertCurrency() )
    convertToBaseCurrency();

  //
  // Determine column headings
  //

  calculateColumnHeadings();

  //
  // Calculate row and column totals
  //

  calculateTotals();
}

void PivotTable::collapseColumns(void)
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  unsigned columnpitch = m_config_f.columnPitch();
  if ( columnpitch != 1 )
  {
    unsigned sourcemonth = (m_config_f.isColumnsAreDays())
      // use the user's locale to determine the week's start
      ? (m_beginDate.dayOfWeek() + 8 - KGlobal::locale()->weekStartDay()) % 7
      : m_beginDate.month();
    unsigned sourcecolumn = 1;
    unsigned destcolumn = 1;
    while ( sourcecolumn < m_numColumns )
    {
      if ( sourcecolumn != destcolumn )
      {
#if 0
        // TODO: Clean up this rather inefficient kludge. We really should jump by an entire
        // destcolumn at a time on RS reports, and calculate the proper sourcecolumn to use,
        // allowing us to clear and accumulate only ONCE per destcolumn
        if ( m_config_f.isRunningSum() )
          clearColumn(destcolumn);
#endif
        accumulateColumn(destcolumn,sourcecolumn);
      }

      if (++sourcecolumn < m_numColumns) {
        if ((sourcemonth++ % columnpitch) == 0) {
          if (sourcecolumn != ++destcolumn)
            clearColumn (destcolumn);
        }
      }
    }
    m_numColumns = destcolumn + 1;
  }
}

void PivotTable::accumulateColumn(unsigned destcolumn, unsigned sourcecolumn)
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);
  DEBUG_OUTPUT(QString("From Column %1 to %2").arg(sourcecolumn).arg(destcolumn));

  // iterate over outer groups
  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    // iterate over inner groups
    PivotOuterGroup::iterator it_innergroup = (*it_outergroup).begin();
    while ( it_innergroup != (*it_outergroup).end() )
    {
      // iterator over rows
      PivotInnerGroup::iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
        if ( (*it_row)[eActual].count() <= sourcecolumn )
          throw new MYMONEYEXCEPTION(QString("Sourcecolumn %1 out of grid range (%2) in PivotTable::accumulateColumn").arg(sourcecolumn).arg((*it_row)[eActual].count()));
        if ( (*it_row)[eActual].count() <= destcolumn )
          throw new MYMONEYEXCEPTION(QString("Destcolumn %1 out of grid range (%2) in PivotTable::accumulateColumn").arg(sourcecolumn).arg((*it_row)[eActual].count()));

        (*it_row)[eActual][destcolumn] += (*it_row)[eActual][sourcecolumn];
        ++it_row;
      }

      ++it_innergroup;
    }
    ++it_outergroup;
  }
}

void PivotTable::clearColumn(unsigned column)
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);
  DEBUG_OUTPUT(QString("Column %1").arg(column));

  // iterate over outer groups
  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    // iterate over inner groups
    PivotOuterGroup::iterator it_innergroup = (*it_outergroup).begin();
    while ( it_innergroup != (*it_outergroup).end() )
    {
      // iterator over rows
      PivotInnerGroup::iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
        if ( (*it_row)[eActual].count() <= column )
          throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::accumulateColumn").arg(column).arg((*it_row)[eActual].count()));

        (*it_row++)[eActual][column] = PivotCell();
      }

      ++it_innergroup;
    }
    ++it_outergroup;
  }
}

void PivotTable::calculateColumnHeadings(void)
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  // one column for the opening balance
  m_columnHeadings.append( "Opening" );

  unsigned columnpitch = m_config_f.columnPitch();

  // if this is a days-based report
  if (m_config_f.isColumnsAreDays())
  {
    if ( columnpitch == 1 )
    {
      QDate columnDate = m_beginDate;
      unsigned column = 1;
      while ( column++ < m_numColumns )
      {
        QString heading = KGlobal::locale()->calendar()->monthName(columnDate.month(), columnDate.year(), true) + " " + QString::number(columnDate.day());
        columnDate = columnDate.addDays(1);
        m_columnHeadings.append( heading);
      }
    }
    else
    {
      QDate day = m_beginDate;
      QDate prv = m_beginDate;

      // use the user's locale to determine the week's start
      unsigned dow = (day.dayOfWeek() +8 -KGlobal::locale()->weekStartDay())%7;

      while (day <= m_endDate)
      {
        if (((dow % columnpitch) == 0) || (day == m_endDate))
        {
          m_columnHeadings.append(QString("%1&nbsp;%2 - %3&nbsp;%4")
            .arg(KGlobal::locale()->calendar()->monthName(prv.month(), prv.year(), true))
            .arg(prv.day())
            .arg(KGlobal::locale()->calendar()->monthName(day.month(), day.year(), true))
            .arg(day.day()));
          prv = day.addDays(1);
        }
        day = day.addDays(1);
        dow++;
      }
    }
  }

  // else it's a months-based report
  else
  {
    if ( columnpitch == 12 )
    {
      unsigned year = m_beginDate.year();
      unsigned column = 1;
      while ( column++ < m_numColumns )
        m_columnHeadings.append(QString::number(year++));
    }
    else
    {
      unsigned year = m_beginDate.year();
      bool includeyear = ( m_beginDate.year() != m_endDate.year() );
      unsigned segment = ( m_beginDate.month() - 1 ) / columnpitch;
      unsigned column = 1;
      while ( column++ < m_numColumns )
      {
        QString heading = KGlobal::locale()->calendar()->monthName(1+segment*columnpitch, 2000, true);
        if ( columnpitch != 1 )
          heading += "-" + KGlobal::locale()->calendar()->monthName((1+segment)*columnpitch, 2000, true);
        if ( includeyear )
          heading += " " + QString::number(year);
        m_columnHeadings.append( heading);
        if ( ++segment >= 12/columnpitch )
        {
          segment -= 12/columnpitch;
          ++year;
        }
      }
    }
  }
}

void PivotTable::createAccountRows(void)
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);
  MyMoneyFile* file = MyMoneyFile::instance();

  QValueList<MyMoneyAccount> accounts;
  file->accountList(accounts);

  QValueList<MyMoneyAccount>::const_iterator it_account = accounts.begin();

  while ( it_account != accounts.end() )
  {
    ReportAccount account = *it_account;

    // only include this item if its account group is included in this report
    // and if the report includes this account
    if ( m_config_f.includes( *it_account ) )
    {
      DEBUG_OUTPUT(QString("Includes account %1").arg(account.name()));

      // the row group is the account class (major account type)
      QString outergroup = KMyMoneyUtils::accountTypeToString(account.accountGroup());
      // place into the 'opening' column...
      assignCell( outergroup, account, 0, MyMoneyMoney() );
    }
    ++it_account;
  }
}

void PivotTable::calculateOpeningBalances( void )
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  // First, determine the inclusive dates of the report.  Normally, that's just
  // the begin & end dates of m_config_f.  However, if either of those dates are
  // blank, we need to use m_beginDate and/or m_endDate instead.
  QDate from = m_config_f.fromDate();
  QDate to = m_config_f.toDate();
  if ( ! from.isValid() )
    from = m_beginDate;
  if ( ! to.isValid() )
    to = m_endDate;

  MyMoneyFile* file = MyMoneyFile::instance();

  QValueList<MyMoneyAccount> accounts;
  file->accountList(accounts);

  QValueList<MyMoneyAccount>::const_iterator it_account = accounts.begin();

  while ( it_account != accounts.end() )
  {
    ReportAccount account = *it_account;

    // only include this item if its account group is included in this report
    // and if the report includes this account
    if ( m_config_f.includes( *it_account ) )
    {

      //do not include account if it is closed and it has no transactions in the report period
      if(account.isClosed()) {
        //check if the account has transactions for the report timeframe
        MyMoneyTransactionFilter filter;
        filter.addAccount(account.id());
        filter.setDateFilter(m_beginDate, m_endDate);
        filter.setReportAllSplits(false);
        QValueList<MyMoneyTransaction> transactions = file->transactionList(filter);
        //if a closed account has no transactions in that timeframe, do not include it
        if(transactions.size() == 0 ) {
          DEBUG_OUTPUT(QString("DOES NOT INCLUDE account %1").arg(account.name()));
          ++it_account;
          continue;
        }
      }

      DEBUG_OUTPUT(QString("Includes account %1").arg(account.name()));
      // the row group is the account class (major account type)
      QString outergroup = KMyMoneyUtils::accountTypeToString(account.accountGroup());

      // extract the balance of the account for the given begin date, which is
      // the opening balance plus the sum of all transactions prior to the begin
      // date

      // this is in the underlying currency
      MyMoneyMoney value = file->balance(account.id(), from.addDays(-1));

      // place into the 'opening' column...
      assignCell( outergroup, account, 0, value );
    }
    else
    {
      DEBUG_OUTPUT(QString("DOES NOT INCLUDE account %1").arg(account.name()));
    }

    ++it_account;
  }
}

void PivotTable::calculateRunningSums( PivotInnerGroup::iterator& it_row)
{
  MyMoneyMoney runningsum = it_row.data()[eActual][0].calculateRunningSum(MyMoneyMoney(0,1));
  unsigned column = 1;
  while ( column < m_numColumns )
  {
    if ( it_row.data()[eActual].count() <= column )
      throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::calculateRunningSums").arg(column).arg(it_row.data()[eActual].count()));

    runningsum = it_row.data()[eActual][column].calculateRunningSum(runningsum);

    ++column;
  }
}

void PivotTable::calculateRunningSums( void )
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  m_runningSumsCalculated = true;

  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    PivotOuterGroup::iterator it_innergroup = (*it_outergroup).begin();
    while ( it_innergroup != (*it_outergroup).end() )
    {
      PivotInnerGroup::iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
#if 0
        MyMoneyMoney runningsum = it_row.data()[0];
        unsigned column = 1;
        while ( column < m_numColumns )
        {
        if ( it_row.data()[eActual].count() <= column )
        throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::calculateRunningSums").arg(column).arg(it_row.data()[eActual].count()));

          runningsum = ( it_row.data()[eActual][column] += runningsum );

          ++column;
        }
#endif
        calculateRunningSums( it_row );
        ++it_row;
      }
      ++it_innergroup;
    }
    ++it_outergroup;
  }
}

MyMoneyMoney PivotTable::cellBalance(const QString& outergroup, const ReportAccount& _row, unsigned _column, bool budget)
{
  if(m_runningSumsCalculated) {
    qDebug("You must not call PivotTable::cellBalance() after calling PivotTable::calculateRunningSums()");
    throw new MYMONEYEXCEPTION(QString("You must not call PivotTable::cellBalance() after calling PivotTable::calculateRunningSums()"));
  }

  // for budget reports, if this is the actual value, map it to the account which
  // holds its budget
  ReportAccount row = _row;
  if ( !budget && m_config_f.hasBudget() )
  {
    QString newrow = m_budgetMap[row.id()];

    // if there was no mapping found, then the budget report is not interested
    // in this account.
    if ( newrow.isEmpty() )
      return MyMoneyMoney();

    row = newrow;
  }

  // ensure the row already exists (and its parental hierarchy)
  createRow( outergroup, row, true );

  // Determine the inner group from the top-most parent account
  QString innergroup( row.topParentName() );

  if ( m_numColumns <= _column )
    throw new MYMONEYEXCEPTION(QString("Column %1 out of m_numColumns range (%2) in PivotTable::cellBalance").arg(_column).arg(m_numColumns));
  if ( m_grid[outergroup][innergroup][row][eActual].count() <= _column )
    throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::cellBalance").arg(_column).arg(m_grid[outergroup][innergroup][row][eActual].count()));

  MyMoneyMoney balance;
  if ( budget )
    balance = m_grid[outergroup][innergroup][row][eBudget][0].cellBalance(MyMoneyMoney());
  else
    balance = m_grid[outergroup][innergroup][row][eActual][0].cellBalance(MyMoneyMoney());

  unsigned column = 1;
  while ( column < _column)
  {
    if ( m_grid[outergroup][innergroup][row][eActual].count() <= column )
      throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::cellBalance").arg(column).arg(m_grid[outergroup][innergroup][row][eActual].count()));

    balance = m_grid[outergroup][innergroup][row][eActual][column].cellBalance(balance);

    ++column;
  }

  return balance;
}


void PivotTable::calculateBudgetMapping( void )
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  MyMoneyFile* file = MyMoneyFile::instance();

  // Only do this if there is at least one budget in the file
  if ( file->countBudgets() )
  {
    // Select a budget
    //
    // It will choose the first budget in the list for the start year of the report if no budget is select
    MyMoneyBudget budget = MyMoneyBudget();
    //if no budget has been selected
    if (m_config_f.budget() == "Any" ) {
      QValueList<MyMoneyBudget> budgets = file->budgetList();
      QValueList<MyMoneyBudget>::const_iterator budgets_it = budgets.begin();
      while( budgets_it != budgets.end() ) {
        //pick the first budget that matches the report start year
        if( (*budgets_it).budgetStart().year() == QDate::currentDate().year() ) {
          budget = file->budget( (*budgets_it).id());
          break;
        }
        ++budgets_it;
      }
      //if we can't find a matching budget, take the first of the list
      if( budget.id() == "" )
        budget = budgets[0];

      //assign the budget to the report
      m_config_f.setBudget(budget.id(), m_config_f.isIncludingBudgetActuals());
    } else {
      //pick the budget selected by the user
      budget = file->budget( m_config_f.budget());
    }

    // Dump the budget
    //kdDebug(2) << "Budget " << budget.name() << ": " << endl;

    // Go through all accounts in the system to build the mapping
    QValueList<MyMoneyAccount> accounts;
    file->accountList(accounts);
    QValueList<MyMoneyAccount>::const_iterator it_account = accounts.begin();
    while ( it_account != accounts.end() )
    {
      //include only the accounts selected for the report
      if ( m_config_f.includes ( *it_account ) ) {
        QString id = ( *it_account ).id();
        QString acid = id;

        // If the budget contains this account outright
        if ( budget.contains ( id ) )
        {
          // Add it to the mapping
          m_budgetMap[acid] = id;
          // kdDebug(2) << ReportAccount(acid).debugName() << " self-maps / type =" << budget.account(id).budgetLevel() << endl;
        }
        // Otherwise, search for a parent account which includes sub-accounts
        else
        {
          //if includeBudgetActuals, include all accounts regardless of whether in budget or not
          if ( m_config_f.isIncludingBudgetActuals() ) {
            m_budgetMap[acid] = id;
            // kdDebug(2) << ReportAccount(acid).debugName() << " maps to " << ReportAccount(id).debugName() << endl;
          }
          do
          {
            id = file->account ( id ).parentAccountId();
            if ( budget.contains ( id ) )
            {
              if ( budget.account ( id ).budgetSubaccounts() )
              {
                m_budgetMap[acid] = id;
                // kdDebug(2) << ReportAccount(acid).debugName() << " maps to " << ReportAccount(id).debugName() << endl;
                break;
              }
            }
          }
          while ( ! id.isEmpty() );
        }
      }
      ++it_account;
    } // end while looping through the accounts in the file

    // Place the budget values into the budget grid
    QValueList<MyMoneyBudget::AccountGroup> baccounts = budget.getaccounts();
    QValueList<MyMoneyBudget::AccountGroup>::const_iterator it_bacc = baccounts.begin();
    while ( it_bacc != baccounts.end() )
    {
      ReportAccount splitAccount = (*it_bacc).id();

      //include the budget account only if it is included in the report
      if ( m_config_f.includes ( splitAccount ) ) {
        MyMoneyAccount::accountTypeE type = splitAccount.accountGroup();
        QString outergroup = KMyMoneyUtils::accountTypeToString(type);

        // reverse sign to match common notation for cash flow direction, only for expense/income splits
        MyMoneyMoney reverse((splitAccount.accountType() == MyMoneyAccount::Expense) ? -1 : 1, 1);

        const QMap<QDate, MyMoneyBudget::PeriodGroup>& periods = (*it_bacc).getPeriods();
        MyMoneyMoney value = (*periods.begin()).amount() * reverse;
        MyMoneyMoney price = MyMoneyMoney(1,1);
        unsigned column = 1;

        // based on the kind of budget it is, deal accordingly
        switch ( (*it_bacc).budgetLevel() )
        {
          case MyMoneyBudget::AccountGroup::eYearly:
            // divide the single yearly value by 12 and place it in each column
            value /= MyMoneyMoney(12,1);
          case MyMoneyBudget::AccountGroup::eNone:
          case MyMoneyBudget::AccountGroup::eMax:
          case MyMoneyBudget::AccountGroup::eMonthly:
            // place the single monthly value in each column of the report
            // only add the value if columns are monthly or longer
            if(m_config_f.columnType() == MyMoneyReport::eBiMonths
               || m_config_f.columnType() == MyMoneyReport::eMonths
               || m_config_f.columnType() == MyMoneyReport::eYears
               || m_config_f.columnType() == MyMoneyReport::eQuarters) {
              //value = value * MyMoneyMoney(m_config_f.columnType(), 1);

              QDate budgetDate = budget.budgetStart();
              while ( column < m_numColumns && budget.budgetStart().addYears(1) > budgetDate ) {
                //only show budget values if the budget year and the column date match
                //no currency conversion is done here because that is done for all columns later
                if(budgetDate > columnDate(column) ) {
                  ++column;
                } else {
                  if(budgetDate >= m_beginDate.addDays(-m_beginDate.day() + 1)
                    && budgetDate <= m_endDate.addDays(m_endDate.daysInMonth() - m_endDate.day() )
                    && budgetDate > (columnDate(column).addMonths(-m_config_f.columnType()))) {
                    assignCell( outergroup, splitAccount, column, value, true /*budget*/ );
                  }
                  budgetDate = budgetDate.addMonths(1);
                }
              }
            }
            break;
          case MyMoneyBudget::AccountGroup::eMonthByMonth:
          // place each value in the appropriate column
          // budget periods are supposed to come in order just like columns
          {
            QMap<QDate, MyMoneyBudget::PeriodGroup>::const_iterator it_period = periods.begin();
            while ( it_period != periods.end() && column < m_numColumns)
            {
              if((*it_period).startDate() > columnDate(column) ) {
                ++column;
              } else {
                switch(m_config_f.columnType()) {
                  case MyMoneyReport::eYears:
                  case MyMoneyReport::eBiMonths:
                  case MyMoneyReport::eQuarters:
                  case MyMoneyReport::eMonths:
                  {
                    if((*it_period).startDate() >= m_beginDate.addDays(-m_beginDate.day() + 1)
                        && (*it_period).startDate() <= m_endDate.addDays(m_endDate.daysInMonth() - m_endDate.day() )
                        && (*it_period).startDate() > (columnDate(column).addMonths(-m_config_f.columnType()))) {
                      //no currency conversion is done here because that is done for all columns later
                      value = (*it_period).amount() * reverse;
                      assignCell( outergroup, splitAccount, column, value, true /*budget*/ );
                    }
                    ++it_period;
                    break;
                  }
                  default:
                    break;
                }
              }
            }
            break;
          }
        }
      }
      ++it_bacc;
    }
  } // end if there was a budget
}

void PivotTable::convertToBaseCurrency( void )
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  int fraction = MyMoneyFile::instance()->baseCurrency().smallestAccountFraction();

  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    PivotOuterGroup::iterator it_innergroup = (*it_outergroup).begin();
    while ( it_innergroup != (*it_outergroup).end() )
    {
      PivotInnerGroup::iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
        unsigned column = 1;
        while ( column < m_numColumns )
        {
          if ( it_row.data()[eActual].count() <= column )
            throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::convertToBaseCurrency").arg(column).arg(it_row.data()[eActual].count()));

          QDate valuedate = columnDate(column);

          //get base price for that date
          MyMoneyMoney conversionfactor = it_row.key().baseCurrencyPrice(valuedate);

          for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
            if( m_rowTypeList[i] != eAverage ) {
              //calculate base value
              MyMoneyMoney oldval = it_row.data()[ m_rowTypeList[i] ][column];
              MyMoneyMoney value = (oldval * conversionfactor).reduce();

              //convert to lowest fraction
              it_row.data()[ m_rowTypeList[i] ][column] = PivotCell(value.convert(fraction));

              DEBUG_OUTPUT_IF(conversionfactor != MyMoneyMoney(1,1) ,QString("Factor of %1, value was %2, now %3").arg(conversionfactor).arg(DEBUG_SENSITIVE(oldval)).arg(DEBUG_SENSITIVE(it_row.data()[m_rowTypeList[i]][column].toDouble())));
            }
          }


          ++column;
        }
        ++it_row;
      }
      ++it_innergroup;
    }
    ++it_outergroup;
  }
}

void PivotTable::convertToDeepCurrency( void )
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);
  MyMoneyFile* file = MyMoneyFile::instance();
  
  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    PivotOuterGroup::iterator it_innergroup = (*it_outergroup).begin();
    while ( it_innergroup != (*it_outergroup).end() )
    {
      PivotInnerGroup::iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
        unsigned column = 1;
        while ( column < m_numColumns )
        {
          if ( it_row.data()[eActual].count() <= column )
            throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::convertToDeepCurrency").arg(column).arg(it_row.data()[eActual].count()));

          QDate valuedate = columnDate(column);

          //get conversion factor for the account and date
          MyMoneyMoney conversionfactor = it_row.key().deepCurrencyPrice(valuedate);

          //use the fraction relevant to the account at hand
          int fraction = it_row.key().currency().smallestAccountFraction();

          //use base currency fraction if not initialized
          if(fraction == -1)
            fraction = file->baseCurrency().smallestAccountFraction();

          //convert to deep currency
          MyMoneyMoney oldval = it_row.data()[eActual][column];
          MyMoneyMoney value = (oldval * conversionfactor).reduce();
          //reduce to lowest fraction
          it_row.data()[eActual][column] = PivotCell(value.convert(fraction));

          //convert price data
          if(m_config_f.isIncludingPrice()) {
            MyMoneyMoney oldPriceVal = it_row.data()[ePrice][column];
            MyMoneyMoney priceValue = (oldPriceVal * conversionfactor).reduce();
            it_row.data()[ePrice][column] = PivotCell(priceValue.convert(10000));
          }

          DEBUG_OUTPUT_IF(conversionfactor != MyMoneyMoney(1,1) ,QString("Factor of %1, value was %2, now %3").arg(conversionfactor).arg(DEBUG_SENSITIVE(oldval)).arg(DEBUG_SENSITIVE(it_row.data()[eActual][column].toDouble())));

          ++column;
        }
        ++it_row;
      }
      ++it_innergroup;
    }
    ++it_outergroup;
  }
}

void PivotTable::calculateTotals( void )
{
  //insert the row type that is going to be used
  for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
    m_grid.m_total[ m_rowTypeList[i] ].insert( m_grid.m_total[ m_rowTypeList[i] ].end(), m_numColumns, PivotCell() );

  //
  // Outer groups
  //

  // iterate over outer groups
  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
      (*it_outergroup).m_total[ m_rowTypeList[i] ].insert( (*it_outergroup).m_total[ m_rowTypeList[i] ].end(), m_numColumns, PivotCell() );

    //
    // Inner Groups
    //

    PivotOuterGroup::iterator it_innergroup = (*it_outergroup).begin();
    while ( it_innergroup != (*it_outergroup).end() )
    {
      for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
        (*it_innergroup).m_total[ m_rowTypeList[i] ].insert( (*it_innergroup).m_total[ m_rowTypeList[i] ].end(), m_numColumns, PivotCell() );
      //
      // Rows
      //

      PivotInnerGroup::iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
        //
        // Columns
        //

        unsigned column = 1;
        while ( column < m_numColumns )
        {
          for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
            if ( it_row.data()[ m_rowTypeList[i] ].count() <= column )
              throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::calculateTotals, row columns").arg(column).arg(it_row.data()[ m_rowTypeList[i] ].count()));
            if ( (*it_innergroup).m_total[ m_rowTypeList[i] ].count() <= column )
              throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::calculateTotals, inner group totals").arg(column).arg((*it_innergroup).m_total[ m_rowTypeList[i] ].count()));

            //calculate total
            MyMoneyMoney value = it_row.data()[ m_rowTypeList[i] ][column];
            (*it_innergroup).m_total[ m_rowTypeList[i] ][column] += value;
            (*it_row)[ m_rowTypeList[i] ].m_total += value;
          }
          ++column;
        }
        ++it_row;
      }

      //
      // Inner Row Group Totals
      //

      unsigned column = 1;
      while ( column < m_numColumns )
      {
        for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
          if ( (*it_innergroup).m_total[ m_rowTypeList[i] ].count() <= column )
            throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::calculateTotals, inner group totals").arg(column).arg((*it_innergroup).m_total[ m_rowTypeList[i] ].count()));
          if ( (*it_outergroup).m_total[ m_rowTypeList[i] ].count() <= column )
            throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::calculateTotals, outer group totals").arg(column).arg((*it_innergroup).m_total[ m_rowTypeList[i] ].count()));

          //calculate totals
          MyMoneyMoney value = (*it_innergroup).m_total[ m_rowTypeList[i] ][column];
          (*it_outergroup).m_total[ m_rowTypeList[i] ][column] += value;
          (*it_innergroup).m_total[ m_rowTypeList[i] ].m_total += value;
        }
        ++column;
      }

      ++it_innergroup;
    }

    //
    // Outer Row Group Totals
    //

    bool invert_total = (*it_outergroup).m_inverted;
    unsigned column = 1;
    while ( column < m_numColumns )
    {
      for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
        if ( m_grid.m_total[ m_rowTypeList[i] ].count() <= column )
          throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::calculateTotals, grid totals").arg(column).arg((*it_innergroup).m_total[ m_rowTypeList[i] ].count()));

      //calculate actual totals
        MyMoneyMoney value = (*it_outergroup).m_total[ m_rowTypeList[i] ][column];
        (*it_outergroup).m_total[ m_rowTypeList[i] ].m_total += value;

        //so far the invert only applies to actual and budget
        if ( invert_total
             && m_rowTypeList[i] != eBudgetDiff
             &&  m_rowTypeList[i] != eForecast)
          value = -value;

        m_grid.m_total[ m_rowTypeList[i] ][column] += value;
      }
      ++column;
    }
    ++it_outergroup;
  }

  //
  // Report Totals
  //

  unsigned totalcolumn = 1;
  while ( totalcolumn < m_numColumns )
  {
    for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
      if ( m_grid.m_total[ m_rowTypeList[i] ].count() <= totalcolumn )
        throw new MYMONEYEXCEPTION(QString("Total column %1 out of grid range (%2) in PivotTable::calculateTotals, grid totals").arg(totalcolumn).arg(m_grid.m_total[ m_rowTypeList[i] ].count()));

    //calculate actual totals
      MyMoneyMoney value = m_grid.m_total[ m_rowTypeList[i] ][totalcolumn];
      m_grid.m_total[ m_rowTypeList[i] ].m_total += value;
    }
    ++totalcolumn;
  }
}

void PivotTable::assignCell( const QString& outergroup, const ReportAccount& _row, unsigned column, MyMoneyMoney value, bool budget, bool stockSplit )
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);
  DEBUG_OUTPUT(QString("Parameters: %1,%2,%3,%4,%5").arg(outergroup).arg(_row.debugName()).arg(column).arg(DEBUG_SENSITIVE(value.toDouble())).arg(budget));

  // for budget reports, if this is the actual value, map it to the account which
  // holds its budget
  ReportAccount row = _row;
  if ( !budget && m_config_f.hasBudget() )
  {
    QString newrow = m_budgetMap[row.id()];

    // if there was no mapping found, then the budget report is not interested
    // in this account.
    if ( newrow.isEmpty() )
      return;

    row = newrow;
  }

  // ensure the row already exists (and its parental hierarchy)
  createRow( outergroup, row, true );

  // Determine the inner group from the top-most parent account
  QString innergroup( row.topParentName() );

  if ( m_numColumns <= column )
    throw new MYMONEYEXCEPTION(QString("Column %1 out of m_numColumns range (%2) in PivotTable::assignCell").arg(column).arg(m_numColumns));
  if ( m_grid[outergroup][innergroup][row][eActual].count() <= column )
    throw new MYMONEYEXCEPTION(QString("Column %1 out of grid range (%2) in PivotTable::assignCell").arg(column).arg(m_grid[outergroup][innergroup][row][eActual].count()));

  if(!stockSplit) {
    // Determine whether the value should be inverted before being placed in the row
    if ( m_grid[outergroup].m_inverted )
      value = -value;

    // Add the value to the grid cell
    if ( budget )
      m_grid[outergroup][innergroup][row][eBudget][column] += value;
    else
      m_grid[outergroup][innergroup][row][eActual][column] += value;
  } else {
    m_grid[outergroup][innergroup][row][eActual][column] += PivotCell::stockSplit(value);
  }

}

void PivotTable::createRow( const QString& outergroup, const ReportAccount& row, bool recursive )
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  // Determine the inner group from the top-most parent account
  QString innergroup( row.topParentName() );

  if ( ! m_grid.contains(outergroup) )
  {
    DEBUG_OUTPUT(QString("Adding group [%1]").arg(outergroup));
    m_grid[outergroup] = PivotOuterGroup(m_numColumns);
  }

  if ( ! m_grid[outergroup].contains(innergroup) )
  {
    DEBUG_OUTPUT(QString("Adding group [%1][%2]").arg(outergroup).arg(innergroup));
    m_grid[outergroup][innergroup] = PivotInnerGroup(m_numColumns);
  }

  if ( ! m_grid[outergroup][innergroup].contains(row) )
  {
    DEBUG_OUTPUT(QString("Adding row [%1][%2][%3]").arg(outergroup).arg(innergroup).arg(row.debugName()));
    m_grid[outergroup][innergroup][row] = PivotGridRowSet(m_numColumns);

    if ( recursive && !row.isTopLevel() )
        createRow( outergroup, row.parent(), recursive );
  }
}

unsigned PivotTable::columnValue(const QDate& _date) const
{
  if (m_config_f.isColumnsAreDays())
    return (QDate().daysTo(_date));
  else
    return (_date.year() * 12 + _date.month());
}

QDate PivotTable::columnDate(int column) const
{
  if (m_config_f.isColumnsAreDays())
    return m_beginDate.addDays( m_config_f.columnPitch() * column - 1 );
  else
    return m_beginDate.addMonths( m_config_f.columnPitch() * column ).addDays(-1);
}

QString PivotTable::renderCSV( void ) const
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  //
  // Report Title
  //

  QString result = QString("\"Report: %1\"\n").arg(m_config_f.name());
  if ( m_config_f.isConvertCurrency() )
    result += i18n("All currencies converted to %1\n").arg(MyMoneyFile::instance()->baseCurrency().name());
  else
    result += i18n("All values shown in %1 unless otherwise noted\n").arg(MyMoneyFile::instance()->baseCurrency().name());

  //
  // Table Header
  //

  result += i18n("Account");

  unsigned column = 1;
  while ( column < m_numColumns )
    result += QString(",%1").arg(QString(m_columnHeadings[column++]));

  if ( m_config_f.isShowingRowTotals() )
    result += QString(",%1").arg(i18n("Total"));

  result += "\n";

  int fraction = MyMoneyFile::instance()->baseCurrency().smallestAccountFraction();

  //
  // Outer groups
  //

  // iterate over outer groups
  PivotGrid::const_iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    //
    // Outer Group Header
    //

    result += it_outergroup.key() + "\n";

    //
    // Inner Groups
    //

    PivotOuterGroup::const_iterator it_innergroup = (*it_outergroup).begin();
    unsigned rownum = 0;
    while ( it_innergroup != (*it_outergroup).end() )
    {
      //
      // Rows
      //

      QString innergroupdata;
      PivotInnerGroup::const_iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
        ReportAccount rowname = it_row.key();
        int fraction = rowname.currency().smallestAccountFraction();

        //
        // Columns
        //

        QString rowdata;
        unsigned column = 1;

        bool isUsed = false;
        for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
          isUsed |= it_row.data()[ m_rowTypeList[i] ][0].isUsed();

        while ( column < m_numColumns ) {
          //show columns
          for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
            isUsed |= it_row.data()[ m_rowTypeList[i] ][column].isUsed();
            rowdata += QString(",\"%1\"").arg(it_row.data()[ m_rowTypeList[i] ][column].formatMoney(fraction, false));
          }
          column++;
        }

        if ( m_config_f.isShowingRowTotals() ) {
          for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
            rowdata += QString(",\"%1\"").arg((*it_row)[ m_rowTypeList[i] ].m_total.formatMoney(fraction, false));
        }

        //
        // Row Header
        //

        if(!rowname.isClosed() || isUsed) {
          innergroupdata += "\"" + QString().fill(' ',rowname.hierarchyDepth() - 1) + rowname.name();

          // if we don't convert the currencies to the base currency and the
          // current row contains a foreign currency, then we append the currency
          // to the name of the account
          if (!m_config_f.isConvertCurrency() && rowname.isForeignCurrency() )
            innergroupdata += QString(" (%1)").arg(rowname.currencyId());

          innergroupdata += "\"";

          if ( isUsed )
            innergroupdata += rowdata;

          innergroupdata += "\n";
        }
        ++it_row;
      }

      //
      // Inner Row Group Totals
      //

      bool finishrow = true;
      QString finalRow;
      bool isUsed = false;
      if ( m_config_f.detailLevel() == MyMoneyReport::eDetailAll && ((*it_innergroup).size() > 1 ))
      {
        // Print the individual rows
        result += innergroupdata;

        if ( m_config_f.isShowingColumnTotals() )
        {
          // Start the TOTALS row
          finalRow = i18n("Total");
          isUsed = true;
        }
        else
        {
          ++rownum;
          finishrow = false;
        }
      }
      else
      {
        // Start the single INDIVIDUAL ACCOUNT row
        ReportAccount rowname = (*it_innergroup).begin().key();
        isUsed |= !rowname.isClosed();

        finalRow = "\"" + QString().fill(' ',rowname.hierarchyDepth() - 1) + rowname.name();
        if (!m_config_f.isConvertCurrency() && rowname.isForeignCurrency() )
          finalRow += QString(" (%1)").arg(rowname.currencyId());
        finalRow += "\"";
      }

      // Finish the row started above, unless told not to
      if ( finishrow )
      {
        unsigned column = 1;

        for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
          isUsed |= (*it_innergroup).m_total[ m_rowTypeList[i] ][0].isUsed();

        while ( column < m_numColumns )
        {
          for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
            isUsed |= (*it_innergroup).m_total[ m_rowTypeList[i] ][column].isUsed();
            finalRow += QString(",\"%1\"").arg((*it_innergroup).m_total[ m_rowTypeList[i] ][column].formatMoney(fraction, false));
          }
          column++;
        }

        if (  m_config_f.isShowingRowTotals() ) {
          for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
            finalRow += QString(",\"%1\"").arg((*it_innergroup).m_total[ m_rowTypeList[i] ].m_total.formatMoney(fraction, false));
        }

        finalRow += "\n";
      }

      if(isUsed)
      {
        result += finalRow;
        ++rownum;
      }
      ++it_innergroup;
    }

    //
    // Outer Row Group Totals
    //

    if ( m_config_f.isShowingColumnTotals() )
    {
      result += QString("%1 %2").arg(i18n("Total")).arg(it_outergroup.key());
      unsigned column = 1;
      while ( column < m_numColumns ) {
        for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
          result += QString(",\"%1\"").arg((*it_outergroup).m_total[ m_rowTypeList[i] ][column].formatMoney(fraction, false));

        column++;
      }

      if (  m_config_f.isShowingRowTotals() ) {
        for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
          result += QString(",\"%1\"").arg((*it_outergroup).m_total[ m_rowTypeList[i] ].m_total.formatMoney(fraction, false));
      }

      result += "\n";
    }
    ++it_outergroup;
  }

  //
  // Report Totals
  //

  if ( m_config_f.isShowingColumnTotals() )
  {
    result += i18n("Grand Total");
    unsigned totalcolumn = 1;
    while ( totalcolumn < m_numColumns ) {
      for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
        result += QString(",\"%1\"").arg(m_grid.m_total[ m_rowTypeList[i] ][totalcolumn].formatMoney(fraction, false));

      totalcolumn++;
    }

    if (  m_config_f.isShowingRowTotals() ) {
      for(unsigned i = 0; i < m_rowTypeList.size(); ++i)
        result += QString(",\"%1\"").arg(m_grid.m_total[ m_rowTypeList[i] ].m_total.formatMoney(fraction, false));
    }

    result += "\n";
  }

  return result;
}

QString PivotTable::renderHTML( void ) const
{
  DEBUG_ENTER(__PRETTY_FUNCTION__);

  QString colspan = QString(" colspan=\"%1\"").arg(m_numColumns + 1 + (m_config_f.isShowingRowTotals() ? 1 : 0) );

  //
  // Report Title
  //

  QString result = QString("<h2 class=\"report\">%1</h2>\n").arg(m_config_f.name());

  //actual dates of the report
  result += QString("<div class=\"subtitle\">");
  result += i18n("Report date range", "%1 through %2").arg(KGlobal::locale()->formatDate(m_config_f.fromDate(), true)).arg(KGlobal::locale()->formatDate(m_config_f.toDate(), true));
  result += QString("</div>\n");
  result += QString("<div class=\"gap\">&nbsp;</div>\n");

  //currency conversion message
  result += QString("<div class=\"subtitle\">");
  if ( m_config_f.isConvertCurrency() )
    result += i18n("All currencies converted to %1").arg(MyMoneyFile::instance()->baseCurrency().name());
  else
    result += i18n("All values shown in %1 unless otherwise noted").arg(MyMoneyFile::instance()->baseCurrency().name());
  result += QString("</div>\n");
  result += QString("<div class=\"gap\">&nbsp;</div>\n");

  // setup a leftborder for better readability of budget vs actual reports
  QString leftborder;
  if (m_rowTypeList.size() > 1)
    leftborder = " class=\"leftborder\"";

  //
  // Table Header
  //
  result += QString("\n\n<table class=\"report\" cellspacing=\"0\">\n"
       "<thead><tr class=\"itemheader\">\n<th>%1</th>").arg(i18n("Account"));

  QString headerspan;
  int span = m_rowTypeList.size();

  headerspan = QString(" colspan=\"%1\"").arg(span);

  unsigned column = 1;
  while ( column < m_numColumns )
    result += QString("<th%1>%2</th>").arg(headerspan,QString(m_columnHeadings[column++]).replace(QRegExp(" "),"<br>"));

  if ( m_config_f.isShowingRowTotals() )
    result += QString("<th%1>%2</th>").arg(headerspan).arg(i18n("Total"));

  result += "</tr></thead>\n";

  //
  // Header for multiple columns
  //
  if ( span > 1 )
  {
    result += "<tr><td></td>";

    unsigned column = 1;
    while ( column < m_numColumns )
    {
      QString lb;
      if(column != 1)
        lb = leftborder;

      for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
        result += QString("<td%2>%1</td>")
            .arg(i18n( m_columnTypeHeaderList[i] ))
            .arg(i == 0 ? lb : QString() );
      }
      column++;
    }
    if ( m_config_f.isShowingRowTotals() ) {
      for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
        result += QString("<td%2>%1</td>")
            .arg(i18n( m_columnTypeHeaderList[i] ))
            .arg(i == 0 ? leftborder : QString() );
      }
    }
    result += "</tr>";
  }


  // Skip the body of the report if the report only calls for totals to be shown
  if ( m_config_f.detailLevel() != MyMoneyReport::eDetailTotal )
  {
    //
    // Outer groups
    //

    // Need to sort the outergroups.  They can't always be sorted by name.  So we create a list of
    // map iterators, and sort that.  Then we'll iterate through the map iterators and use those as
    // before.
    //
    // I hope this doesn't bog the performance of reports, given that we're copying the entire report
    // data.  If this is a perf hit, we could change to storing outergroup pointers, I think.
    QValueList<PivotOuterGroup> outergroups;
    PivotGrid::const_iterator it_outergroup_map = m_grid.begin();
    while ( it_outergroup_map != m_grid.end() )
    {
      outergroups.push_back(it_outergroup_map.data());

      // copy the name into the outergroup, because we will now lose any association with
      // the map iterator
      outergroups.back().m_displayName = it_outergroup_map.key();

      ++it_outergroup_map;
    }
    qHeapSort(outergroups);

    QValueList<PivotOuterGroup>::const_iterator it_outergroup = outergroups.begin();
    while ( it_outergroup != outergroups.end() )
    {
      //
      // Outer Group Header
      //

      result += QString("<tr class=\"sectionheader\"><td class=\"left\"%1>%2</td></tr>\n").arg(colspan).arg((*it_outergroup).m_displayName);

      // Skip the inner groups if the report only calls for outer group totals to be shown
      if ( m_config_f.detailLevel() != MyMoneyReport::eDetailGroup )
      {

        //
        // Inner Groups
        //

        PivotOuterGroup::const_iterator it_innergroup = (*it_outergroup).begin();
        unsigned rownum = 0;
        while ( it_innergroup != (*it_outergroup).end() )
        {
          //
          // Rows
          //

          QString innergroupdata;
          PivotInnerGroup::const_iterator it_row = (*it_innergroup).begin();
          while ( it_row != (*it_innergroup).end() )
          {
            //
            // Columns
            //

            QString rowdata;
            unsigned column = 1;
            bool isUsed = it_row.data()[eActual][0].isUsed();
            while ( column < m_numColumns )
            {
              QString lb;
              if(column != 1)
                lb = leftborder;

              for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
                rowdata += QString("<td%2>%1</td>")
                    .arg(coloredAmount(it_row.data()[ m_rowTypeList[i] ][column]))
                    .arg(i == 0 ? lb : QString());

                isUsed |= it_row.data()[ m_rowTypeList[i] ][column].isUsed();
              }

              column++;
            }

            if ( m_config_f.isShowingRowTotals() )
            {
              for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
                rowdata += QString("<td%2>%1</td>")
                    .arg(coloredAmount(it_row.data()[ m_rowTypeList[i] ].m_total))
                    .arg(i == 0 ? leftborder : QString());
              }
            }

            //
            // Row Header
            //

            ReportAccount rowname = it_row.key();

            // don't show closed accounts if they have not been used
            if(!rowname.isClosed() || isUsed) {
              innergroupdata += QString("<tr class=\"row-%1\"%2><td%3 class=\"left\" style=\"text-indent: %4.0em\">%5%6</td>")
                .arg(rownum & 0x01 ? "even" : "odd")
                .arg(rowname.isTopLevel() ? " id=\"topparent\"" : "")
                .arg("") //.arg((*it_row).m_total.isZero() ? colspan : "")  // colspan the distance if this row will be blank
                .arg(rowname.hierarchyDepth() - 1)
                .arg(rowname.name().replace(QRegExp(" "), "&nbsp;"))
                .arg((m_config_f.isConvertCurrency() || !rowname.isForeignCurrency() )?QString():QString(" (%1)").arg(rowname.currency().id()));

              // Don't print this row if it's going to be all zeros
              // TODO: Uncomment this, and deal with the case where the data
              // is zero, but the budget is non-zero
              //if ( !(*it_row).m_total.isZero() )
              innergroupdata += rowdata;

              innergroupdata += "</tr>\n";
            }

            ++it_row;
          }

          //
          // Inner Row Group Totals
          //

          bool finishrow = true;
          QString finalRow;
          bool isUsed = false;
          if ( m_config_f.detailLevel() == MyMoneyReport::eDetailAll && ((*it_innergroup).size() > 1 ))
          {
            // Print the individual rows
            result += innergroupdata;

            if ( m_config_f.isShowingColumnTotals() )
            {
              // Start the TOTALS row
              finalRow = QString("<tr class=\"row-%1\" id=\"subtotal\"><td class=\"left\">&nbsp;&nbsp;%2</td>")
                .arg(rownum & 0x01 ? "even" : "odd")
                .arg(i18n("Total"));
              // don't suppress display of totals
              isUsed = true;
            }
            else {
              finishrow = false;
              ++rownum;
            }
          }
          else
          {
            // Start the single INDIVIDUAL ACCOUNT row
            // FIXME: There is a bit of a bug here with class=leftX.  There's only a finite number
            // of classes I can define in the .CSS file, and the user can theoretically nest deeper.
            // The right solution is to use style=Xem, and calculate X.  Let's see if anyone complains
            // first :)  Also applies to the row header case above.
            // FIXED: I found it in one of my reports and changed it to the proposed method.
            // This works for me (ipwizard)
            ReportAccount rowname = (*it_innergroup).begin().key();
            isUsed |= !rowname.isClosed();
            finalRow = QString("<tr class=\"row-%1\"%2><td class=\"left\" style=\"text-indent: %3.0em;\">%5%6</td>")
              .arg(rownum & 0x01 ? "even" : "odd")
                .arg( m_config_f.detailLevel() == MyMoneyReport::eDetailAll ? "id=\"solo\"" : "" )
              .arg(rowname.hierarchyDepth() - 1)
              .arg(rowname.name().replace(QRegExp(" "), "&nbsp;"))
              .arg((m_config_f.isConvertCurrency() || !rowname.isForeignCurrency() )?QString():QString(" (%1)").arg(rowname.currency().id()));
          }

          // Finish the row started above, unless told not to
          if ( finishrow )
          {
            unsigned column = 1;
            isUsed |= (*it_innergroup).m_total[eActual][0].isUsed();
            while ( column < m_numColumns )
            {
              QString lb;
              if(column != 1)
                lb = leftborder;

              for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
                finalRow += QString("<td%2>%1</td>")
                    .arg(coloredAmount((*it_innergroup).m_total[ m_rowTypeList[i] ][column]))
                    .arg(i == 0 ? lb : QString());
                isUsed |= (*it_innergroup).m_total[ m_rowTypeList[i] ][column].isUsed();
              }

              column++;
            }

            if (  m_config_f.isShowingRowTotals() )
            {
              for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
                finalRow += QString("<td%2>%1</td>")
                    .arg(coloredAmount((*it_innergroup).m_total[ m_rowTypeList[i] ].m_total))
                    .arg(i == 0 ? leftborder : QString());
              }
            }

            finalRow += "</tr>\n";
            if(isUsed) {
              result += finalRow;
              ++rownum;
            }
          }

          ++it_innergroup;

        } // end while iterating on the inner groups

      } // end if detail level is not "group"

      //
      // Outer Row Group Totals
      //

      if ( m_config_f.isShowingColumnTotals() )
      {
        result += QString("<tr class=\"sectionfooter\"><td class=\"left\">%1&nbsp;%2</td>").arg(i18n("Total")).arg((*it_outergroup).m_displayName);
        unsigned column = 1;
        while ( column < m_numColumns )
        {
          QString lb;
          if(column != 1)
            lb = leftborder;

          for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
            result += QString("<td%2>%1</td>")
                .arg(coloredAmount((*it_outergroup).m_total[ m_rowTypeList[i] ][column]))
                .arg(i == 0 ? lb : QString());
          }

          column++;
        }

        if (  m_config_f.isShowingRowTotals() )
        {
          for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
            result += QString("<td%2>%1</td>")
                .arg(coloredAmount((*it_outergroup).m_total[ m_rowTypeList[i] ].m_total))
                .arg(i == 0 ? leftborder : QString());
          }
        }
        result += "</tr>\n";
      }

      ++it_outergroup;

    } // end while iterating on the outergroups

  } // end if detail level is not "total"

  //
  // Report Totals
  //

  if ( m_config_f.isShowingColumnTotals() )
  {
    result += QString("<tr class=\"spacer\"><td>&nbsp;</td></tr>\n");
    result += QString("<tr class=\"reportfooter\"><td class=\"left\">%1</td>").arg(i18n("Grand Total"));
    unsigned totalcolumn = 1;
    while ( totalcolumn < m_numColumns )
    {
      QString lb;
      if(totalcolumn != 1)
        lb = leftborder;

      for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
        result += QString("<td%2>%1</td>")
            .arg(coloredAmount(m_grid.m_total[ m_rowTypeList[i] ][totalcolumn]))
            .arg(i == 0 ? lb : QString());
      }

      totalcolumn++;
    }

    if (  m_config_f.isShowingRowTotals() )
    {
      for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
        result += QString("<td%2>%1</td>")
            .arg(coloredAmount(m_grid.m_total[ m_rowTypeList[i] ].m_total))
            .arg(i == 0 ? leftborder : QString());
      }
    }

    result += "</tr>\n";
  }

  result += QString("<tr class=\"spacer\"><td>&nbsp;</td></tr>\n");
  result += QString("<tr class=\"spacer\"><td>&nbsp;</td></tr>\n");
  result += "</table>\n";

  return result;
}

void PivotTable::dump( const QString& file, const QString& /* context */) const
{
  QFile g( file );
  g.open( IO_WriteOnly );
  QTextStream(&g) << renderHTML();
  g.close();
}

#ifdef HAVE_KDCHART
void PivotTable::drawChart( KReportChartView& _view ) const
{
#if 1 // make this "#if 1" if you want to play with the axis settings
  // not sure if 0 is X and 1 is Y.
  KDChartAxisParams xAxisParams, yAxisParams;
  KDChartAxisParams::deepCopy(xAxisParams, _view.params()->axisParams(0));
  KDChartAxisParams::deepCopy(yAxisParams, _view.params()->axisParams(1));

  // modify axis settings here
  xAxisParams.setAxisLabelsFontMinSize(12);
  xAxisParams.setAxisLabelsFontRelSize(20);
  yAxisParams.setAxisLabelsFontMinSize(12);
  yAxisParams.setAxisLabelsFontRelSize(20);

  _view.params()->setAxisParams( 0, xAxisParams );
  _view.params()->setAxisParams( 1, yAxisParams );

#endif
  _view.params()->setLegendFontRelSize(20);
  _view.params()->setLegendTitleFontRelSize(24);
  _view.params()->setLegendTitleText(i18n("Legend"));

  _view.params()->setAxisShowGrid(0,m_config_f.isChartGridLines());
  _view.params()->setAxisShowGrid(1,m_config_f.isChartGridLines());
  _view.params()->setPrintDataValues(m_config_f.isChartDataLabels());

  // whether to limit the chart to use series totals only.  Used for reports which only
  // show one dimension (pie).
  bool seriesTotals = false;

  // whether series (rows) are accounts (true) or months (false). This causes a lot
  // of complexity in the charts.  The problem is that circular reports work best with
  // an account in a COLUMN, while line/bar prefer it in a ROW.
  bool accountSeries = true;

  //what values should be shown
  bool showBudget = m_config_f.hasBudget();
  bool showForecast = m_config_f.isIncludingForecast();
  bool showActual = false;
  if( (m_config_f.isIncludingBudgetActuals()) || ( !showBudget && !showForecast) )
    showActual = true;

  _view.params()->setLineWidth( m_config_f.chartLineWidth() );

  switch( m_config_f.chartType() )
  {
  case MyMoneyReport::eChartNone:
  case MyMoneyReport::eChartEnd:
  case MyMoneyReport::eChartLine:
    _view.params()->setChartType( KDChartParams::Line );
    _view.params()->setAxisDatasets( 0,0 );
    break;
  case MyMoneyReport::eChartBar:
    _view.params()->setChartType( KDChartParams::Bar );
    _view.params()->setBarChartSubType( KDChartParams::BarNormal );
    break;
  case MyMoneyReport::eChartStackedBar:
    _view.params()->setChartType( KDChartParams::Bar );
    _view.params()->setBarChartSubType( KDChartParams::BarStacked );
    break;
  case MyMoneyReport::eChartPie:
    _view.params()->setChartType( KDChartParams::Pie );
    // Charts should only be 3D if this adds any information
    _view.params()->setThreeDPies( false );
    accountSeries = false;
    seriesTotals = true;
    break;
  case MyMoneyReport::eChartRing:
    _view.params()->setChartType( KDChartParams::Ring );
    _view.params()->setRelativeRingThickness( true );
    accountSeries = false;
    break;
  }

  // For onMouseOver events, we want to activate mouse tracking
  _view.setMouseTracking( true );

  //
  // In KDChart parlance, a 'series' (or row) is an account (or accountgroup, etc)
  // and an 'item' (or column) is a month
  //
  unsigned r;
  unsigned c;
  if ( accountSeries )
  {
    r = 1;
    c = m_numColumns - 1;
  }
  else
  {
    c = 1;
    r = m_numColumns - 1;
  }
  KDChartTableData data( r,c );

  // The KReportChartView widget needs to know whether the legend
  // corresponds to rows or columns
  _view.setAccountSeries( accountSeries );

  // Set up X axis labels (ie "abscissa" to use the technical term)
  QStringList& abscissaNames = _view.abscissaNames();
  abscissaNames.clear();
  if ( accountSeries )
  {
    unsigned column = 1;
    while ( column < m_numColumns ) {
      abscissaNames += QString(m_columnHeadings[column++]).replace("&nbsp;", " ");
    }
  }
  else
  {
    // we will set these up while putting in the chart values.
  }

  switch ( m_config_f.detailLevel() )
  {
    case MyMoneyReport::eDetailNone:
    case MyMoneyReport::eDetailEnd:
    case MyMoneyReport::eDetailAll:
    {
      unsigned rowNum = 0;

      // iterate over outer groups
      PivotGrid::const_iterator it_outergroup = m_grid.begin();
      while ( it_outergroup != m_grid.end() )
      {

        // iterate over inner groups
        PivotOuterGroup::const_iterator it_innergroup = (*it_outergroup).begin();
        while ( it_innergroup != (*it_outergroup).end() )
        {
          //
          // Rows
          //
          QString innergroupdata;
          PivotInnerGroup::const_iterator it_row = (*it_innergroup).begin();
          while ( it_row != (*it_innergroup).end() )
          {
            //Do not include investments accounts in the chart because they are merely container of stock and other accounts
            if( it_row.key().accountType() != MyMoneyAccount::Investment) {
              //iterate row types
              for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
                //skip the budget difference rowset
                if(m_rowTypeList[i] != eBudgetDiff ) {
                  rowNum = drawChartRowSet(rowNum, seriesTotals, accountSeries, data, it_row.data(), m_rowTypeList[i]);

                  //only show the column type in the header if there is more than one type
                  if(m_rowTypeList.size() > 1) {
                    _view.params()->setLegendText( rowNum-1, m_columnTypeHeaderList[i] + " - " + it_row.key().name() );
                  } else {
                    _view.params()->setLegendText( rowNum-1, it_row.key().name() );
                  }
                }
              }
            }
            ++it_row;
          }
          ++it_innergroup;
        }
        ++it_outergroup;
      }
    }
    break;

    case MyMoneyReport::eDetailTop:
    {
      unsigned rowNum = 0;

      // iterate over outer groups
      PivotGrid::const_iterator it_outergroup = m_grid.begin();
      while ( it_outergroup != m_grid.end() )
      {

        // iterate over inner groups
        PivotOuterGroup::const_iterator it_innergroup = (*it_outergroup).begin();
        while ( it_innergroup != (*it_outergroup).end() )
        {
          //iterate row types
          for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
            //skip the budget difference rowset
            if(m_rowTypeList[i] != eBudgetDiff ) {
              rowNum = drawChartRowSet(rowNum, seriesTotals, accountSeries, data, (*it_innergroup).m_total, m_rowTypeList[i]);

              //only show the column type in the header if there is more than one type
              if(m_rowTypeList.size() > 1) {
                _view.params()->setLegendText( rowNum-1, m_columnTypeHeaderList[i] + " - " + it_innergroup.key() );
              } else {
                _view.params()->setLegendText( rowNum-1, it_innergroup.key() );
              }
            }
          }
          ++it_innergroup;
        }
        ++it_outergroup;
      }
    }
    break;

    case MyMoneyReport::eDetailGroup:
    {
      unsigned rowNum = 0;

      // iterate over outer groups
      PivotGrid::const_iterator it_outergroup = m_grid.begin();
      while ( it_outergroup != m_grid.end() )
      {
        //iterate row types
        for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
          //skip the budget difference rowset
          if(m_rowTypeList[i] != eBudgetDiff ) {
            rowNum = drawChartRowSet(rowNum, seriesTotals, accountSeries, data, (*it_outergroup).m_total, m_rowTypeList[i]);

            //only show the column type in the header if there is more than one type
            if(m_rowTypeList.size() > 1) {
              _view.params()->setLegendText( rowNum-1, m_columnTypeHeaderList[i] + " - " + it_outergroup.key() );
            } else {
              _view.params()->setLegendText( rowNum-1, it_outergroup.key() );
            }
          }
        }
        ++it_outergroup;
      }

      //if selected, show totals too
      if (m_config_f.isShowingRowTotals())
      {
        //iterate row types
        for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
          //skip the budget difference rowset
          if(m_rowTypeList[i] != eBudgetDiff ) {
            rowNum = drawChartRowSet(rowNum, seriesTotals, accountSeries, data, m_grid.m_total, m_rowTypeList[i]);

            //only show the column type in the header if there is more than one type
            if(m_rowTypeList.size() > 1) {
              _view.params()->setLegendText( rowNum-1, m_columnTypeHeaderList[i] + " - " + i18n("Total") );
            } else {
              _view.params()->setLegendText( rowNum-1, i18n("Total") );
            }
          }
        }
      }
    }
    break;

    case MyMoneyReport::eDetailTotal:
    {
      unsigned rowNum = 0;

      //iterate row types
      for(unsigned i = 0; i < m_rowTypeList.size(); ++i) {
        //skip the budget difference rowset
        if(m_rowTypeList[i] != eBudgetDiff ) {
          rowNum = drawChartRowSet(rowNum, seriesTotals, accountSeries, data, m_grid.m_total, m_rowTypeList[i]);

          //only show the column type in the header if there is more than one type
          if(m_rowTypeList.size() > 1) {
            _view.params()->setLegendText( rowNum-1, m_columnTypeHeaderList[i] + " - " + i18n("Total") );
          } else {
            _view.params()->setLegendText( rowNum-1, i18n("Total") );
          }
        }
      }
    }
    break;
  }

  _view.setNewData(data);

  // make sure to show only the required number of fractional digits on the labels of the graph
  _view.params()->setDataValuesCalc(0, MyMoneyMoney::denomToPrec(MyMoneyFile::instance()->baseCurrency().smallestAccountFraction()));
  _view.refreshLabels();

#if 0
  // I have not been able to get this to work (ace)

  //
  // Set line to dashed for the future
  //

  if ( accountSeries )
  {
    // the first column of report which represents a date in the future, or one past the
    // last column if all columns are in the present day. Only relevant when accountSeries==true
    unsigned futurecolumn = columnValue(QDate::currentDate()) - columnValue(m_beginDate) + 1;

    // kdDebug(2) << "futurecolumn: " << futurecolumn << endl;
    // kdDebug(2) << "m_numColumns: " << m_numColumns << endl;

    // Properties for line charts whose values are in the future.
    KDChartPropertySet propSetFutureValue("future value", KDChartParams::KDCHART_PROPSET_NORMAL_DATA);
    propSetFutureValue.setLineStyle(KDChartPropertySet::OwnID, Qt::DotLine);
    const int idPropFutureValue = _view.params()->registerProperties(propSetFutureValue);

    for(int col = futurecolumn; col < m_numColumns; ++col) {
      _view.setProperty(0, col, idPropFutureValue);
    }

  }
#endif
}
#else
void PivotTable::drawChart( KReportChartView& ) const { }
#endif

unsigned PivotTable::drawChartRowSet(unsigned rowNum, const bool seriesTotals, const bool accountSeries, KDChartTableData& data, const PivotGridRowSet& rowSet, const ERowType rowType ) const
{
  //only add a row if one has been added before
  // TODO: This is inefficient. Really we should total up how many rows
  // there will be and allocate it all at once.
  if(rowNum > 0) {
    if ( accountSeries )
      data.expand( rowNum+1, m_numColumns-1 );
    else
      data.expand( m_numColumns-1, rowNum+1 );
  }

  // Columns
  if ( seriesTotals )
  {
    if ( accountSeries )
      data.setCell( rowNum, 0, rowSet[rowType].m_total.toDouble() );
    else
      data.setCell( 0, rowNum, rowSet[rowType].m_total.toDouble() );
  }
  else
  {
    unsigned column = 1;
    while ( column < m_numColumns )
    {
      if ( accountSeries )
        data.setCell( rowNum, column-1, rowSet[rowType][column].toDouble() );
      else
        data.setCell( column-1, rowNum, rowSet[rowType][column].toDouble() );
      ++column;
    }
  }

  return ++rowNum;
}

QString PivotTable::coloredAmount(const MyMoneyMoney& amount, const QString& currencySymbol, int prec) const
{
  QString result;
  if( amount.isNegative() )
    result += QString("<font color=\"rgb(%1,%2,%3)\">")
        .arg(KMyMoneyGlobalSettings::listNegativeValueColor().red())
        .arg(KMyMoneyGlobalSettings::listNegativeValueColor().green())
        .arg(KMyMoneyGlobalSettings::listNegativeValueColor().blue());
  result += amount.formatMoney(currencySymbol, prec);
  if( amount.isNegative() )
    result += QString("</font>");
  return result;
}

void PivotTable::calculateBudgetDiff(void)
{
  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    PivotOuterGroup::iterator it_innergroup = (*it_outergroup).begin();
    while ( it_innergroup != (*it_outergroup).end() )
    {
      PivotInnerGroup::iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
        unsigned column = 1;
        switch( it_row.key().accountGroup() )
        {
          case MyMoneyAccount::Income:
          case MyMoneyAccount::Asset:
            while ( column < m_numColumns ) {
              it_row.data()[eBudgetDiff][column] = it_row.data()[eActual][column] - it_row.data()[eBudget][column];
              ++column;
            }
            break;
          case MyMoneyAccount::Expense:
          case MyMoneyAccount::Liability:
            while ( column < m_numColumns ) {
              it_row.data()[eBudgetDiff][column] = it_row.data()[eBudget][column] - it_row.data()[eActual][column];
              ++column;
            }
            break;
          default:
            break;
        }
        ++it_row;
      }
      ++it_innergroup;
    }
    ++it_outergroup;
  }

}

void PivotTable::calculateForecast(void)
{
  //setup forecast
  MyMoneyForecast forecast;

  //setup forecast settings

  //since this is a net worth forecast we want to include all account even those that are not in use
  forecast.setIncludeUnusedAccounts(true);

  //setup forecast dates
  if(m_endDate > QDate::currentDate()) {
    forecast.setForecastEndDate(m_endDate);
    forecast.setForecastStartDate(QDate::currentDate());
    forecast.setForecastDays(QDate::currentDate().daysTo(m_endDate));
  } else {
    forecast.setForecastStartDate(m_beginDate);
    forecast.setForecastEndDate(m_endDate);
    forecast.setForecastDays(m_beginDate.daysTo(m_endDate) + 1);
  }

  //adjust history dates if beginning date is before today
  if(m_beginDate < QDate::currentDate()) {
    forecast.setHistoryEndDate(m_beginDate.addDays(-1));
    forecast.setHistoryStartDate(forecast.historyEndDate().addDays(-forecast.accountsCycle()*forecast.forecastCycles()));
  }

  //run forecast
  forecast.doForecast();

  //go through the data and add forecast
  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    PivotOuterGroup::iterator it_innergroup = (*it_outergroup).begin();
    while ( it_innergroup != (*it_outergroup).end() )
    {
      PivotInnerGroup::iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
        unsigned column = 1;
        QDate forecastDate = m_beginDate;
        //check whether columns are days or months
        if(m_config_f.isColumnsAreDays())
        {
          while(column < m_numColumns) {
            it_row.data()[eForecast][column] = forecast.forecastBalance(it_row.key(), forecastDate);

            forecastDate = forecastDate.addDays(1);
            ++column;
          }
        } else {
          //if columns are months
          while(column < m_numColumns) {
            //set forecastDate to last day of each month
            //TODO we really need a date manipulation util
            forecastDate = QDate(forecastDate.year(), forecastDate.month(), forecastDate.daysInMonth());
            //check that forecastDate is not over ending date
            if(forecastDate > m_endDate)
              forecastDate = m_endDate;

            //get forecast balance and set the corresponding column
            it_row.data()[eForecast][column] = forecast.forecastBalance(it_row.key(), forecastDate);

            forecastDate = forecastDate.addDays(1);
            ++column;
          }
        }
        ++it_row;
      }
      ++it_innergroup;
    }
    ++it_outergroup;
  }
}

void PivotTable::loadRowTypeList()
{
  if( (m_config_f.isIncludingBudgetActuals()) ||
       ( !m_config_f.hasBudget()
       && !m_config_f.isIncludingForecast()
       && !m_config_f.isIncludingMovingAverage()
       && !m_config_f.isIncludingPrice()
       && !m_config_f.isIncludingAveragePrice())
     ) {
    m_rowTypeList.append(eActual);
    m_columnTypeHeaderList.append(i18n("Actual"));
  }

  if (m_config_f.hasBudget()) {
    m_rowTypeList.append(eBudget);
    m_columnTypeHeaderList.append(i18n("Budget"));
  }

  if(m_config_f.isIncludingBudgetActuals()) {
    m_rowTypeList.append(eBudgetDiff);
    m_columnTypeHeaderList.append(i18n("Difference"));
  }

  if(m_config_f.isIncludingForecast()) {
    m_rowTypeList.append(eForecast);
    m_columnTypeHeaderList.append(i18n("Forecast"));
  }

  if(m_config_f.isIncludingMovingAverage()) {
    m_rowTypeList.append(eAverage);
    m_columnTypeHeaderList.append(i18n("Moving Average"));
  }

  if(m_config_f.isIncludingAveragePrice()) {
    m_rowTypeList.append(eAverage);
    m_columnTypeHeaderList.append(i18n("Moving Average Price"));
  }

  if(m_config_f.isIncludingPrice()) {
    m_rowTypeList.append(ePrice);
    m_columnTypeHeaderList.append(i18n("Price"));
  }
}


void PivotTable::calculateMovingAverage (void)
{
  int delta = m_config_f.movingAverageDays()/2;

  //go through the data and add the moving average
  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    PivotOuterGroup::iterator it_innergroup = (*it_outergroup).begin();
    while ( it_innergroup != (*it_outergroup).end() )
    {
      PivotInnerGroup::iterator it_row = (*it_innergroup).begin();
      while ( it_row != (*it_innergroup).end() )
      {
        unsigned column = 1;

        //check whether columns are days or months
        if(m_config_f.columnType() == MyMoneyReport::eDays) {
          while(column < m_numColumns) {
            MyMoneyMoney totalPrice = MyMoneyMoney( 0, 1 );

            QDate averageStart = columnDate(column).addDays(-delta);
            QDate averageEnd = columnDate(column).addDays(delta);
            for(QDate averageDate = averageStart; averageDate <= averageEnd; averageDate = averageDate.addDays(1)) {
              if(m_config_f.isConvertCurrency()) {
                totalPrice += it_row.key().deepCurrencyPrice(averageDate) * it_row.key().baseCurrencyPrice(averageDate);
              } else {
                totalPrice += it_row.key().deepCurrencyPrice(averageDate);
              }
              totalPrice = totalPrice.convert(10000);
            }

            //calculate the average price
            MyMoneyMoney averagePrice = totalPrice / MyMoneyMoney ((averageStart.daysTo(averageEnd) + 1), 1);

            //get the actual value, multiply by the average price and save that value
            MyMoneyMoney averageValue = it_row.data()[eActual][column] * averagePrice;
            it_row.data()[eAverage][column] = averageValue.convert(10000);

            ++column;
          }
        } else {
          //if columns are months
          while(column < m_numColumns) {
            QDate averageStart = columnDate(column);

            //set the right start date depending on the column type
            switch(m_config_f.columnType()) {
              case MyMoneyReport::eYears:
              {
                averageStart = QDate(columnDate(column).year(), 1, 1);
                break;
              }
              case MyMoneyReport::eBiMonths:
              {
                averageStart = QDate(columnDate(column).year(), columnDate(column).month(), 1).addMonths(-1);
                break;
              }
              case MyMoneyReport::eQuarters:
              {
                averageStart = QDate(columnDate(column).year(), columnDate(column).month(), 1).addMonths(-1);
                break;
              }
              case MyMoneyReport::eMonths:
              {
                averageStart = QDate(columnDate(column).year(), columnDate(column).month(), 1);
                break;
              }
              case MyMoneyReport::eWeeks:
              {
                averageStart = columnDate(column).addDays(-columnDate(column).dayOfWeek() + 1);
                break;
              }
              default:
                break;
            }

            //gather the actual data and calculate the average
            MyMoneyMoney totalPrice = MyMoneyMoney(0, 1);
            QDate averageEnd = columnDate(column);
            for(QDate averageDate = averageStart; averageDate <= averageEnd; averageDate = averageDate.addDays(1)) {
              if(m_config_f.isConvertCurrency()) {
                totalPrice += it_row.key().deepCurrencyPrice(averageDate) * it_row.key().baseCurrencyPrice(averageDate);
              } else {
                totalPrice += it_row.key().deepCurrencyPrice(averageDate);
              }
              totalPrice = totalPrice.convert(10000);
            }

            MyMoneyMoney averagePrice = totalPrice / MyMoneyMoney ((averageStart.daysTo(averageEnd) + 1), 1);
            MyMoneyMoney averageValue = it_row.data()[eActual][column] * averagePrice;

            //fill in the average
            it_row.data()[eAverage][column] = averageValue.convert(10000);

            ++column;
          }
        }
        ++it_row;
      }
      ++it_innergroup;
    }
    ++it_outergroup;
  }
}

void PivotTable::fillBasePriceUnit(ERowType rowType)
{
  //go through the data and add forecast
  PivotGrid::iterator it_outergroup = m_grid.begin();
  while ( it_outergroup != m_grid.end() )
  {
    PivotOuterGroup::iterator it_innergroup = ( *it_outergroup ).begin();
    while ( it_innergroup != ( *it_outergroup ).end() )
    {
      PivotInnerGroup::iterator it_row = ( *it_innergroup ).begin();
      while ( it_row != ( *it_innergroup ).end() )
      {
        unsigned column = 1;
        while ( column < m_numColumns ) {
          //insert a unit of currency for each account
          it_row.data() [rowType][column] = MyMoneyMoney ( 1, 1 );
          ++column;
        }
        ++it_row;
      }
      ++it_innergroup;
    }
    ++it_outergroup;
  }
}

void PivotTable::includeInvestmentSubAccounts()
{
  // if we're not in expert mode, we need to make sure
  // that all stock accounts for the selected investment
  // account are also selected
  QStringList accountList;
  if(m_config_f.accounts(accountList)) {
    if(!KMyMoneyGlobalSettings::expertMode()) {
      QStringList::const_iterator it_a, it_b;
      for(it_a = accountList.begin(); it_a != accountList.end(); ++it_a) {
        MyMoneyAccount acc = MyMoneyFile::instance()->account(*it_a);
        if(acc.accountType() == MyMoneyAccount::Investment) {
          for(it_b = acc.accountList().begin(); it_b != acc.accountList().end(); ++it_b) {
            if(!accountList.contains(*it_b)) {
              m_config_f.addAccount(*it_b);
            }
          }
        }
      }
    }
  }
}

} // namespace
// vim:cin:si:ai:et:ts=2:sw=2: