This file is indexed.

/usr/include/vigra/accumulator.hxx is in libvigraimpex-dev 1.10.0+dfsg-3ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
/************************************************************************/
/*                                                                      */
/*               Copyright 2011-2012 by Ullrich Koethe                  */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    The VIGRA Website is                                              */
/*        http://hci.iwr.uni-heidelberg.de/vigra/                       */
/*    Please direct questions, bug reports, and contributions to        */
/*        ullrich.koethe@iwr.uni-heidelberg.de    or                    */
/*        vigra@informatik.uni-hamburg.de                               */
/*                                                                      */
/*    Permission is hereby granted, free of charge, to any person       */
/*    obtaining a copy of this software and associated documentation    */
/*    files (the "Software"), to deal in the Software without           */
/*    restriction, including without limitation the rights to use,      */
/*    copy, modify, merge, publish, distribute, sublicense, and/or      */
/*    sell copies of the Software, and to permit persons to whom the    */
/*    Software is furnished to do so, subject to the following          */
/*    conditions:                                                       */
/*                                                                      */
/*    The above copyright notice and this permission notice shall be    */
/*    included in all copies or substantial portions of the             */
/*    Software.                                                         */
/*                                                                      */
/*    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND    */
/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   */
/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          */
/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       */
/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      */
/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      */
/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     */
/*    OTHER DEALINGS IN THE SOFTWARE.                                   */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_ACCUMULATOR_HXX
#define VIGRA_ACCUMULATOR_HXX

#ifdef _MSC_VER
#pragma warning (disable: 4503)
#endif

#include "accumulator-grammar.hxx"
#include "config.hxx"
#include "metaprogramming.hxx"
#include "bit_array.hxx"
#include "static_assert.hxx"
#include "mathutil.hxx"
#include "utilities.hxx"
#include "multi_iterator_coupled.hxx"
#include "matrix.hxx"
#include "multi_math.hxx"
#include "eigensystem.hxx"
#include "histogram.hxx"
#include <algorithm>
#include <iostream>

namespace vigra {
  
/** \defgroup FeatureAccumulators Feature Accumulators

The namespace <tt>vigra::acc</tt> provides the function \ref vigra::acc::extractFeatures() along with associated statistics functors and accumulator classes. Together, they provide a framework for efficient compution of a wide variety of statistical features, both globally for an entire image, and locally for each region defined by a label array. Many different statistics can be composed out of a small number of fundamental statistics and suitable modifiers. The user simply selects the desired statistics by means of their <i>tags</i> (see below), and a template meta-program automatically generates an efficient functor that computes exactly those statistics.

The function \ref acc::extractFeatures() "extractFeatures()" scans the data in as few passes as the selected statstics permit (usually one or two passes are sufficient). Statistics are computed by accurate incremental algorithms, whose internal state is maintained by accumulator objects. The state is updated by passing data to the accumulator one sample at a time. Accumulators are grouped within an accumulator chain. Dependencies between accumulators in the accumulator chain are automatically resolved and missing dependencies are inserted. For example, to compute the mean, you also need to count the number of samples. This allows accumulators to offload some of their computations on other accumulators, making the algorithms more efficient. Each accumulator only sees data in the appropriate pass through the data, called its "working pass". 

<b>\#include</b> \<vigra/accumulator.hxx\>

    
<b>Basic statistics:</b>
    - PowerSum<N> (computes @f$ \sum_i x_i^N @f$)
    - AbsPowerSum<N> (computes @f$ \sum_i |x_i|^N @f$)
    - Skewness, UnbiasedSkewness
    - Kurtosis, UnbiasedKurtosis
    - Minimum, Maximum
    - FlatScatterMatrix (flattened upper-triangular part of scatter matrix)
    - 4 histogram classes (see \ref histogram "below")
    - StandardQuantiles (0%, 10%, 25%, 50%, 75%, 90%, 100%)
    - ArgMinWeight, ArgMaxWeight (store data or coordinate where weight assumes its minimal or maximal value)
    - CoordinateSystem (identity matrix of appropriate size)
    
    <b>Modifiers:</b> (S is the statistc to be modified)
    - Normalization
      <table border="0">
      <tr><td> DivideByCount<S>        </td><td>  S/Count           </td></tr>
      <tr><td> RootDivideByCount<S>    </td><td>  sqrt( S/Count )     </td></tr>
      <tr><td> DivideUnbiased<S>       </td><td>  S/(Count-1)       </td></tr>
      <tr><td> RootDivideUnbiased<S> &nbsp; &nbsp;  </td><td>  sqrt( S/(Count-1) ) </td></tr>
      </table>    
    - Data preparation:
      <table border="0">
      <tr><td>  Central<S>   </td><td> substract mean before computing S </td></tr>
      <tr><td>  Principal<S> </td><td> project onto PCA eigenvectors   </td></tr>
      <tr><td>  Whitened<S> &nbsp; &nbsp;  </td><td> scale to unit variance after PCA   </td></tr>
      <tr><td>  Coord<S>        </td><td> compute S from pixel coordinates rather than from pixel values    </td></tr>
      <tr><td>  Weighted<S>     </td><td> compute weighted version of S   </td></tr>
      <tr><td>  Global<S>       </td><td> compute S globally rather than per region (per region is default if labels are given)   </td></tr>
      </table>
      
    Aliases for many important features are implemented (mainly as <tt>typedef FullName Alias</tt>). The alias names are equivalent to full names. Below are some examples for supported alias names. A full list of all available statistics and alias names can be found in the namespace reference <tt>vigra::acc</tt>. These examples also show how to compose statistics from the fundamental statistics and modifiers:
    
    <table border="0">
    <tr><th> Alias           </th><th>   Full Name                 </th></tr>
    <tr><td> Count           </td><td>  PowerSum<0>                </td></tr>
    <tr><td> Sum             </td><td>  PowerSum<1>                </td></tr>
    <tr><td> SumOfSquares    </td><td>  PowerSum<2>                </td></tr>
    <tr><td> Mean            </td><td>  DivideByCount<PowerSum<1>> </td></tr>
    <tr><td> RootMeanSquares &nbsp; </td><td>  RootDivideByCount<PowerSum<2>> </td></tr>
    <tr><td> Moment<N>       </td><td>  DivideByCount<PowerSum<N>>  </td></tr>
    <tr><td> Variance        </td><td>  DivideByCount<Central<PowerSum<2>>>  </td></tr>
    <tr><td> StdDev          </td><td>  RootDivideByCount<Central<PowerSum<2>>>  </td></tr>
    <tr><td> Covariance      </td><td>  DivideByCount<FlatScatterMatrix> </td></tr>
    <tr><td> RegionCenter    </td><td>  Coord<Mean>                </td></tr>
    <tr><td> CenterOfMass    </td><td>  Weighted<Coord<Mean>>      </td></tr>
    </table>
    
    There are a few <b>rules for composing statistics</b>:
    - modifiers can be specified in any order, but are internally transformed to standard order: Global<Weighted<Coord<normalization<data preparation<basic statistic
    - only one normalization modifier and one data preparation modifier (Central or Principal or Whitened) is permitted 
    - Count ignores all modifiers except Global and Weighted
    - Sum ignores Central and Principal, because sum would be zero
    - ArgMinWeight and ArgMaxWeight are automatically Weighted


    Here is an example how to use \ref acc::AccumulatorChain to compute statistics. (To use Weighted<> or Coord<> modifiers, see below):

    \code
    #include <vigra/multi_array.hxx>
    #include <vigra/impex.hxx>
    #include <vigra/accumulator.hxx>
    using namespace vigra::acc;
    typedef double DataType;
    int size = 1000;
    vigra::MultiArray<2, DataType> data(vigra::Shape2(size, size));
   
    AccumulatorChain<DataType, 
        Select<Variance, Mean, StdDev, Minimum, Maximum, RootMeanSquares, Skewness, Covariance> >
        a;
        
    std::cout << "passes required: " << a.passesRequired() << std::endl;
    extractFeatures(data.begin(), data.end(), a); 
    
    std::cout << "Mean: " << get<Mean>(a) << std::endl;
    std::cout << "Variance: " << get<Variance>(a) << std::endl;
    \endcode
    
    The \ref acc::AccumulatorChain object contains the selected statistics and their dependencies. Statistics have to be wrapped with \ref acc::Select. The statistics are computed with the acc::extractFeatures function and the statistics can be accessed with acc::get . 

    Rules and notes:
    - order of statistics in Select<> is arbitrary
    - up to 20 statistics in Select<>, but Select<> can be nested
    - dependencies are automatically inserted
    - duplicates are automatically removed
    - extractFeatures() does as many passes through the data as necessary
    - each accumulator only sees data in the appropriate pass (its "working pass")

    The Accumulators can also be used with vector-valued data (vigra::RGBValue, vigra::TinyVector, vigra::MultiArray or vigra::MultiArrayView):
    
    \code
    typedef vigra::RGBValue<double> DataType;
    AccumulatorChain<DataType, Select<...> > a;
    ...
    \endcode

    To compute <b>weighted statistics</b> (Weighted<>) or <b>statistics over coordinates</b> (Coord<>), the accumulator chain can be used with several coupled arrays, one for the data and another for the weights and/or the labels. "Coupled" means that statistics are computed over the corresponding elements of the involved arrays. This is internally done by means of \ref CoupledScanOrderIterator and \ref vigra::CoupledHandle which provide simultaneous access to several arrays (e.g. weight and data) and corresponding coordinates. The types of the coupled arrays are best specified by means of the helper class \ref vigra::CoupledArrays :
    
    \code 
    vigra::MultiArray<3, RGBValue<unsigned char> > data(...);
    vigra::MultiArray<3, double>                   weights(...);
    
    AccumulatorChain<CoupledArrays<3, RGBValue<unsigned char>, double>,
                     Select<...> > a;
    \endcode
    
This works likewise for label images which are needed for region statistics (see below). The indxx of the array holding data, weights, or labels respectively can be specified inside the Select wrapper. These <b>index specifiers</b> are: (INDEX is of type int)
    - DataArg<INDEX>: data are in array 'INDEX' (default INDEX=1)
    - LabelArg<INDEX>: labels are in array 'INDEX' (default INDEX=2)
    - WeightArg<INDEX>: weights are in array 'INDEX' (default INDEX=rightmost index)

Pixel coordinates are always at index 0. To collect statistics, you simply pass all arrays to the <tt>extractFeatures()</tt> function:
    \code
    using namespace vigra::acc;
    vigra::MultiArray<3, double> data(...), weights(...);
    
    AccumulatorChain<CoupledArrays<3, double, double>, // two 3D arrays for data and weights
        Select<DataArg<1>, WeightArg<2>,           // in which array to look (coordinates are always arg 0)
               Mean, Variance,                     //statistics over values  
               Coord<Mean>, Coord<Variance>,       //statistics over coordinates,
               Weighted<Mean>, Weighted<Variance>, //weighted values,
               Weighted<Coord<Mean> > > >          //weighted coordinates.
        a;
     
    extractFeatures(data, weights, a);
    \endcode
    
    This even works for a single array, which is useful if you want to combine values with coordinates. For example, to find the location of the minimum element in an array, you interpret the data as weights and select the <tt>Coord<ArgMinWeight></tt> statistic (note that the version of <tt>extractFeatures()</tt> below only works in conjunction with <tt>CoupledArrays</tt>, despite the fact that there is only one array involved):
    \code 
    using namespace vigra::acc;
    vigra::MultiArray<3, double> data(...);
    
    AccumulatorChain<CoupledArrays<3, double>,
                     Select<WeightArg<1>,           // we interprete the data as weights
                            Coord<ArgMinWeight> > > // and look for the coordinate with minimal weight
        a;
        
    extractFeatures(data, a);
    std::cout << "minimum is at " << get<Coord<ArgMinWeight> >(a) << std::endl;
    \endcode
    
    To compute <b>region statistics</b>, you use \ref acc::AccumulatorChainArray. Regions are defined by means of a label array whose elements specify the region ID of the corresponding point. Therefore, you will always need at least two arrays here, which are again best specified using the <tt>CoupledArrays</tt> helper:
    
    \code
    using namespace vigra::acc;
    vigra::MultiArray<3, double> data(...);
    vigra::MultiArray<3, int> labels(...);

    AccumulatorChainArray<CoupledArrays<3, double, int>,
        Select<DataArg<1>, LabelArg<2>,       // in which array to look (coordinates are always arg 0)
               Mean, Variance,                    //per-region statistics over values
               Coord<Mean>, Coord<Variance>,      //per-region statistics over coordinates
               Global<Mean>, Global<Variance> > > //global statistics
    a;

    a.ignoreLabel(0); //statistics will not be computed for region 0 (e.g. background)

    extractFeatures(data, labels, a);

    int regionlabel = ...;
    std::cout << get<Mean>(a, regionlabel) << std::endl; //get Mean of region with label 'regionlabel'
    \endcode

   
    In some application it will be known only at run-time which statistics have to be computed. An Accumulator with <b>run-time activation</b> is provided by the \ref acc::DynamicAccumulatorChain class. One specifies a set of statistics at compile-time and from this set one can activate the needed statistics at run-time:
  
    \code
    using namespace vigra::acc;
    vigra::MultiArray<2, double> data(...);
    DynamicAccumulatorChain<double, 
        Select<Mean, Minimum, Maximum, Variance, StdDev> > a; // at compile-time
    activate<Mean>(a);      //at run-time
    a.activate("Minimum");  //same as activate<Minimum>(a) (alias names are not recognized)
    
    extractFeatures(data.begin(), data.end(), a);
    std::cout << "Mean: " << get<Mean>(a) << std::endl;       //ok
    //std::cout << "Maximum: " << get<Maximum>(a) << std::endl; // run-time error because Maximum not activated
    \endcode
      
    Likewise, for run-time activation of region statistics, use \ref acc::DynamicAccumulatorChainArray. 

    <b>Accumulator merging</b> (e.g. for parallelization or hierarchical segmentation) is possible for many accumulators:

    \code
    using namespace vigra::acc;
    vigra::MultiArray<2, double> data(...);
    AccumulatorChain<double, Select<Mean, Variance, Skewness> > a, a1, a2;

    extractFeatures(data.begin(), data.end(), a); //process entire data set at once
    extractFeatures(data.begin(), data.begin()+data.size()/2, a1); //process first half
    extractFeatures(data.begin()+data.size()/2, data.end(), a2); //process second half
    a1 += a2; // merge: a1 now equals a0 (within numerical tolerances)
    \endcode

    Not all statistics can be merged (e.g. Principal<A> usually cannot, except for some important specializations). A statistic can be merged if the "+=" operator is supported (see the documentation of that particular statistic). If the accumulator chain only requires one pass to collect the data, it is also possible to just apply the extractFeatures() function repeatedly:

    \code
    using namespace vigra::acc;
    vigra::MultiArray<2, double> data(...);
    AccumulatorChain<double, Select<Mean, Variance> > a;

    extractFeatures(data.begin(), data.begin()+data.size()/2, a); // this works because 
    extractFeatures(data.begin()+data.size()/2, data.end(), a);   // all statistics only need pass 1
    \endcode
    
    More care is needed to merge coordinate-based statistics. By default, all coordinate statistics are computed in the local coordinate system of the current region of interest. That is, the upper left corner of the ROI has the coordinate (0, 0) by default. This behavior is not desirable when you want to merge coordinate statistics from different ROIs: then, all accumulators should use the same coordinate system, usually the global system of the entire dataset. This can be achieved by the <tt>setCoordinateOffset()</tt> function. The following code demonstrates this for the <tt>RegionCenter</tt> statistic:

    \code
    using namespace vigra;
    using namespace vigra::acc;
    
    MultiArray<2, double> data(width, height);
    MultiArray<2, int>    labels(width, height);
    
    AccumulatorChainArray<CoupledArrays<2, double, int>,
                          Select<DataArg<1>, LabelArg<2>, 
                                 RegionCenter> >
    a1, a2;
    
    // a1 is responsible for the left half of the image. The local coordinate system of this ROI 
    // happens to be identical to the global coordinate system, so the offset is zero.
    Shape2 origin(0,0);
    a1.setCoordinateOffset(origin);
    extractFeatures(data.subarray(origin, Shape2(width/2, height)), 
                    labels.subarray(origin, Shape2(width/2, height)),
                    a1);
                    
    // a2 is responsible for the right half, so the offset of the local coordinate system is (width/2, 0)
    origin = Shape2(width/2, 0);
    a2.setCoordinateOffset(origin);
    extractFeatures(data.subarray(origin, Shape2(width, height)), 
                    labels.subarray(origin, Shape2(width, height)),
                    a2);
   
    // since both accumulators worked in the same global coordinate system, we can safely merge them
    a1.merge(a2);
    \endcode
    
    When you compute region statistics in ROIs, it is sometimes desirable to use a local region labeling in each ROI. In this way, the labels of each ROI cover a consecutive range of numbers starting with 0. This can save a lot of memory, because <tt>AccumulatorChainArray</tt> internally uses dense arrays -- accumulators will be allocated for all labels from 0 to the maxmimum label, even when many of them are unused. This is avoided by a local labeling. However, this means that label 1 (say) may refer to two different regions in different ROIs. To adjust for this mismatch, you can pass a label mapping to <tt>merge()</tt> that provides a global label for each label of the accumulator to be merged. Thus, each region on the right hand side will be merged into the left-hand-side accumulator with the given <i>global</i> label. For example, let us assume that the left and right half of the image contain just one region and background. Then, the accumulators of both ROIs have the label 0 (background) and 1 (the region). Upon merging, the region from the right ROI should be given the global label 2, whereas the background should keep its label 0. This is achieved like this:
    
    \code
    std::vector<int> labelMapping(2);
    labelMapping[0] = 0;   // background keeps label 0
    labelMapping[1] = 2;   // local region 1 becomes global region 2
    
    a1.merge(a2, labelMapping);
    \endcode

    \anchor histogram
    Four kinds of <b>histograms</b> are currently implemented:
    
    <table border="0">
      <tr><td> IntegerHistogram      </td><td>   Data values are equal to bin indices   </td></tr>
      <tr><td> UserRangeHistogram    </td><td>  User provides lower and upper bounds for linear range mapping from values to indices.    </td></tr>
      <tr><td> AutoRangeHistogram    </td><td>  Range mapping bounds are defiend by minimum and maximum of the data (2 passes needed!)    </td></tr>
      <tr><td> GlobalRangeHistogram &nbsp;  </td><td>  Likewise, but use global min/max rather than region min/max as AutoRangeHistogram will </td></tr>
      </table>    
  

       
    - The number of bins is specified at compile time (as template parameter int BinCount) or at run-time (if BinCount is zero at compile time). In the first case the return type of the accumulator is TinyVector<double, BinCount> (number of bins cannot be changed). In the second case, the return type is MultiArray<1, double> and the number of bins must be set before seeing data (see example below). 
    - If UserRangeHistogram is used, the bounds for the linear range mapping from values to indices must be set before seeing data (see below).
    - Options can be set by passing an instance of HistogramOptions to the accumulator chain (same options for all histograms in the chain) or by directly calling the appropriate member functions of the accumulators.
    - Merging is supported if the range mapping of the histograms is the same.
    - Histogram accumulators have two members for outliers (left_outliers, right_outliers).

    With the StandardQuantiles class, <b>histogram quantiles</b> (0%, 10%, 25%, 50%, 75%, 90%, 100%) are computed from a given histgram using linear interpolation. The return type is TinyVector<double, 7> .

    \anchor acc_hist_options Usage:
    \code
    using namespace vigra::acc;
    typedef double DataType;
    vigra::MultiArray<2, DataType> data(...);
    
    typedef UserRangeHistogram<40> SomeHistogram;   //binCount set at compile time
    typedef UserRangeHistogram<0> SomeHistogram2; // binCount must be set at run-time
    typedef AutoRangeHistogram<0> SomeHistogram3;
    typedef StandardQuantiles<SomeHistogram3> Quantiles3;
    
    AccumulatorChain<DataType, Select<SomeHistogram, SomeHistogram2, SomeHistogram3, Quantiles3> > a;
    
    //set options for all histograms in the accumulator chain:
    vigra::HistogramOptions histogram_opt;         
    histogram_opt = histogram_opt.setBinCount(50); 
    //histogram_opt = histogram_opt.setMinMax(0.1, 0.9); // this would set min/max for all three histograms, but range bounds 
                                                         // shall be set automatically by min/max of data for SomeHistogram3
    a.setHistogramOptions(histogram_opt);  

    // set options for a specific histogram in the accumulator chain:
    getAccumulator<SomeHistogram>(a).setMinMax(0.1, 0.9); // number of bins must be set before setting min/max
    getAccumulator<SomeHistogram2>(a).setMinMax(0.0, 1.0);

    extractFeatures(data.begin(), data.end(), a);

    vigra::TinyVector<double, 40> hist = get<SomeHistogram>(a);
    vigra::MultiArray<1, double> hist2 = get<SomeHistogram2>(a);
    vigra::TinyVector<double, 7> quant = get<Quantiles3>(a);
    double right_outliers = getAccumulator<SomeHistogram>(a).right_outliers;
    \endcode


    
*/


/** This namespace contains the accumulator classes, fundamental statistics and modifiers. See \ref FeatureAccumulators for examples of usage.
*/
namespace acc {

/****************************************************************************/
/*                                                                          */
/*                             infrastructure                               */
/*                                                                          */
/****************************************************************************/

  /// \brief Wrapper for MakeTypeList that additionally performs tag standardization.

template <class T01=void, class T02=void, class T03=void, class T04=void, class T05=void,
          class T06=void, class T07=void, class T08=void, class T09=void, class T10=void,
          class T11=void, class T12=void, class T13=void, class T14=void, class T15=void,
          class T16=void, class T17=void, class T18=void, class T19=void, class T20=void>
struct Select
: public MakeTypeList<
    typename StandardizeTag<T01>::type, typename StandardizeTag<T02>::type, typename StandardizeTag<T03>::type, 
    typename StandardizeTag<T04>::type, typename StandardizeTag<T05>::type, typename StandardizeTag<T06>::type, 
    typename StandardizeTag<T07>::type, typename StandardizeTag<T08>::type, typename StandardizeTag<T09>::type, 
    typename StandardizeTag<T10>::type, typename StandardizeTag<T11>::type, typename StandardizeTag<T12>::type, 
    typename StandardizeTag<T13>::type, typename StandardizeTag<T14>::type, typename StandardizeTag<T15>::type, 
    typename StandardizeTag<T16>::type, typename StandardizeTag<T17>::type, typename StandardizeTag<T18>::type, 
    typename StandardizeTag<T19>::type, typename StandardizeTag<T20>::type
    >
{};

    // enable nesting of Select<> expressions 
template <class T01, class T02, class T03, class T04, class T05,
          class T06, class T07, class T08, class T09, class T10,
          class T11, class T12, class T13, class T14, class T15,
          class T16, class T17, class T18, class T19, class T20>
struct StandardizeTag<Select<T01, T02, T03, T04, T05,
                             T06, T07, T08, T09, T10,
                             T11, T12, T13, T14, T15,
                             T16, T17, T18, T19, T20>, 
                      Select<T01, T02, T03, T04, T05,
                             T06, T07, T08, T09, T10,
                             T11, T12, T13, T14, T15,
                             T16, T17, T18, T19, T20> >
{
    typedef typename  Select<T01, T02, T03, T04, T05,
                             T06, T07, T08, T09, T10,
                             T11, T12, T13, T14, T15,
                             T16, T17, T18, T19, T20>::type type;
};

struct AccumulatorBegin
{
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return "AccumulatorBegin (internal)";
       // static const std::string n("AccumulatorBegin (internal)");
       // return n;
    }
    
    template <class T, class BASE>
    struct Impl
    : public BASE
    {};
};


struct AccumulatorEnd;
struct DataArgTag;
struct WeightArgTag;
struct LabelArgTag;
struct CoordArgTag;
struct LabelDispatchTag;

struct Error__Global_statistics_are_only_defined_for_AccumulatorChainArray;

/** \brief Specifies index of labels in CoupledHandle. 

    LabelArg<INDEX> tells the acc::AccumulatorChainArray which index of the Handle contains the labels. (Note that coordinates are always index 0)
 */
template <int INDEX>
class LabelArg
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return std::string("LabelArg<") + asString(INDEX) + "> (internal)";
        // static const std::string n = std::string("LabelArg<") + asString(INDEX) + "> (internal)";
        // return n;
    }
    
    template <class T, class BASE>
    struct Impl
    : public BASE
    {
        typedef LabelArgTag Tag;
        typedef void value_type;
        typedef void result_type;

        static const int value = INDEX;
        static const unsigned int workInPass = 0;
    };
};

template <int INDEX>
class CoordArg
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return std::string("CoordArg<") + asString(INDEX) + "> (internal)";
        // static const std::string n = std::string("CoordArg<") + asString(INDEX) + "> (internal)";
        // return n;
    }
    
    template <class T, class BASE>
    struct Impl
    : public BASE
    {
        typedef CoordArgTag Tag;
        typedef void value_type;
        typedef void result_type;

        static const int value = INDEX;
        static const unsigned int workInPass = 0;
    };
};

template <class T, class TAG, class NEXT=AccumulatorEnd>
struct AccumulatorBase;

template <class Tag, class A>
struct LookupTag;

template <class Tag, class A, class TargetTag=typename A::Tag>
struct LookupDependency;

#ifndef _MSC_VER  // compiler bug? (causes 'ambiguous overload error')

template <class TAG, class A>
typename LookupTag<TAG, A>::reference
getAccumulator(A & a);

template <class TAG, class A>
typename LookupDependency<TAG, A>::result_type
getDependency(A const & a);

#endif

namespace acc_detail {

/****************************************************************************/
/*                                                                          */
/*                   internal tag handling meta-functions                   */
/*                                                                          */
/****************************************************************************/

    // we must make sure that Arg<INDEX> tags are at the end of the chain because 
    // all other tags potentially depend on them
template <class T>
struct PushArgTagToTail
{
    typedef T type;
};

#define VIGRA_PUSHARGTAG(TAG) \
template <int INDEX, class TAIL> \
struct PushArgTagToTail<TypeList<TAG<INDEX>, TAIL> > \
{ \
    typedef typename Push<TAIL, TypeList<TAG<INDEX> > >::type type; \
};

VIGRA_PUSHARGTAG(DataArg)
VIGRA_PUSHARGTAG(WeightArg)
VIGRA_PUSHARGTAG(CoordArg)
VIGRA_PUSHARGTAG(LabelArg)

#undef VIGRA_PUSHARGTAG

    // Insert the dependencies of the selected functors into the TypeList and sort
    // the list such that dependencies come after the functors using them. Make sure 
    // that each functor is contained only once.
template <class T>
struct AddDependencies;

template <class HEAD, class TAIL>
struct AddDependencies<TypeList<HEAD, TAIL> >
{
    typedef typename AddDependencies<TAIL>::type                                   TailWithDependencies;
    typedef typename StandardizeDependencies<HEAD>::type                           HeadDependencies;
    typedef typename AddDependencies<HeadDependencies>::type                       TransitiveHeadDependencies;
    typedef TypeList<HEAD, TransitiveHeadDependencies>                             HeadWithDependencies;
    typedef typename PushUnique<HeadWithDependencies, TailWithDependencies>::type  UnsortedDependencies;
    typedef typename PushArgTagToTail<UnsortedDependencies>::type                  type;
};

template <>
struct AddDependencies<void>
{
    typedef void type;
};

    // Helper class to activate dependencies at runtime (i.e. when activate<Tag>(accu) is called,
    // activate() must also be called for Tag's dependencies).
template <class Dependencies>
struct ActivateDependencies;

template <class HEAD, class TAIL>
struct ActivateDependencies<TypeList<HEAD, TAIL> >
{
    template <class Chain, class ActiveFlags>
    static void exec(ActiveFlags & flags)
    {
        LookupTag<HEAD, Chain>::type::activateImpl(flags);
        ActivateDependencies<TAIL>::template exec<Chain>(flags);
    }
    
    template <class Chain, class ActiveFlags, class GlobalFlags>
    static void exec(ActiveFlags & flags, GlobalFlags & gflags)
    {
        LookupTag<HEAD, Chain>::type::template activateImpl<Chain>(flags, gflags);
        ActivateDependencies<TAIL>::template exec<Chain>(flags, gflags);
    }
};

template <class HEAD, class TAIL>
struct ActivateDependencies<TypeList<Global<HEAD>, TAIL> >
{
    template <class Chain, class ActiveFlags, class GlobalFlags>
    static void exec(ActiveFlags & flags, GlobalFlags & gflags)
    {
        LookupTag<Global<HEAD>, Chain>::type::activateImpl(gflags);
        ActivateDependencies<TAIL>::template exec<Chain>(flags, gflags);
    }
};

template <>
struct ActivateDependencies<void>
{
    template <class Chain, class ActiveFlags>
    static void exec(ActiveFlags &)
    {}
    
    template <class Chain, class ActiveFlags, class GlobalFlags>
    static void exec(ActiveFlags &, GlobalFlags &)
    {}
};

template <class List>
struct SeparateGlobalAndRegionTags;

template <class HEAD, class TAIL>
struct SeparateGlobalAndRegionTags<TypeList<HEAD, TAIL> >
{
    typedef SeparateGlobalAndRegionTags<TAIL>           Inner;
    typedef TypeList<HEAD, typename Inner::RegionTags>  RegionTags;
    typedef typename Inner::GlobalTags                  GlobalTags;
};

template <class HEAD, class TAIL>
struct SeparateGlobalAndRegionTags<TypeList<Global<HEAD>, TAIL> >
{
    typedef SeparateGlobalAndRegionTags<TAIL>           Inner;
    typedef typename Inner::RegionTags                  RegionTags;
    typedef TypeList<HEAD, typename Inner::GlobalTags>  GlobalTags;
};

template <int INDEX, class TAIL>
struct SeparateGlobalAndRegionTags<TypeList<DataArg<INDEX>, TAIL> >
{
    typedef SeparateGlobalAndRegionTags<TAIL>           Inner;
    typedef TypeList<DataArg<INDEX>, typename Inner::RegionTags>  RegionTags;
    typedef TypeList<DataArg<INDEX>, typename Inner::GlobalTags>  GlobalTags;
};

template <int INDEX, class TAIL>
struct SeparateGlobalAndRegionTags<TypeList<LabelArg<INDEX>, TAIL> >
{
    typedef SeparateGlobalAndRegionTags<TAIL>           Inner;
    typedef typename Inner::RegionTags                  RegionTags;
    typedef TypeList<LabelArg<INDEX>, typename Inner::GlobalTags>  GlobalTags;
};

template <int INDEX, class TAIL>
struct SeparateGlobalAndRegionTags<TypeList<WeightArg<INDEX>, TAIL> >
{
    typedef SeparateGlobalAndRegionTags<TAIL>           Inner;
    typedef TypeList<WeightArg<INDEX>, typename Inner::RegionTags>  RegionTags;
    typedef TypeList<WeightArg<INDEX>, typename Inner::GlobalTags>  GlobalTags;
};

template <int INDEX, class TAIL>
struct SeparateGlobalAndRegionTags<TypeList<CoordArg<INDEX>, TAIL> >
{
    typedef SeparateGlobalAndRegionTags<TAIL>           Inner;
    typedef TypeList<CoordArg<INDEX>, typename Inner::RegionTags>  RegionTags;
    typedef TypeList<CoordArg<INDEX>, typename Inner::GlobalTags>  GlobalTags;
};

template <>
struct SeparateGlobalAndRegionTags<void>
{
    typedef void RegionTags;
    typedef void GlobalTags;
};

/****************************************************************************/
/*                                                                          */
/*          helper classes to handle tags at runtime via strings            */
/*                                                                          */
/****************************************************************************/

template <class Accumulators>
struct CollectAccumulatorNames;

template <class HEAD, class TAIL>
struct CollectAccumulatorNames<TypeList<HEAD, TAIL> >
{
    template <class BackInsertable>
    static void exec(BackInsertable & a, bool skipInternals=true)
    {
        if(!skipInternals || HEAD::name().find("internal") == std::string::npos)
            a.push_back(HEAD::name());
        CollectAccumulatorNames<TAIL>::exec(a, skipInternals);
    }
};

template <>
struct CollectAccumulatorNames<void>
{
    template <class BackInsertable>
    static void exec(BackInsertable & a, bool skipInternals=true)
    {}
};

template <class T>
struct ApplyVisitorToTag;

template <class HEAD, class TAIL>
struct ApplyVisitorToTag<TypeList<HEAD, TAIL> >
{
    template <class Accu, class Visitor>
    static bool exec(Accu & a, std::string const & tag, Visitor const & v)
    {
        static std::string * name = VIGRA_SAFE_STATIC(name, new std::string(normalizeString(HEAD::name())));
        if(*name == tag)
        {
            v.template exec<HEAD>(a);
            return true;
        }
        else
        {
            return ApplyVisitorToTag<TAIL>::exec(a, tag, v);
        }
    }
};

template <>
struct ApplyVisitorToTag<void>
{
    template <class Accu, class Visitor>
    static bool exec(Accu & a, std::string const & tag, Visitor const & v)
    {
        return false;
    }
};

struct ActivateTag_Visitor
{
    template <class TAG, class Accu>
    void exec(Accu & a) const
    {
        a.template activate<TAG>();
    }
};

struct TagIsActive_Visitor
{
    mutable bool result;
    
    template <class TAG, class Accu>
    void exec(Accu & a) const
    {
        result = a.template isActive<TAG>();
    }
};

/****************************************************************************/
/*                                                                          */
/*                    histogram initialization functors                     */
/*                                                                          */
/****************************************************************************/

template <class TAG>
struct SetHistogramBincount
{
    template <class Accu>
    static void exec(Accu & a, HistogramOptions const & options)
    {}
};

template <template <int> class Histogram>
struct SetHistogramBincount<Histogram<0> >
{
    template <class Accu>
    static void exec(Accu & a, HistogramOptions const & options)
    {
        a.setBinCount(options.binCount);
    }
};

template <class TAG>
struct ApplyHistogramOptions
{
    template <class Accu>
    static void exec(Accu & a, HistogramOptions const & options)
    {}
};

template <class TAG>
struct ApplyHistogramOptions<StandardQuantiles<TAG> >
{
    template <class Accu>
    static void exec(Accu & a, HistogramOptions const & options)
    {}
};

template <class TAG, template <class> class MODIFIER>
struct ApplyHistogramOptions<MODIFIER<TAG> >
: public ApplyHistogramOptions<TAG>
{};

template <>
struct ApplyHistogramOptions<IntegerHistogram<0> >
{
    template <class Accu>
    static void exec(Accu & a, HistogramOptions const & options)
    {
        SetHistogramBincount<IntegerHistogram<0> >::exec(a, options);
    }
};

template <int BinCount>
struct ApplyHistogramOptions<UserRangeHistogram<BinCount> >
{
    template <class Accu>
    static void exec(Accu & a, HistogramOptions const & options)
    {
        SetHistogramBincount<UserRangeHistogram<BinCount> >::exec(a, options);
        if(a.scale_ == 0.0 && options.validMinMax())
            a.setMinMax(options.minimum, options.maximum);
    }
};

template <int BinCount>
struct ApplyHistogramOptions<AutoRangeHistogram<BinCount> >
{
    template <class Accu>
    static void exec(Accu & a, HistogramOptions const & options)
    {
        SetHistogramBincount<AutoRangeHistogram<BinCount> >::exec(a, options);
        if(a.scale_ == 0.0 && options.validMinMax())
            a.setMinMax(options.minimum, options.maximum);
    }
};

template <int BinCount>
struct ApplyHistogramOptions<GlobalRangeHistogram<BinCount> >
{
    template <class Accu>
    static void exec(Accu & a, HistogramOptions const & options)
    {
        SetHistogramBincount<GlobalRangeHistogram<BinCount> >::exec(a, options);
        if(a.scale_ == 0.0)
        {
            if(options.validMinMax())
                a.setMinMax(options.minimum, options.maximum);
            else
                a.setRegionAutoInit(options.local_auto_init);
        }
    }
};

/****************************************************************************/
/*                                                                          */
/*                   internal accumulator chain classes                     */
/*                                                                          */
/****************************************************************************/

    // AccumulatorEndImpl has the following functionalities:
    //  * marks end of accumulator chain by the AccumulatorEnd tag
    //  * provides empty implementation of standard accumulator functions
    //  * provides active_accumulators_ flags for run-time activation of dynamic accumulators
    //  * provides is_dirty_ flags for caching accumulators
    //  * hold the GlobalAccumulatorHandle for global accumulator lookup from region accumulators
template <unsigned LEVEL, class GlobalAccumulatorHandle>
struct AccumulatorEndImpl
{
    typedef typename GlobalAccumulatorHandle::type  GlobalAccumulatorType;
    
    typedef AccumulatorEnd     Tag;
    typedef void               value_type;
    typedef bool               result_type;
    typedef BitArray<LEVEL>    AccumulatorFlags;
    
    static const unsigned int  workInPass = 0; 
    static const int           index = -1;
    static const unsigned      level = LEVEL;
    
    AccumulatorFlags            active_accumulators_;
    mutable AccumulatorFlags    is_dirty_;
    GlobalAccumulatorHandle     globalAccumulator_;
        
    template <class GlobalAccumulator>
    void setGlobalAccumulator(GlobalAccumulator const * a)
    {
        globalAccumulator_.pointer_ = a;
    }

    static std::string name()
    {
        return "AccumulatorEnd (internal)";
    }
        
    bool operator()() const { return false; }
    bool get() const { return false; }
    
    template <unsigned, class U>
    void pass(U const &) 
    {}
    
    template <unsigned, class U>
    void pass(U const &, double) 
    {}
    
    template <class U>
    void mergeImpl(U const &) 
    {}
    
    template <class U>
    void resize(U const &) 
    {}
        
    template <class U>
    void setCoordinateOffsetImpl(U const &)
    {}
    
    void activate() 
    {}
    
    bool isActive() const 
    { 
        return false;
    }
    
    template <class Flags>
    static void activateImpl(Flags &)
    {}
    
    template <class Accu, class Flags1, class Flags2>
    static void activateImpl(Flags1 &, Flags2 &)
    {}
    
    template <class Flags>
    static bool isActiveImpl(Flags const &)
    {
        return true;
    }
    
    void applyHistogramOptions(HistogramOptions const &)
    {}
    
    static unsigned int passesRequired()
    {
        return 0;
    }
    
    static unsigned int passesRequired(AccumulatorFlags const &)
    {
        return 0;
    }

    void reset()
    {
        active_accumulators_.clear();
        is_dirty_.clear();
    }
        
    template <int which>
    void setDirtyImpl() const
    {
        is_dirty_.template set<which>();
    }
    
    template <int which>
    void setCleanImpl() const
    {
        is_dirty_.template reset<which>();
    }
    
    template <int which>
    bool isDirtyImpl() const
    {
        return is_dirty_.template test<which>();
    }
};

    // DecoratorImpl implement the functionality of Decorator below
template <class A, unsigned CurrentPass, bool allowRuntimeActivation, unsigned WorkPass=A::workInPass>
struct DecoratorImpl
{
    template <class T>
    static void exec(A & a, T const & t)
    {}

    template <class T>
    static void exec(A & a, T const & t, double weight)
    {}
};

template <class A, unsigned CurrentPass>
struct DecoratorImpl<A, CurrentPass, false, CurrentPass>
{
    template <class T>
    static void exec(A & a, T const & t)
    {
        a.update(t);
    }
    
    template <class T>
    static void exec(A & a, T const & t, double weight)
    {
        a.update(t, weight);
    }

    static typename A::result_type get(A const & a)
    {
        return a();
    }

    static void mergeImpl(A & a, A const & o)
    {
        a += o;
    }

    template <class T>
    static void resize(A & a, T const & t)
    {
        a.reshape(t);
    }
    
    static void applyHistogramOptions(A & a, HistogramOptions const & options)
    {
        ApplyHistogramOptions<typename A::Tag>::exec(a, options);
    }

    static unsigned int passesRequired()
    {
        static const unsigned int A_workInPass = A::workInPass;
        return std::max(A_workInPass, A::InternalBaseType::passesRequired());
    }
};

template <class A, unsigned CurrentPass>
struct DecoratorImpl<A, CurrentPass, true, CurrentPass>
{
    static bool isActive(A const & a)
    {
        return A::isActiveImpl(getAccumulator<AccumulatorEnd>(a).active_accumulators_);
    }
    
    template <class T>
    static void exec(A & a, T const & t)
    {
        if(isActive(a))
            a.update(t);
    }

    template <class T>
    static void exec(A & a, T const & t, double weight)
    {
        if(isActive(a))
            a.update(t, weight);
    }

    static typename A::result_type get(A const & a)
    {
        if(!isActive(a))
        {
            std::string message = std::string("get(accumulator): attempt to access inactive statistic '") +
                                              A::Tag::name() + "'.";
            vigra_precondition(false, message);
        }
        return a();
    }

    static void mergeImpl(A & a, A const & o)
    {
        if(isActive(a))
            a += o;
    }

    template <class T>
    static void resize(A & a, T const & t)
    {
        if(isActive(a))
            a.reshape(t);
    }
    
    static void applyHistogramOptions(A & a, HistogramOptions const & options)
    {
        if(isActive(a))
            ApplyHistogramOptions<typename A::Tag>::exec(a, options);
    }
    
    template <class ActiveFlags>
    static unsigned int passesRequired(ActiveFlags const & flags)
    {
        static const unsigned int A_workInPass = A::workInPass;
        return A::isActiveImpl(flags)
                   ? std::max(A_workInPass, A::InternalBaseType::passesRequired(flags))
                   : A::InternalBaseType::passesRequired(flags);
    }
};

    // Generic reshape function (expands to a no-op when T has fixed shape, and to
    // the appropriate specialized call otherwise). Shape is an instance of MultiArrayShape<N>::type.
template <class T, class Shape>
void reshapeImpl(T &, Shape const &)
{}

template <class T, class Shape, class Initial>
void reshapeImpl(T &, Shape const &, Initial const & = T())
{}

template <unsigned int N, class T, class Alloc, class Shape>
void reshapeImpl(MultiArray<N, T, Alloc> & a, Shape const & s, T const & initial = T())
{
    MultiArray<N, T, Alloc>(s, initial).swap(a);
}

template <class T, class Alloc, class Shape>
void reshapeImpl(Matrix<T, Alloc> & a, Shape const & s, T const & initial = T())
{
    Matrix<T, Alloc>(s, initial).swap(a);
}

template <class T, class U>
void copyShapeImpl(T const &, U const &)   // to be used for scalars and static arrays
{}

template <unsigned int N, class T, class Alloc, class U>
void copyShapeImpl(MultiArray<N, T, Alloc> const & from, U & to) 
{
    to.reshape(from.shape());
}

template <class T, class Alloc, class U>
void copyShapeImpl(Matrix<T, Alloc> const & from, U & to) 
{
    to.reshape(from.shape());
}

template <class T, class U>
bool hasDataImpl(T const &)   // to be used for scalars and static arrays
{
    return true;
}

template <unsigned int N, class T, class Stride>
bool hasDataImpl(MultiArrayView<N, T, Stride> const & a) 
{
    return a.hasData();
}

    // generic functions to create suitable shape objects from various input data types 
template <unsigned int N, class T, class Stride>
inline typename MultiArrayShape<N>::type
shapeOf(MultiArrayView<N, T, Stride> const & a)
{
    return a.shape();
}

template <class T, int N>
inline Shape1
shapeOf(TinyVector<T, N> const &)
{
    return Shape1(N);
}

template <class T, class NEXT>
inline CoupledHandle<T, NEXT> const &
shapeOf(CoupledHandle<T, NEXT> const & t)
{
    return t;
}

#define VIGRA_SHAPE_OF(type) \
inline Shape1 \
shapeOf(type) \
{ \
    return Shape1(1); \
}

VIGRA_SHAPE_OF(unsigned char)
VIGRA_SHAPE_OF(signed char)
VIGRA_SHAPE_OF(unsigned short)
VIGRA_SHAPE_OF(short)
VIGRA_SHAPE_OF(unsigned int)
VIGRA_SHAPE_OF(int)
VIGRA_SHAPE_OF(unsigned long)
VIGRA_SHAPE_OF(long)
VIGRA_SHAPE_OF(unsigned long long)
VIGRA_SHAPE_OF(long long)
VIGRA_SHAPE_OF(float)
VIGRA_SHAPE_OF(double)
VIGRA_SHAPE_OF(long double)

#undef VIGRA_SHAPE_OF

    // LabelDispatch is only used in AccumulatorChainArrays and has the following functionalities:
    //  * hold an accumulator chain for global statistics
    //  * hold an array of accumulator chains (one per region) for region statistics
    //  * forward data to the appropriate chains
    //  * allocate the region array with appropriate size
    //  * store and forward activation requests
    //  * compute required number of passes as maximum from global and region accumulators
template <class T, class GlobalAccumulators, class RegionAccumulators>
struct LabelDispatch
{
    typedef LabelDispatchTag Tag;
    typedef GlobalAccumulators GlobalAccumulatorChain;
    typedef RegionAccumulators RegionAccumulatorChain;
    typedef typename LookupTag<AccumulatorEnd, RegionAccumulatorChain>::type::AccumulatorFlags ActiveFlagsType;
    typedef ArrayVector<RegionAccumulatorChain> RegionAccumulatorArray;
        
    typedef LabelDispatch type;
    typedef LabelDispatch & reference;
    typedef LabelDispatch const & const_reference;
    typedef GlobalAccumulatorChain InternalBaseType;
    
    typedef T const & argument_type;
    typedef argument_type first_argument_type;
    typedef double second_argument_type;
    typedef RegionAccumulatorChain & result_type;
    
    static const int index = GlobalAccumulatorChain::index + 1;
    
    template <class IndexDefinition, class TagFound=typename IndexDefinition::Tag>
    struct CoordIndexSelector
    {
        static const int value = 0; // default: CoupledHandle holds coordinates at index 0 
    };
    
    template <class IndexDefinition>
    struct CoordIndexSelector<IndexDefinition, CoordArgTag>
    {
        static const int value = IndexDefinition::value;
    };
    
    static const int coordIndex = CoordIndexSelector<typename LookupTag<CoordArgTag, GlobalAccumulatorChain>::type>::value;
    static const int coordSize  = CoupledHandleCast<coordIndex, T>::type::value_type::static_size;
    typedef TinyVector<double, coordSize> CoordinateType;
    
    GlobalAccumulatorChain next_;
    RegionAccumulatorArray regions_;
    HistogramOptions region_histogram_options_;
    MultiArrayIndex ignore_label_;
    ActiveFlagsType active_region_accumulators_;
    CoordinateType coordinateOffset_;
    
    template <class IndexDefinition, class TagFound=typename IndexDefinition::Tag>
    struct LabelIndexSelector
    {
        static const int value = 2; // default: CoupledHandle holds labels at index 2

        template <class U, class NEXT>
        static MultiArrayIndex exec(CoupledHandle<U, NEXT> const & t)
        {
            return (MultiArrayIndex)get<value>(t); 
        }
    };
    
    template <class IndexDefinition>
    struct LabelIndexSelector<IndexDefinition, LabelArgTag>
    {
        static const int value = IndexDefinition::value;

        template <class U, class NEXT>
        static MultiArrayIndex exec(CoupledHandle<U, NEXT> const & t)
        {
            return (MultiArrayIndex)get<value>(t);
        }
    };
    
    template <class TAG>
    struct ActivateImpl
    {
        typedef typename LookupTag<TAG, type>::type TargetAccumulator;
        
        static void activate(GlobalAccumulatorChain & globals, RegionAccumulatorArray & regions, 
                             ActiveFlagsType & flags)
        {
            TargetAccumulator::template activateImpl<LabelDispatch>(
                      flags, getAccumulator<AccumulatorEnd>(globals).active_accumulators_);
            for(unsigned int k=0; k<regions.size(); ++k)
                getAccumulator<AccumulatorEnd>(regions[k]).active_accumulators_ = flags;
        }
        
        static bool isActive(GlobalAccumulatorChain const &, ActiveFlagsType const & flags)
        {
            return TargetAccumulator::isActiveImpl(flags);
        }
    };
    
    template <class TAG>
    struct ActivateImpl<Global<TAG> >
    {
        static void activate(GlobalAccumulatorChain & globals, RegionAccumulatorArray &, ActiveFlagsType &)
        {
            LookupTag<TAG, GlobalAccumulatorChain>::type::activateImpl(getAccumulator<AccumulatorEnd>(globals).active_accumulators_);
        }
        
        static bool isActive(GlobalAccumulatorChain const & globals, ActiveFlagsType const &)
        {
            return LookupTag<TAG, GlobalAccumulatorChain>::type::isActiveImpl(getAccumulator<AccumulatorEnd>(globals).active_accumulators_);
        }
    };
    
    template <int INDEX>
    struct ActivateImpl<LabelArg<INDEX> >
    {
        static void activate(GlobalAccumulatorChain &, RegionAccumulatorArray &, ActiveFlagsType &)
        {}
        
        static bool isActive(GlobalAccumulatorChain const & globals, ActiveFlagsType const &)
        {
            return getAccumulator<LabelArg<INDEX> >(globals).isActive();
        }
    };
    
    typedef typename LookupTag<LabelArgTag, GlobalAccumulatorChain>::type FindLabelIndex;
    
    LabelDispatch()
    : next_(),
      regions_(),
      region_histogram_options_(),
      ignore_label_(-1),
      active_region_accumulators_()
    {}
    
    LabelDispatch(LabelDispatch const & o)
    : next_(o.next_),
      regions_(o.regions_),
      region_histogram_options_(o.region_histogram_options_),
      ignore_label_(o.ignore_label_),
      active_region_accumulators_(o.active_region_accumulators_)
    {
        for(unsigned int k=0; k<regions_.size(); ++k)
        {
            getAccumulator<AccumulatorEnd>(regions_[k]).setGlobalAccumulator(&next_);
        }
    }
    
    MultiArrayIndex maxRegionLabel() const
    {
        return (MultiArrayIndex)regions_.size() - 1;
    }
    
    void setMaxRegionLabel(unsigned maxlabel)
    {
        if(maxRegionLabel() == (MultiArrayIndex)maxlabel)
            return;
        unsigned int oldSize = regions_.size();
        regions_.resize(maxlabel + 1);
        for(unsigned int k=oldSize; k<regions_.size(); ++k)
        {
            getAccumulator<AccumulatorEnd>(regions_[k]).setGlobalAccumulator(&next_);
            getAccumulator<AccumulatorEnd>(regions_[k]).active_accumulators_ = active_region_accumulators_;
            regions_[k].applyHistogramOptions(region_histogram_options_);
            regions_[k].setCoordinateOffsetImpl(coordinateOffset_);
        }
    }
    
    void ignoreLabel(MultiArrayIndex l)
    {
        ignore_label_ = l;
    }
    
    void applyHistogramOptions(HistogramOptions const & options)
    {
        applyHistogramOptions(options, options);
    }
    
    void applyHistogramOptions(HistogramOptions const & regionoptions, HistogramOptions const & globaloptions)
    {
        region_histogram_options_ = regionoptions;
        for(unsigned int k=0; k<regions_.size(); ++k)
        {
            regions_[k].applyHistogramOptions(region_histogram_options_);
        }
        next_.applyHistogramOptions(globaloptions);
    }
    
    void setCoordinateOffsetImpl(CoordinateType const & offset)
    {
        coordinateOffset_ = offset;
        for(unsigned int k=0; k<regions_.size(); ++k)
        {
            regions_[k].setCoordinateOffsetImpl(coordinateOffset_);
        }
        next_.setCoordinateOffsetImpl(coordinateOffset_);
    }
    
    template <class U>
    void resize(U const & t)
    {
        if(regions_.size() == 0)
        {
            static const int labelIndex = LabelIndexSelector<FindLabelIndex>::value;
            typedef typename CoupledHandleCast<labelIndex, T>::type LabelHandle;
            typedef typename LabelHandle::value_type LabelType;
            typedef MultiArrayView<LabelHandle::dimensions, LabelType, StridedArrayTag> LabelArray;
            LabelArray labelArray(t.shape(), cast<labelIndex>(t).strides(), const_cast<LabelType *>(cast<labelIndex>(t).ptr()));
            
            LabelType minimum, maximum;
            labelArray.minmax(&minimum, &maximum);
            setMaxRegionLabel(maximum);
        }
        next_.resize(t);
        // FIXME: only call resize when label k actually exists?
        for(unsigned int k=0; k<regions_.size(); ++k)
            regions_[k].resize(t);
    }
    
    template <unsigned N>
    void pass(T const & t)
    {
        if(LabelIndexSelector<FindLabelIndex>::exec(t) != ignore_label_)
        {
            next_.template pass<N>(t);
            regions_[LabelIndexSelector<FindLabelIndex>::exec(t)].template pass<N>(t);
        }
    }
    
    template <unsigned N>
    void pass(T const & t, double weight)
    {
        if(LabelIndexSelector<FindLabelIndex>::exec(t) != ignore_label_)
        {
            next_.template pass<N>(t, weight);
            regions_[LabelIndexSelector<FindLabelIndex>::exec(t)].template pass<N>(t, weight);
        }
    }
    
    static unsigned int passesRequired()
    {
        return std::max(GlobalAccumulatorChain::passesRequired(), RegionAccumulatorChain::passesRequired());
    }
    
    unsigned int passesRequiredDynamic() const
    {
        return std::max(GlobalAccumulatorChain::passesRequired(getAccumulator<AccumulatorEnd>(next_).active_accumulators_), 
                        RegionAccumulatorChain::passesRequired(active_region_accumulators_));
    }
    
    void reset()
    {
        next_.reset();
        
        active_region_accumulators_.clear();
        RegionAccumulatorArray().swap(regions_);
        // FIXME: or is it better to just reset the region accumulators?
        // for(unsigned int k=0; k<regions_.size(); ++k)
            // regions_[k].reset();
    }
    
    template <class TAG>
    void activate()
    {
        ActivateImpl<TAG>::activate(next_, regions_, active_region_accumulators_);
    }
    
    void activateAll()
    {
        getAccumulator<AccumulatorEnd>(next_).active_accumulators_.set();
        active_region_accumulators_.set();
        for(unsigned int k=0; k<regions_.size(); ++k)
            getAccumulator<AccumulatorEnd>(regions_[k]).active_accumulators_.set();
    }
    
    template <class TAG>
    bool isActive() const
    {
        return ActivateImpl<TAG>::isActive(next_, active_region_accumulators_);
    }
    
    void mergeImpl(LabelDispatch const & o)
    {
        for(unsigned int k=0; k<regions_.size(); ++k)
            regions_[k].mergeImpl(o.regions_[k]);
        next_.mergeImpl(o.next_);
    }
    
    void mergeImpl(unsigned i, unsigned j)
    {
        regions_[i].mergeImpl(regions_[j]);
        regions_[j].reset();
        getAccumulator<AccumulatorEnd>(regions_[j]).active_accumulators_ = active_region_accumulators_;
    }
    
    template <class ArrayLike>
    void mergeImpl(LabelDispatch const & o, ArrayLike const & labelMapping)
    {
        MultiArrayIndex newMaxLabel = std::max<MultiArrayIndex>(maxRegionLabel(), *argMax(labelMapping.begin(), labelMapping.end()));
        setMaxRegionLabel(newMaxLabel);
        for(unsigned int k=0; k<labelMapping.size(); ++k)
            regions_[labelMapping[k]].mergeImpl(o.regions_[k]);
        next_.mergeImpl(o.next_);
    }
};

template <class TargetTag, class TagList>
struct FindNextTag;

template <class TargetTag, class HEAD, class TAIL>
struct FindNextTag<TargetTag, TypeList<HEAD, TAIL> >
{
    typedef typename FindNextTag<TargetTag, TAIL>::type type;
};

template <class TargetTag, class TAIL>
struct FindNextTag<TargetTag, TypeList<TargetTag, TAIL> >
{
    typedef typename TAIL::Head type;
};

template <class TargetTag>
struct FindNextTag<TargetTag, TypeList<TargetTag, void> >
{
    typedef void type;
};

template <class TargetTag>
struct FindNextTag<TargetTag, void>
{
    typedef void type;
};

    // AccumulatorFactory creates the decorator hierarchy for the given TAG and configuration CONFIG
template <class TAG, class CONFIG, unsigned LEVEL=0>
struct AccumulatorFactory
{
    typedef typename FindNextTag<TAG, typename CONFIG::TagList>::type NextTag;
    typedef typename AccumulatorFactory<NextTag, CONFIG, LEVEL+1>::type NextType;
    typedef typename CONFIG::InputType InputType;
    
    template <class T>
    struct ConfigureTag
    {
        typedef TAG type;
    };
    
        // When InputType is a CoupledHandle, some tags need to be wrapped into 
        // DataFromHandle<> and/or Weighted<> modifiers. The following code does
        // this when appropriate.
    template <class T, class NEXT>
    struct ConfigureTag<CoupledHandle<T, NEXT> >
    {
        typedef typename StandardizeTag<DataFromHandle<TAG> >::type WrappedTag;
        typedef typename IfBool<(!HasModifierPriority<WrappedTag, WeightingPriority>::value && ShouldBeWeighted<WrappedTag>::value),
                                 Weighted<WrappedTag>, WrappedTag>::type type;
    };
    
    typedef typename ConfigureTag<InputType>::type UseTag;
    
        // base class of the decorator hierarchy: default (possibly empty) 
        // implementations of all members
    struct AccumulatorBase
    {
        typedef AccumulatorBase              ThisType;
        typedef TAG                          Tag;
        typedef NextType                     InternalBaseType;
        typedef InputType                    input_type;
        typedef input_type const &           argument_type;
        typedef argument_type                first_argument_type;
        typedef double                       second_argument_type;
        typedef void                         result_type;
        
        static const unsigned int            workInPass = 1;
        static const int                     index = InternalBaseType::index + 1;
        
        InternalBaseType next_;
        
        static std::string name()
        {
            return TAG::name();
        }
        
        template <class ActiveFlags>
        static void activateImpl(ActiveFlags & flags)
        {
            flags.template set<index>();
            typedef typename StandardizeDependencies<Tag>::type StdDeps;
            acc_detail::ActivateDependencies<StdDeps>::template exec<ThisType>(flags);
        }
        
        template <class Accu, class ActiveFlags, class GlobalFlags>
        static void activateImpl(ActiveFlags & flags, GlobalFlags & gflags)
        {
            flags.template set<index>();
            typedef typename StandardizeDependencies<Tag>::type StdDeps;
            acc_detail::ActivateDependencies<StdDeps>::template exec<Accu>(flags, gflags);
        }
        
        template <class ActiveFlags>
        static bool isActiveImpl(ActiveFlags & flags)
        {
            return flags.template test<index>();
        }
        
        void setDirty() const
        {
            next_.template setDirtyImpl<index>();
        }
        
        template <int INDEX>
        void setDirtyImpl() const
        {
            next_.template setDirtyImpl<INDEX>();
        }
        
        void setClean() const
        {
            next_.template setCleanImpl<index>();
        }
        
        template <int INDEX>
        void setCleanImpl() const
        {
            next_.template setCleanImpl<INDEX>();
        }
        
        bool isDirty() const
        {
            return next_.template isDirtyImpl<index>();
        }
        
        template <int INDEX>
        bool isDirtyImpl() const
        {
            return next_.template isDirtyImpl<INDEX>();
        }
        
        void reset()
        {}
        
        template <class Shape>
        void setCoordinateOffset(Shape const &)
        {}
        
        template <class Shape>
        void reshape(Shape const &)
        {}
        
        void operator+=(AccumulatorBase const &)
        {}
        
        template <class U>
        void update(U const &)
        {}
        
        template <class U>
        void update(U const &, double)
        {}
        
        template <class TargetTag>
        typename LookupDependency<TargetTag, ThisType>::result_type
        call_getDependency() const
        {
            return getDependency<TargetTag>(*this);
        }
    };

        // The middle class(es) of the decorator hierarchy implement the actual feature computation.
    typedef typename UseTag::template Impl<InputType, AccumulatorBase> AccumulatorImpl;
    
        // outer class of the decorator hierarchy. It has the following functionalities
        //  * ensure that only active accumulators are called in a dynamic accumulator chain
        //  * ensure that each accumulator is only called in its desired pass as defined in A::workInPass
        //  * determine how many passes through the data are required
    struct Accumulator
    : public AccumulatorImpl
    {
        typedef Accumulator type;
        typedef Accumulator & reference;
        typedef Accumulator const & const_reference;
        typedef AccumulatorImpl A;
        
        static const unsigned int workInPass = A::workInPass;
        static const bool allowRuntimeActivation = CONFIG::allowRuntimeActivation;
        
        template <class T>
        void resize(T const & t)
        {
            this->next_.resize(t);
            DecoratorImpl<Accumulator, workInPass, allowRuntimeActivation>::resize(*this, t);
        }
        
        void reset()
        {
            this->next_.reset();
            A::reset();
        }
        
        typename A::result_type get() const
        {
            return DecoratorImpl<A, workInPass, allowRuntimeActivation>::get(*this);
        }
        
        template <unsigned N, class T>
        void pass(T const & t)
        {
            this->next_.template pass<N>(t);
            DecoratorImpl<Accumulator, N, allowRuntimeActivation>::exec(*this, t);
        }
        
        template <unsigned N, class T>
        void pass(T const & t, double weight)
        {
            this->next_.template pass<N>(t, weight);
            DecoratorImpl<Accumulator, N, allowRuntimeActivation>::exec(*this, t, weight);
        }
        
        void mergeImpl(Accumulator const & o)
        {
            DecoratorImpl<Accumulator, Accumulator::workInPass, allowRuntimeActivation>::mergeImpl(*this, o);
            this->next_.mergeImpl(o.next_);
        }
        
        void applyHistogramOptions(HistogramOptions const & options)
        {
            DecoratorImpl<Accumulator, workInPass, allowRuntimeActivation>::applyHistogramOptions(*this, options);
            this->next_.applyHistogramOptions(options);
        }
        
        template <class SHAPE>
        void setCoordinateOffsetImpl(SHAPE const & offset)
        {
            this->setCoordinateOffset(offset);
            this->next_.setCoordinateOffsetImpl(offset);
        }
        
        static unsigned int passesRequired()
        {
            return DecoratorImpl<Accumulator, workInPass, allowRuntimeActivation>::passesRequired();
        }
        
        template <class ActiveFlags>
        static unsigned int passesRequired(ActiveFlags const & flags)
        {
            return DecoratorImpl<Accumulator, workInPass, allowRuntimeActivation>::passesRequired(flags);
        }
    };

    typedef Accumulator type;
};

template <class CONFIG, unsigned LEVEL>
struct AccumulatorFactory<void, CONFIG, LEVEL>
{
    typedef AccumulatorEndImpl<LEVEL, typename CONFIG::GlobalAccumulatorHandle> type;
};

struct InvalidGlobalAccumulatorHandle
{
    typedef Error__Global_statistics_are_only_defined_for_AccumulatorChainArray type;
    
    InvalidGlobalAccumulatorHandle()
    : pointer_(0)
    {}
    
    type const * pointer_;
};

    // helper classes to create an accumulator chain from a TypeList
    // if dynamic=true,  a dynamic accumulator will be created
    // if dynamic=false, a plain accumulator will be created
template <class T, class Selected, bool dynamic=false, class GlobalHandle=InvalidGlobalAccumulatorHandle>
struct ConfigureAccumulatorChain
#ifndef DOXYGEN
: public ConfigureAccumulatorChain<T, typename AddDependencies<typename Selected::type>::type, dynamic>
#endif
{};

template <class T, class HEAD, class TAIL, bool dynamic, class GlobalHandle>
struct ConfigureAccumulatorChain<T, TypeList<HEAD, TAIL>, dynamic, GlobalHandle>
{
    typedef TypeList<HEAD, TAIL> TagList;
    typedef T InputType;
    static const bool allowRuntimeActivation = dynamic;
    typedef GlobalHandle GlobalAccumulatorHandle;
 
    typedef typename AccumulatorFactory<HEAD, ConfigureAccumulatorChain>::type type;
};

template <class T, class Selected, bool dynamic=false>
struct ConfigureAccumulatorChainArray
#ifndef DOXYGEN
: public ConfigureAccumulatorChainArray<T, typename AddDependencies<typename Selected::type>::type, dynamic>
#endif
{};

template <class T, class HEAD, class TAIL, bool dynamic>
struct ConfigureAccumulatorChainArray<T, TypeList<HEAD, TAIL>, dynamic>
{
    typedef TypeList<HEAD, TAIL> TagList;
    typedef SeparateGlobalAndRegionTags<TagList> TagSeparator;
    typedef typename TagSeparator::GlobalTags GlobalTags;
    typedef typename TagSeparator::RegionTags RegionTags;
    typedef typename ConfigureAccumulatorChain<T, GlobalTags, dynamic>::type GlobalAccumulatorChain;

    struct GlobalAccumulatorHandle
    {
        typedef GlobalAccumulatorChain type;
        
        GlobalAccumulatorHandle()
        : pointer_(0)
        {}
        
        type const * pointer_;
    };
    
    typedef typename ConfigureAccumulatorChain<T, RegionTags, dynamic, GlobalAccumulatorHandle>::type RegionAccumulatorChain;
    
    typedef LabelDispatch<T, GlobalAccumulatorChain, RegionAccumulatorChain> type;
};

} // namespace acc_detail 

/****************************************************************************/
/*                                                                          */
/*                            accumulator chain                             */
/*                                                                          */
/****************************************************************************/

// Implement the high-level interface of an accumulator chain
template <class T, class NEXT>
class AccumulatorChainImpl
{
  public:
    typedef NEXT                                             InternalBaseType;
    typedef AccumulatorBegin                                 Tag;
    typedef typename InternalBaseType::argument_type         argument_type;
    typedef typename InternalBaseType::first_argument_type   first_argument_type;
    typedef typename InternalBaseType::second_argument_type  second_argument_type;
    typedef void                                             value_type;
    typedef typename InternalBaseType::result_type           result_type;
    
    static const int staticSize = InternalBaseType::index;

    InternalBaseType next_;

    /** \brief Current pass of the accumulator chain.
    */
    unsigned int current_pass_;
    
    AccumulatorChainImpl()
    : current_pass_(0)
    {}

    /** Set options for all histograms in the accumulator chain. See histogram accumulators for possible options. The function is ignored if there is no histogram in the accumulator chain.
    */
    void setHistogramOptions(HistogramOptions const & options)
    {
        next_.applyHistogramOptions(options);
    }
    

    /** Set regional and global options for all histograms in the accumulator chain.
    */
    void setHistogramOptions(HistogramOptions const & regionoptions, HistogramOptions const & globaloptions)
    {
        next_.applyHistogramOptions(regionoptions, globaloptions);
    }
    
    /** Set an offset for <tt>Coord<...></tt> statistics.
    
        If the offset is non-zero, coordinate statistics such as <tt>RegionCenter</tt> are computed
        in the global coordinate system defined by the \a offset. Without an offset, these statistics
        are computed in the local coordinate system of the current region of interest.
    */    
    template <class SHAPE>
    void setCoordinateOffset(SHAPE const & offset)
    {
        next_.setCoordinateOffsetImpl(offset);
    }
    
    /** Reset current_pass_ of the accumulator chain to 'reset_to_pass'.
    */
    void reset(unsigned int reset_to_pass = 0)
    {
        current_pass_ = reset_to_pass;
        if(reset_to_pass == 0)
            next_.reset();
    }
    
    template <unsigned N>
    void update(T const & t)
    {
        if(current_pass_ == N)
        {
            next_.template pass<N>(t);
        }
        else if(current_pass_ < N)
        {
            current_pass_ = N;
            if(N == 1)
                next_.resize(acc_detail::shapeOf(t));
            next_.template pass<N>(t);
        }
        else
        {
            std::string message("AccumulatorChain::update(): cannot return to pass ");
            message << N << " after working on pass " << current_pass_ << ".";
            vigra_precondition(false, message);
        }
    }
    
    template <unsigned N>
    void update(T const & t, double weight)
    {
        if(current_pass_ == N)
        {
            next_.template pass<N>(t, weight);
        }
        else if(current_pass_ < N)
        {
            current_pass_ = N;
            if(N == 1)
                next_.resize(acc_detail::shapeOf(t));
            next_.template pass<N>(t, weight);
        }
        else
        {
            std::string message("AccumulatorChain::update(): cannot return to pass ");
            message << N << " after working on pass " << current_pass_ << ".";
            vigra_precondition(false, message);
       }
    }
    
    /** Equivalent to merge(o) .
    */
    void operator+=(AccumulatorChainImpl const & o)
    {
        merge(o);
    }
    
    /** Merge the accumulator chain with accumulator chain 'o'. This only works if all selected statistics in the accumulator chain support the '+=' operator. See the documentations of the particular statistics for support information.
    */
    void merge(AccumulatorChainImpl const & o)
    {
        next_.mergeImpl(o.next_);
    }

    result_type operator()() const
    {
        return next_.get();
    }

    void operator()(T const & t)
    {
        update<1>(t);
    }
    
    void operator()(T const & t, double weight)
    {
        update<1>(t, weight);
    }

    void updatePass2(T const & t)
    {
        update<2>(t);
    }
    
    void updatePass2(T const & t, double weight)
    {
        update<2>(t, weight);
    }

    /** Upate all accumulators in the accumulator chain that work in pass N with data t. Requirement: 0 < N < 6 and N >= current_pass_ . If N < current_pass_ call reset() first.  
    */
    void updatePassN(T const & t, unsigned int N)
    {
        switch (N)
        {
            case 1: update<1>(t); break;
            case 2: update<2>(t); break;
            case 3: update<3>(t); break;
            case 4: update<4>(t); break;
            case 5: update<5>(t); break;
            default:
                vigra_precondition(false,
                     "AccumulatorChain::updatePassN(): 0 < N < 6 required.");
        }
    }
    
    /** Upate all accumulators in the accumulator chain that work in pass N with data t and weight. Requirement: 0 < N < 6 and N >= current_pass_ . If N < current_pass_ call reset() first. 
    */
    void updatePassN(T const & t, double weight, unsigned int N)
    {
        switch (N)
        {
            case 1: update<1>(t, weight); break;
            case 2: update<2>(t, weight); break;
            case 3: update<3>(t, weight); break;
            case 4: update<4>(t, weight); break;
            case 5: update<5>(t, weight); break;
            default:
                vigra_precondition(false,
                     "AccumulatorChain::updatePassN(): 0 < N < 6 required.");
        }
    }
  
    /** Return the number of passes required to compute all statistics in the accumulator chain.
    */
    unsigned int passesRequired() const
    {
        return InternalBaseType::passesRequired();
    }
};



   // Create an accumulator chain containing the Selected statistics and their dependencies.

/** \brief Create an accumulator chain containing the selected statistics and their dependencies.

    AccumulatorChain is used to compute global statistics which have to be selected at compile time. 

    The template parameters are as follows:
    - T: The input type
        - either element type of the data(e.g. double, int, RGBValue, ...)
        - or type of CoupledHandle (for simultaneous access to coordinates and/or weights)
    - Selected: statistics to be computed and index specifier for the CoupledHandle, wrapped with Select
    
    Usage:
    \code
    typedef double DataType;
    AccumulatorChain<DataType, Select<Variance, Mean, Minimum, ...> > accumulator;
    \endcode

    Usage, using CoupledHandle:
    \code
    const int dim = 3; //dimension of MultiArray
    typedef double DataType;
    typedef double WeightType;
    typedef vigra::CoupledIteratorType<dim, DataType, WeightType>::HandleType Handle;
    AccumulatorChain<Handle, Select<DataArg<1>, WeightArg<2>, Mean,...> > a;
    \endcode

    See \ref FeatureAccumulators for more information and examples of use.
 */
template <class T, class Selected, bool dynamic=false>
class AccumulatorChain
#ifndef DOXYGEN // hide AccumulatorChainImpl from documentation
: public AccumulatorChainImpl<T, typename acc_detail::ConfigureAccumulatorChain<T, Selected, dynamic>::type>
#endif
{
  public:
  // \brief TypeList of Tags in the accumulator chain (?).
    typedef typename acc_detail::ConfigureAccumulatorChain<T, Selected, dynamic>::TagList AccumulatorTags;
  
    /** Before having seen data (current_pass_==0), the shape of the data can be changed... (?)
    */
    template <class U, int N>
    void reshape(TinyVector<U, N> const & s)
    {
        vigra_precondition(this->current_pass_ == 0,
             "AccumulatorChain::reshape(): cannot reshape after seeing data. Call AccumulatorChain::reset() first.");
        this->next_.resize(s);
        this->current_pass_ = 1;
    }
     
    /** Return the names of all tags in the accumulator chain (selected statistics and their dependencies).
    */
    static ArrayVector<std::string> const & tagNames()
    {
        static ArrayVector<std::string> * n = VIGRA_SAFE_STATIC(n, new ArrayVector<std::string>(collectTagNames()));
        return *n;
    }


#ifdef DOXYGEN // hide AccumulatorChainImpl from documentation
  
  /** Set options for all histograms in the accumulator chain. See histogram accumulators for possible options. The function is ignored if there is no histogram in the accumulator chain.
   */
  void setHistogramOptions(HistogramOptions const & options);
    
  /** Set an offset for <tt>Coord<...></tt> statistics.
  
      If the offset is non-zero, coordinate statistics such as <tt>RegionCenter</tt> are computed
      in the global coordinate system defined by the \a offset. Without an offset, these statistics
      are computed in the local coordinate system of the current region of interest.
  */    
  template <class SHAPE>
  void setCoordinateOffset(SHAPE const & offset);
    
  /** Reset current_pass_ of the accumulator chain to 'reset_to_pass'. */
  void reset(unsigned int reset_to_pass = 0);

  /** Equivalent to merge(o) . */
  void operator+=(AccumulatorChainImpl const & o);
  
  /** Merge the accumulator chain with accumulator chain 'o'. This only works if all selected statistics in the accumulator chain support the '+=' operator. See the documentations of the particular statistics for support information.
   */
  void merge(AccumulatorChainImpl const & o);
  
  /** Upate all accumulators in the accumulator chain that work in pass N with data t. Requirement: 0 < N < 6 and N >= current_pass_ . If N < current_pass_ call reset first.  
   */
  void updatePassN(T const & t, unsigned int N);
  
  /** Upate all accumulators in the accumulator chain that work in pass N with data t and weight. Requirement: 0 < N < 6 and N >= current_pass_ . If N < current_pass_ call reset first. 
   */
  void updatePassN(T const & t, double weight, unsigned int N);
  
  /** Return the number of passes required to compute all statistics in the accumulator chain.
   */
  unsigned int passesRequired() const;
  
#endif   
 
  private:
    static ArrayVector<std::string> collectTagNames()
    {
        ArrayVector<std::string> n;
        acc_detail::CollectAccumulatorNames<AccumulatorTags>::exec(n);
        std::sort(n.begin(), n.end());
        return n;
    }
}; 

template <unsigned int N, class T1, class T2, class T3, class T4, class T5, class Selected, bool dynamic>
class AccumulatorChain<CoupledArrays<N, T1, T2, T3, T4, T5>, Selected, dynamic>
: public AccumulatorChain<typename CoupledArrays<N, T1, T2, T3, T4, T5>::HandleType, Selected, dynamic>
{};


    // Create a dynamic accumulator chain containing the Selected statistics and their dependencies.
    // Statistics will only be computed if activate<Tag>() is called at runtime.
/** \brief Create a dynamic accumulator chain containing the selected statistics and their dependencies.

    DynamicAccumulatorChain is used to compute global statistics with run-time activation. A set of statistics is selected at run-time and from this set statistics can be activated at run-time by calling activate<stat>() or activate(std::string stat).

    The template parameters are as follows:
    - T: The input type
        - either element type of the data(e.g. double, int, RGBValue, ...)
        - or type of CoupledHandle (for access to coordinates and/or weights)
    - Selected: statistics to be computed and index specifier for the CoupledHandle, wrapped with Select
    
    Usage:
    \code
    typedef double DataType;
    DynamicAccumulatorChain<DataType, Select<Variance, Mean, Minimum, ...> > accumulator;
    \endcode

    Usage, using CoupledHandle:
    \code
    const int dim = 3; //dimension of MultiArray
    typedef double DataType;
    typedef double WeightType;
    typedef vigra::CoupledIteratorType<dim, DataType, WeightType>::HandleType Handle;
    DynamicAccumulatorChain<Handle, Select<DataArg<1>, WeightArg<2>, Mean,...> > a;
    \endcode

    See \ref FeatureAccumulators for more information and examples of use.
 */
template <class T, class Selected>
class DynamicAccumulatorChain
: public AccumulatorChain<T, Selected, true>
{
  public:
    typedef typename AccumulatorChain<T, Selected, true>::InternalBaseType InternalBaseType;
    typedef typename DynamicAccumulatorChain::AccumulatorTags AccumulatorTags;
       
    /** Activate statistic 'tag'. Alias names are not recognized. If the statistic is not in the accumulator chain a PreconditionViolation is thrown.
    */
    void activate(std::string tag)
    {
        vigra_precondition(activateImpl(tag),
            std::string("DynamicAccumulatorChain::activate(): Tag '") + tag + "' not found.");
    }
    
    /** %activate\<TAG\>() activates statistic 'TAG'. If the statistic is not in the accumulator chain it is ignored. (?)
    */
    template <class TAG>
    void activate()
    {
        LookupTag<TAG, DynamicAccumulatorChain>::type::activateImpl(getAccumulator<AccumulatorEnd>(*this).active_accumulators_);
    }
    
    /** Activate all statistics in the accumulator chain.
    */
    void activateAll()
    {
        getAccumulator<AccumulatorEnd>(*this).active_accumulators_.set();
    }
    /** Return true if the statistic 'tag' is active, i.e. activate(std::string tag) or activate<TAG>() has been called. If the statistic is not in the accumulator chain a PreconditionViolation is thrown. (Note that alias names are not recognized.)
    */
    bool isActive(std::string tag) const
    {
        acc_detail::TagIsActive_Visitor v;
        vigra_precondition(isActiveImpl(tag, v),
            std::string("DynamicAccumulatorChain::isActive(): Tag '") + tag + "' not found.");
        return v.result;
    }
    
    /** %isActive\<TAG\>() returns true if statistic 'TAG' is active, i.e. activate(std::string tag) or activate<TAG>() has been called. If the statistic is not in the accumulator chain, true is returned. (?)
    */
    template <class TAG>
    bool isActive() const
    {
        return LookupTag<TAG, DynamicAccumulatorChain>::type::isActiveImpl(getAccumulator<AccumulatorEnd>(*this).active_accumulators_);
    }

    /** Return names of all statistics in the accumulator chain that are active.
    */
    ArrayVector<std::string> activeNames() const
    {
        ArrayVector<std::string> res;
        for(unsigned k=0; k<DynamicAccumulatorChain::tagNames().size(); ++k)
            if(isActive(DynamicAccumulatorChain::tagNames()[k]))
                res.push_back(DynamicAccumulatorChain::tagNames()[k]);
        return res;
    }
    
    /** Return number of passes required to compute the active statistics in the accumulator chain.
    */
    unsigned int passesRequired() const
    {
        return InternalBaseType::passesRequired(getAccumulator<AccumulatorEnd>(*this).active_accumulators_);
    }
    
  protected:
  
    bool activateImpl(std::string tag)
    {
        return acc_detail::ApplyVisitorToTag<AccumulatorTags>::exec(*this, 
                                         normalizeString(tag), acc_detail::ActivateTag_Visitor());
    }
    
    bool isActiveImpl(std::string tag, acc_detail::TagIsActive_Visitor & v) const
    {
        return acc_detail::ApplyVisitorToTag<AccumulatorTags>::exec(*this, normalizeString(tag), v);
    }
};

template <unsigned int N, class T1, class T2, class T3, class T4, class T5, class Selected>
class DynamicAccumulatorChain<CoupledArrays<N, T1, T2, T3, T4, T5>, Selected>
: public DynamicAccumulatorChain<typename CoupledArrays<N, T1, T2, T3, T4, T5>::HandleType, Selected>
{};



/** \brief Create an array of accumulator chains containing the selected per-region and global statistics and their dependencies.

    AccumulatorChainArray is used to compute per-region statistics (as well as global statistics). The statistics are selected at compile-time. An array of accumulator chains (one per region) for region statistics is created and one accumulator chain for global statistics. The region labels always start at 0. Use the Global modifier to compute global statistics (by default per-region statistics are computed). 

    The template parameters are as follows:
    - T: The input type, type of CoupledHandle (for access to coordinates, labels and weights)
    - Selected: statistics to be computed and index specifier for the CoupledHandle, wrapped with Select

    Usage:
    \code
    const int dim = 3; //dimension of MultiArray
    typedef double DataType;
    typedef double WeightType;
    typedef unsigned int LabelType;
    typedef vigra::CoupledIteratorType<dim, DataType, WeightType, LabelType>::HandleType Handle;
    AccumulatorChainArray<Handle, Select<DataArg<1>, WeightArg<2>, LabelArg<3>, Mean, Variance, ...> > a;
    \endcode

    See \ref FeatureAccumulators for more information and examples of use.
*/
template <class T, class Selected, bool dynamic=false>
class AccumulatorChainArray
#ifndef DOXYGEN //hide AccumulatorChainImpl vom documentation
: public AccumulatorChainImpl<T, typename acc_detail::ConfigureAccumulatorChainArray<T, Selected, dynamic>::type>
#endif
{
  public:
    typedef typename acc_detail::ConfigureAccumulatorChainArray<T, Selected, dynamic> Creator;
    typedef typename Creator::TagList AccumulatorTags;
    typedef typename Creator::GlobalTags GlobalTags;
    typedef typename Creator::RegionTags RegionTags;
    
    /** Statistics will not be computed for label l. Note that only one label can be ignored.
    */
    void ignoreLabel(MultiArrayIndex l)
    {
        this->next_.ignoreLabel(l);
    }
    
    /** Set the maximum region label (e.g. for merging two accumulator chains).
    */
    void setMaxRegionLabel(unsigned label)
    {
        this->next_.setMaxRegionLabel(label);
    }
    
    /** %Maximum region label. (equal to regionCount() - 1)
    */
    MultiArrayIndex maxRegionLabel() const
    {
        return this->next_.maxRegionLabel();
    }
    
    /** Number of Regions. (equal to maxRegionLabel() + 1)
    */
    unsigned int regionCount() const
    {
        return this->next_.regions_.size();
    }
    
    /** Equivalent to <tt>merge(o)</tt>.
    */
    void operator+=(AccumulatorChainArray const & o)
    {
        merge(o);
    }
    
    /** Merge region i with region j. 
    */
    void merge(unsigned i, unsigned j)
    {
        vigra_precondition(i <= maxRegionLabel() && j <= maxRegionLabel(),
            "AccumulatorChainArray::merge(): region labels out of range.");
        this->next_.mergeImpl(i, j);
    }
    
    /** Merge with accumulator chain o. maxRegionLabel() of the two accumulators must be equal.
    */
    void merge(AccumulatorChainArray const & o)
    {
        if(maxRegionLabel() == -1)
            setMaxRegionLabel(o.maxRegionLabel());
        vigra_precondition(maxRegionLabel() == o.maxRegionLabel(),
            "AccumulatorChainArray::merge(): maxRegionLabel must be equal.");
        this->next_.mergeImpl(o.next_);
    }

    /** Merge with accumulator chain o using a mapping between labels of the two accumulators. Label l of accumulator chain o is mapped to labelMapping[l]. Hence, all elements of labelMapping must be <= maxRegionLabel() and size of labelMapping must match o.regionCount().
    */
    template <class ArrayLike>
    void merge(AccumulatorChainArray const & o, ArrayLike const & labelMapping)
    {
        vigra_precondition(labelMapping.size() == o.regionCount(),
            "AccumulatorChainArray::merge(): labelMapping.size() must match regionCount() of RHS.");
        this->next_.mergeImpl(o.next_, labelMapping);
    }

    /** Return names of all tags in the accumulator chain (selected statistics and their dependencies).
    */
    static ArrayVector<std::string> const & tagNames()
    {
        static const ArrayVector<std::string> n = collectTagNames();
        return n;
    }


#ifdef DOXYGEN // hide AccumulatorChainImpl from documentation

  /** \copydoc vigra::acc::AccumulatorChain::setHistogramOptions(HistogramOptions const &) */
  void setHistogramOptions(HistogramOptions const & options);

  /** Set regional and global options for all histograms in the accumulator chain.
   */
  void setHistogramOptions(HistogramOptions const & regionoptions, HistogramOptions const & globaloptions);
    
  /** \copydoc vigra::acc::AccumulatorChain::setCoordinateOffset(SHAPE const &)
  */    
  template <class SHAPE>
  void setCoordinateOffset(SHAPE const & offset)
  
  /** \copydoc vigra::acc::AccumulatorChain::reset() */
  void reset(unsigned int reset_to_pass = 0);

  /** \copydoc vigra::acc::AccumulatorChain::operator+=() */
  void operator+=(AccumulatorChainImpl const & o);
    
  /** \copydoc vigra::acc::AccumulatorChain::updatePassN(T const &,unsigned int) */
  void updatePassN(T const & t, unsigned int N);
  
  /** \copydoc vigra::acc::AccumulatorChain::updatePassN(T const &,double,unsigned int) */
  void updatePassN(T const & t, double weight, unsigned int N);
  
#endif
    
  private:
    static ArrayVector<std::string> collectTagNames()
    {
        ArrayVector<std::string> n;
        acc_detail::CollectAccumulatorNames<AccumulatorTags>::exec(n);
        std::sort(n.begin(), n.end());
        return n;
    }
};

template <unsigned int N, class T1, class T2, class T3, class T4, class T5, class Selected, bool dynamic>
class AccumulatorChainArray<CoupledArrays<N, T1, T2, T3, T4, T5>, Selected, dynamic>
: public AccumulatorChainArray<typename CoupledArrays<N, T1, T2, T3, T4, T5>::HandleType, Selected, dynamic>
{};

/** \brief Create an array of dynamic accumulator chains containing the selected per-region and global statistics and their dependencies.


    DynamicAccumulatorChainArray is used to compute per-region statistics (as well as global statistics) with run-time activation. A set of statistics is selected at run-time and from this set statistics can be activated at run-time by calling activate<stat>() or activate(std::string stat).

     The template parameters are as follows:
    - T: The input type, type of CoupledHandle (for access to coordinates, labels and weights)
    - Selected: statistics to be computed and index specifier for the CoupledHandle, wrapped with Select

    Usage:
    \code
    const int dim = 3; //dimension of MultiArray
    typedef double DataType;
    typedef double WeightType;
    typedef unsigned int LabelType;
    typedef vigra::CoupledIteratorType<dim, DataType, WeightType, LabelType>::HandleType Handle;
    DynamicAccumulatorChainArray<Handle, Select<DataArg<1>, WeightArg<2>, LabelArg<3>, Mean, Variance, ...> > a;
    \endcode

    See \ref FeatureAccumulators for more information and examples of use.
*/
template <class T, class Selected>
class DynamicAccumulatorChainArray
: public AccumulatorChainArray<T, Selected, true>
{
  public:
    typedef typename DynamicAccumulatorChainArray::AccumulatorTags AccumulatorTags;

    /** \copydoc DynamicAccumulatorChain::activate(std::string tag) */
    void activate(std::string tag)
    {
        vigra_precondition(activateImpl(tag),
            std::string("DynamicAccumulatorChainArray::activate(): Tag '") + tag + "' not found.");
    }
    
    /** \copydoc DynamicAccumulatorChain::activate() */
    template <class TAG>
    void activate()
    {
        this->next_.template activate<TAG>();
    }
    
    /** \copydoc DynamicAccumulatorChain::activateAll() */
    void activateAll()
    {
        this->next_.activateAll();
    }
    
    /** Return true if the statistic 'tag' is active, i.e. activate(std::string tag) or activate<TAG>() has been called. If the statistic is not in the accumulator chain a PreconditionViolation is thrown. (Note that alias names are not recognized.)
     */
    bool isActive(std::string tag) const
    {
        acc_detail::TagIsActive_Visitor v;
        vigra_precondition(isActiveImpl(tag, v),
            std::string("DynamicAccumulatorChainArray::isActive(): Tag '") + tag + "' not found.");
        return v.result;
    }
    
    /** %isActive\<TAG\>() returns true if statistic 'TAG' is active, i.e. activate(std::string tag) or activate<TAG>() has been called. If the statistic is not in the accumulator chain, true is returned. (?)
     */
    template <class TAG>
    bool isActive() const
    {
        return this->next_.template isActive<TAG>();
    }
    
    /** \copydoc DynamicAccumulatorChain::activeNames() */
    ArrayVector<std::string> activeNames() const
    {
        ArrayVector<std::string> res;
        for(unsigned k=0; k<DynamicAccumulatorChainArray::tagNames().size(); ++k)
            if(isActive(DynamicAccumulatorChainArray::tagNames()[k]))
                res.push_back(DynamicAccumulatorChainArray::tagNames()[k]);
        return res;
    }
    
    /** \copydoc DynamicAccumulatorChain::passesRequired() */
    unsigned int passesRequired() const
    {
        return this->next_.passesRequiredDynamic();
    }

  protected:
  
    bool activateImpl(std::string tag)
    {
        return acc_detail::ApplyVisitorToTag<AccumulatorTags>::exec(this->next_, 
                                         normalizeString(tag), acc_detail::ActivateTag_Visitor());
    }
    
    bool isActiveImpl(std::string tag, acc_detail::TagIsActive_Visitor & v) const
    {
        return acc_detail::ApplyVisitorToTag<AccumulatorTags>::exec(this->next_, normalizeString(tag), v);
    }
};

template <unsigned int N, class T1, class T2, class T3, class T4, class T5, class Selected>
class DynamicAccumulatorChainArray<CoupledArrays<N, T1, T2, T3, T4, T5>, Selected>
: public DynamicAccumulatorChainArray<typename CoupledArrays<N, T1, T2, T3, T4, T5>::HandleType, Selected>
{};

/****************************************************************************/
/*                                                                          */
/*                        generic access functions                          */
/*                                                                          */
/****************************************************************************/

template <class TAG>
struct Error__Attempt_to_access_inactive_statistic;

namespace acc_detail {

    // accumulator lookup rules: find the accumulator that implements TAG
    
    // When A does not implement TAG, continue search in A::InternalBaseType.
template <class TAG, class A, class FromTag=typename A::Tag>
struct LookupTagImpl
#ifndef DOXYGEN
: public LookupTagImpl<TAG, typename A::InternalBaseType>
#endif
{};

    // 'const A' is treated like A, except that the reference member is now const.
template <class TAG, class A, class FromTag>
struct LookupTagImpl<TAG, A const, FromTag>
: public LookupTagImpl<TAG, A>
{
    typedef typename LookupTagImpl<TAG, A>::type const & reference;
    typedef typename LookupTagImpl<TAG, A>::type const * pointer;
};

    // When A implements TAG, report its type and associated information.
template <class TAG, class A>
struct LookupTagImpl<TAG, A, TAG>
{
    typedef TAG Tag;
    typedef A type;
    typedef A & reference;
    typedef A * pointer;
    typedef typename A::value_type value_type;
    typedef typename A::result_type result_type;
};

    // Again, 'const A' is treated like A, except that the reference member is now const.
template <class TAG, class A>
struct LookupTagImpl<TAG, A const, TAG>
: public LookupTagImpl<TAG, A, TAG>
{
    typedef typename LookupTagImpl<TAG, A, TAG>::type const & reference;
    typedef typename LookupTagImpl<TAG, A, TAG>::type const * pointer;
};

    // Recursion termination: when we end up in AccumulatorEnd without finding a 
    // suitable A, we stop and report an error
template <class TAG, class A>
struct LookupTagImpl<TAG, A, AccumulatorEnd>
{
    typedef TAG Tag;
    typedef A type;
    typedef A & reference;
    typedef A * pointer;
    typedef Error__Attempt_to_access_inactive_statistic<TAG> value_type;
    typedef Error__Attempt_to_access_inactive_statistic<TAG> result_type;
};

    // ... except when we are actually looking for AccumulatorEnd
template <class A>
struct LookupTagImpl<AccumulatorEnd, A, AccumulatorEnd>
{
    typedef AccumulatorEnd Tag;
    typedef A type;
    typedef A & reference;
    typedef A * pointer;
    typedef void value_type;
    typedef void result_type;
};

    // ... or we are looking for a global statistic, in which case
    // we continue the serach via A::GlobalAccumulatorType, but remember that 
    // we are actually looking for a global tag. 
template <class TAG, class A>
struct LookupTagImpl<Global<TAG>, A, AccumulatorEnd>
: public LookupTagImpl<TAG, typename A::GlobalAccumulatorType>
{
    typedef Global<TAG> Tag;
};

    // When we encounter the LabelDispatch accumulator, we continue the
    // search via LabelDispatch::RegionAccumulatorChain by default
template <class TAG, class A>
struct LookupTagImpl<TAG, A, LabelDispatchTag>
: public LookupTagImpl<TAG, typename A::RegionAccumulatorChain>
{};

    // ... except when we are looking for a global statistic, in which case
    // we continue via LabelDispatch::GlobalAccumulatorChain, but remember that 
    // we are actually looking for a global tag.
template <class TAG, class A>
struct LookupTagImpl<Global<TAG>, A, LabelDispatchTag>
: public LookupTagImpl<TAG, typename A::GlobalAccumulatorChain>
{
    typedef Global<TAG> Tag;
};

    // ... or we are looking for the LabelDispatch accumulator itself
template <class A>
struct LookupTagImpl<LabelDispatchTag, A, LabelDispatchTag>
{
    typedef LabelDispatchTag Tag;
    typedef A type;
    typedef A & reference;
    typedef A * pointer;
    typedef void value_type;
    typedef void result_type;
};

} // namespace acc_detail

    // Lookup the accumulator in the chain A that implements the given TAG.
template <class Tag, class A>
struct LookupTag
: public acc_detail::LookupTagImpl<typename StandardizeTag<Tag>::type, A>
{};

    // Lookup the dependency TAG of the accumulator A.
    // This template ensures that dependencies are used with matching modifiers.
    // Specifically, if you search for Count as a dependency of Weighted<Mean>, the search
    // actually returns Weighted<Count>, wheras Count will be returned for plain Mean.
template <class Tag, class A, class TargetTag>
struct LookupDependency
: public acc_detail::LookupTagImpl<
       typename TransferModifiers<TargetTag, typename StandardizeTag<Tag>::type>::type, A>
{};
 

namespace acc_detail {

    // CastImpl applies the same rules as LookupTagImpl, but returns a reference to an 
    // accumulator instance rather than an accumulator type
template <class Tag, class FromTag, class reference>
struct CastImpl
{
    template <class A>
    static reference exec(A & a)
    {
        return CastImpl<Tag, typename A::InternalBaseType::Tag, reference>::exec(a.next_);
    }
    
    template <class A>
    static reference exec(A & a, MultiArrayIndex label)
    {
        return CastImpl<Tag, typename A::InternalBaseType::Tag, reference>::exec(a.next_, label);
    }
};

template <class Tag, class reference>
struct CastImpl<Tag, Tag, reference>
{
    template <class A>
    static reference exec(A & a)
    {
        return const_cast<reference>(a);
    }
    
    template <class A>
    static reference exec(A & a, MultiArrayIndex)
    {
        vigra_precondition(false, 
            "getAccumulator(): region accumulators can only be queried for AccumulatorChainArray.");
        return a;
    }
};

template <class Tag, class reference>
struct CastImpl<Tag, AccumulatorEnd, reference>
{
    template <class A>
    static reference exec(A & a)
    {
        return a;
    }
    
    template <class A>
    static reference exec(A & a, MultiArrayIndex)
    {
        return a;
    }
};

template <class Tag, class reference>
struct CastImpl<Global<Tag>, AccumulatorEnd, reference>
{
    template <class A>
    static reference exec(A & a)
    {
        return CastImpl<Tag, typename A::GlobalAccumulatorType::Tag, reference>::exec(*a.globalAccumulator_.pointer_);
    }
};

template <class reference>
struct CastImpl<AccumulatorEnd, AccumulatorEnd, reference>
{
    template <class A>
    static reference exec(A & a)
    {
        return a;
    }
    
    template <class A>
    static reference exec(A & a, MultiArrayIndex)
    {
        return a;
    }
};

template <class Tag, class reference>
struct CastImpl<Tag, LabelDispatchTag, reference>
{
    template <class A>
    static reference exec(A & a)
    {
        vigra_precondition(false, 
            "getAccumulator(): a region label is required when a region accumulator is queried.");
        return CastImpl<Tag, typename A::RegionAccumulatorChain::Tag, reference>::exec(a.regions_[0]);
    }
    
    template <class A>
    static reference exec(A & a, MultiArrayIndex label)
    {
        return CastImpl<Tag, typename A::RegionAccumulatorChain::Tag, reference>::exec(a.regions_[label]);
    }
};

template <class Tag, class reference>
struct CastImpl<Global<Tag>, LabelDispatchTag, reference>
{
    template <class A>
    static reference exec(A & a)
    {
        return CastImpl<Tag, typename A::GlobalAccumulatorChain::Tag, reference>::exec(a.next_);
    }
};

template <class reference>
struct CastImpl<LabelDispatchTag, LabelDispatchTag, reference>
{
    template <class A>
    static reference exec(A & a)
    {
        return a;
    }
};

} // namespace acc_detail

    // Get a reference to the accumulator TAG in the accumulator chain A
/** Get a reference to the accumulator 'TAG' in the accumulator chain 'a'. This can be useful for example to update a certain accumulator with data, set individual options or get information about a certain accumulator.\n
Example of use (set options):
\code
    vigra::MultiArray<2, double> data(...);   
    typedef UserRangeHistogram<40> SomeHistogram;   //binCount set at compile time
    typedef UserRangeHistogram<0> SomeHistogram2; // binCount must be set at run-time
    AccumulatorChain<DataType, Select<SomeHistogram, SomeHistogram2> > a;
    
    getAccumulator<SomeHistogram>(a).setMinMax(0.1, 0.9);
    getAccumulator<SomeHistogram2>(a).setMinMax(0.0, 1.0);

    extractFeatures(data.begin(), data.end(), a);
\endcode

Example of use (get information):
\code
  vigra::MultiArray<2, double> data(...));
  AccumulatorChain<double, Select<Mean, Skewness> > a;

  std::cout << "passes required for all statistics: " << a.passesRequired() << std::endl; //skewness needs two passes
  std::cout << "passes required by Mean: " << getAccumulator<Mean>(a).passesRequired() << std::endl;
\endcode
See \ref FeatureAccumulators for more information about feature computation via accumulators.
*/
template <class TAG, class A>
inline typename LookupTag<TAG, A>::reference
getAccumulator(A & a)
{
    typedef typename LookupTag<TAG, A>::Tag StandardizedTag;
    typedef typename LookupTag<TAG, A>::reference reference;
    return acc_detail::CastImpl<StandardizedTag, typename A::Tag, reference>::exec(a);
}

    // Get a reference to the accumulator TAG for region 'label' in the accumulator chain A
/** Get a reference to the accumulator 'TAG' for region 'label' in the accumulator chain 'a'.
*/
template <class TAG, class A>
inline typename LookupTag<TAG, A>::reference
getAccumulator(A & a, MultiArrayIndex label)
{
    typedef typename LookupTag<TAG, A>::Tag StandardizedTag;
    typedef typename LookupTag<TAG, A>::reference reference;
    return acc_detail::CastImpl<StandardizedTag, typename A::Tag, reference>::exec(a, label);
}

    // get the result of the accumulator specified by TAG
/** Get the result of the accumulator 'TAG' in the accumulator chain 'a'.\n
Example of use:
\code
    vigra::MultiArray<2, double> data(...);
    AccumulatorChain<DataType, Select<Variance, Mean, StdDev> > a;
    extractFeatures(data.begin(), data.end(), a); 
    double mean = get<Mean>(a);
\endcode
See \ref FeatureAccumulators for more information about feature computation via accumulators.
*/
template <class TAG, class A>
inline typename LookupTag<TAG, A>::result_type
get(A const & a)
{
    return getAccumulator<TAG>(a).get();
}

    // get the result of the accumulator TAG for region 'label'
/** Get the result of the accumulator 'TAG' for region 'label' in the accumulator chain 'a'.\n
Example of use:
\code
    vigra::MultiArray<2, double> data(...);
    vigra::MultiArray<2, int> labels(...);
    typedef vigra::CoupledIteratorType<2, double, int>::type Iterator;
    typedef Iterator::value_type Handle;

    AccumulatorChainArray<Handle, 
        Select<DataArg<1>, LabelArg<2>, Mean, Variance> > a;

    Iterator start = createCoupledIterator(data, labels);
    Iterator end = start.getEndIterator();
    extractFeatures(start,end,a);

    double mean_of_region_1 = get<Mean>(a,1);
    double mean_of_background = get<Mean>(a,0);
\endcode
See \ref FeatureAccumulators for more information about feature computation via accumulators.
*/
template <class TAG, class A>
inline typename LookupTag<TAG, A>::result_type
get(A const & a, MultiArrayIndex label)
{
    return getAccumulator<TAG>(a, label).get();
}

    // Get the result of the accumulator specified by TAG without checking if the accumulator is active.
    // This must be used within an accumulator implementation to access dependencies because
    // it applies the approprate modifiers to the given TAG. It must not be used in other situations.
    // FIXME: is there a shorter name?
template <class TAG, class A>
inline typename LookupDependency<TAG, A>::result_type
getDependency(A const & a)
{
    typedef typename LookupDependency<TAG, A>::Tag StandardizedTag;
    typedef typename LookupDependency<TAG, A>::reference reference;
    return acc_detail::CastImpl<StandardizedTag, typename A::Tag, reference>::exec(a)();
}

    // activate the dynamic accumulator specified by Tag
/** Activate the dynamic accumulator 'Tag' in the dynamic accumulator chain 'a'. Same as a.activate<Tag>() (see DynamicAccumulatorChain::activate<Tag>() or DynamicAccumulatorChainArray::activate<Tag>()). For run-time activation use DynamicAccumulatorChain::activate(std::string tag) or DynamicAccumulatorChainArray::activate(std::string tag) instead.\n
See \ref FeatureAccumulators for more information about feature computation via accumulators.
*/
template <class Tag, class A>
inline void
activate(A & a)
{
    a.template activate<Tag>();
}

    // check if the dynamic accumulator specified by Tag is active
/** Check if the dynamic accumulator 'Tag' in the accumulator chain 'a' is active. Same as a.isActive<Tag>() (see DynamicAccumulatorChain::isActive<Tag>() or DynamicAccumulatorChainArray::isActive<Tag>()). At run-time, use DynamicAccumulatorChain::isActive(std::string tag) const or DynamicAccumulatorChainArray::isActive(std::string tag) const instead.\n
See \ref FeatureAccumulators for more information about feature computation via accumulators.
*/
template <class Tag, class A>
inline bool
isActive(A const & a)
{
    return a.template isActive<Tag>();
}

/****************************************************************************/
/*                                                                          */
/*                               generic loops                              */
/*                                                                          */
/****************************************************************************/

/** Generic loop to collect statistics from one or several arrays.

This function automatically performs as many passes over the data as necessary for the selected statistics. The basic version of <tt>extractFeatures()</tt> takes an iterator pair and a reference to an accumulator chain:
\code
namespace vigra { namespace acc {

    template <class ITERATOR, class ACCUMULATOR>
    void extractFeatures(ITERATOR start, ITERATOR end, ACCUMULATOR & a);
}}
\endcode
The <tt>ITERATOR</tt> can be any STL-conforming <i>forward iterator</i> (including raw pointers and \ref vigra::CoupledScanOrderIterator). The <tt>ACCUMULATOR</tt> must be instantiated with the <tt>ITERATOR</tt>'s <tt>value_type</tt> as its first template argument. For example, to use a raw pointer you write:
\code
    AccumulatorChain<double, Select<Mean, Variance> > a;

    double * start = ...,
           * end   = ...;
    extractFeatures(start, end, a);
\endcode
Similarly, you can use MultiArray's scan-order iterator:
\code    
    AccumulatorChain<TinyVector<float, 2>, Select<Mean, Variance> > a;

    MultiArray<3, TinyVector<float, 2> > data(...);
    extractFeatures(data.begin(), data.end(), a);
\endcode
An alternative syntax is used when you want to compute weighted or region statistics (or both). Then it is necessary to iterate over several arrays simultaneously. This fact is best conveyed to the accumulator via the helper class \ref vigra::CoupledArrays that is used as the accumulator's first template argument and holds the dimension and value types of the arrays involved. To actually compute the features, you then pass appropriate arrays to the <tt>extractfeatures()</tt> function directly. For example, region statistics can be obtained like this:
\code
    MultiArray<3, double> data(...);
    MultiArray<3, int> labels(...);

    AccumulatorChainArray<CoupledArrays<3, double, int>,
                          Select<DataArg<1>, LabelArg<2>, // where to look for data and region labels
                                 Mean, Variance> >        // what statistics to compute
        a;

    extractFeatures(data, labels, a);
\endcode
This form of <tt>extractFeatures()</tt> is supported for up to five arrays (although at most three are currently making sense in practice):
\code
namespace vigra { namespace acc {

    template <unsigned int N, class T1, class S1,
              class ACCUMULATOR>
    void extractFeatures(MultiArrayView<N, T1, S1> const & a1, 
                         ACCUMULATOR & a);
                         
    ...

    template <unsigned int N, class T1, class S1,
                              class T2, class S2,
                              class T3, class S3,
                              class T4, class S4,
                              class T5, class S5,
              class ACCUMULATOR>
    void extractFeatures(MultiArrayView<N, T1, S1> const & a1, 
                         MultiArrayView<N, T2, S2> const & a2, 
                         MultiArrayView<N, T3, S3> const & a3, 
                         MultiArrayView<N, T4, S4> const & a4, 
                         MultiArrayView<N, T5, S5> const & a5, 
                         ACCUMULATOR & a);
}}
\endcode
Of course, the number and types of the arrays specified in <tt>CoupledArrays</tt> must conform to the number and types of the arrays passed to <tt>extractFeatures()</tt>.

See \ref FeatureAccumulators for more information about feature computation via accumulators.
*/
doxygen_overloaded_function(template <...> void extractFeatures)


template <class ITERATOR, class ACCUMULATOR>
void extractFeatures(ITERATOR start, ITERATOR end, ACCUMULATOR & a)
{
    for(unsigned int k=1; k <= a.passesRequired(); ++k)
        for(ITERATOR i=start; i < end; ++i)
            a.updatePassN(*i, k);
}

template <unsigned int N, class T1, class S1,
          class ACCUMULATOR>
void extractFeatures(MultiArrayView<N, T1, S1> const & a1, 
                     ACCUMULATOR & a)
{
    typedef typename CoupledIteratorType<N, T1>::type Iterator;
    Iterator start = createCoupledIterator(a1),
             end   = start.getEndIterator();
    extractFeatures(start, end, a);
}

template <unsigned int N, class T1, class S1,
                          class T2, class S2,
          class ACCUMULATOR>
void extractFeatures(MultiArrayView<N, T1, S1> const & a1, 
                     MultiArrayView<N, T2, S2> const & a2, 
                     ACCUMULATOR & a)
{
    typedef typename CoupledIteratorType<N, T1, T2>::type Iterator;
    Iterator start = createCoupledIterator(a1, a2),
             end   = start.getEndIterator();
    extractFeatures(start, end, a);
}

template <unsigned int N, class T1, class S1,
                          class T2, class S2,
                          class T3, class S3,
          class ACCUMULATOR>
void extractFeatures(MultiArrayView<N, T1, S1> const & a1, 
                     MultiArrayView<N, T2, S2> const & a2, 
                     MultiArrayView<N, T3, S3> const & a3, 
                     ACCUMULATOR & a)
{
    typedef typename CoupledIteratorType<N, T1, T2, T3>::type Iterator;
    Iterator start = createCoupledIterator(a1, a2, a3),
             end   = start.getEndIterator();
    extractFeatures(start, end, a);
}

template <unsigned int N, class T1, class S1,
                          class T2, class S2,
                          class T3, class S3,
                          class T4, class S4,
          class ACCUMULATOR>
void extractFeatures(MultiArrayView<N, T1, S1> const & a1, 
                     MultiArrayView<N, T2, S2> const & a2, 
                     MultiArrayView<N, T3, S3> const & a3, 
                     MultiArrayView<N, T4, S4> const & a4, 
                     ACCUMULATOR & a)
{
    typedef typename CoupledIteratorType<N, T1, T2, T3, T4>::type Iterator;
    Iterator start = createCoupledIterator(a1, a2, a3, a4),
             end   = start.getEndIterator();
    extractFeatures(start, end, a);
}

template <unsigned int N, class T1, class S1,
                          class T2, class S2,
                          class T3, class S3,
                          class T4, class S4,
                          class T5, class S5,
          class ACCUMULATOR>
void extractFeatures(MultiArrayView<N, T1, S1> const & a1, 
                     MultiArrayView<N, T2, S2> const & a2, 
                     MultiArrayView<N, T3, S3> const & a3, 
                     MultiArrayView<N, T4, S4> const & a4, 
                     MultiArrayView<N, T5, S5> const & a5, 
                     ACCUMULATOR & a)
{
    typedef typename CoupledIteratorType<N, T1, T2, T3, T4, T5>::type Iterator;
    Iterator start = createCoupledIterator(a1, a2, a3, a4, a5),
             end   = start.getEndIterator();
    extractFeatures(start, end, a);
}

/****************************************************************************/
/*                                                                          */
/*                          AccumulatorResultTraits                         */
/*                                                                          */
/****************************************************************************/

template <class T>
struct AccumulatorResultTraits
{
    typedef T                                       type;
    typedef T                                       element_type;
    typedef double                                  element_promote_type;
    typedef T                                       MinmaxType;
    typedef element_promote_type                    SumType;
    typedef element_promote_type                    FlatCovarianceType;
    typedef element_promote_type                    CovarianceType;
};

template <class T, int N>
struct AccumulatorResultTraits<TinyVector<T, N> >
{
    typedef TinyVector<T, N>                             type;
    typedef T                                            element_type;
    typedef double                                       element_promote_type;
    typedef TinyVector<T, N>                             MinmaxType;
    typedef TinyVector<element_promote_type, N>          SumType;
    typedef TinyVector<element_promote_type, N*(N+1)/2>  FlatCovarianceType;
    typedef Matrix<element_promote_type>                 CovarianceType;
};

// (?) beign change
template <class T, unsigned int RED_IDX, unsigned int GREEN_IDX, unsigned int BLUE_IDX>
struct AccumulatorResultTraits<RGBValue<T, RED_IDX, GREEN_IDX, BLUE_IDX> >
{
    typedef RGBValue<T>                                  type;
    typedef T                                            element_type;
    typedef double                                       element_promote_type;
    typedef RGBValue<T>                                  MinmaxType;
    typedef RGBValue<element_promote_type>               SumType;
    typedef TinyVector<element_promote_type, 3*(3+1)/2>  FlatCovarianceType;
    typedef Matrix<element_promote_type>                 CovarianceType;
};
// end change


template <unsigned int N, class T, class Stride>
struct AccumulatorResultTraits<MultiArrayView<N, T, Stride> >
{
    typedef MultiArrayView<N, T, Stride>            type;
    typedef T                                       element_type;
    typedef double                                  element_promote_type;
    typedef MultiArray<N, T>                        MinmaxType;
    typedef MultiArray<N, element_promote_type>     SumType;
    typedef MultiArray<1, element_promote_type>     FlatCovarianceType;
    typedef Matrix<element_promote_type>            CovarianceType;
};

template <unsigned int N, class T, class Alloc>
struct AccumulatorResultTraits<MultiArray<N, T, Alloc> >
{
    typedef MultiArrayView<N, T, Alloc>             type;
    typedef T                                       element_type;
    typedef double                                  element_promote_type;
    typedef MultiArray<N, T>                        MinmaxType;
    typedef MultiArray<N, element_promote_type>     SumType;
    typedef MultiArray<1, element_promote_type>     FlatCovarianceType;
    typedef Matrix<element_promote_type>            CovarianceType;
};

/****************************************************************************/
/*                                                                          */
/*                           modifier implementations                       */
/*                                                                          */
/****************************************************************************/

/** \brief Modifier. Compute statistic globally rather than per region. 

This modifier only works when labels are given (with (Dynamic)AccumulatorChainArray), in which case statistics are computed per-region by default.
*/
template <class TAG>
class Global
{
  public:
    typedef typename StandardizeTag<TAG>::type  TargetTag;
    typedef typename TargetTag::Dependencies    Dependencies;
    
    static std::string name() 
    { 
        return std::string("Global<") + TargetTag::name() + " >";
        // static const std::string n = std::string("Global<") + TargetTag::name() + " >";
        // return n;
    }
};

/** \brief Specifies index of data in CoupledHandle. 

    If AccumulatorChain is used with CoupledIterator, DataArg<INDEX> tells the accumulator chain which index of the Handle contains the data. (Coordinates are always index 0)
*/
template <int INDEX>
class DataArg
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return std::string("DataArg<") + asString(INDEX) + "> (internal)";
        // static const std::string n = std::string("DataArg<") + asString(INDEX) + "> (internal)";
        // return n;
    }
    
    template <class T, class BASE>
    struct Impl
    : public BASE
    {
        typedef DataArgTag Tag;
        typedef void value_type;
        typedef void result_type;

        static const int value = INDEX;
        static const unsigned int workInPass = 0;
    };
};

// Tags are automatically wrapped with DataFromHandle if CoupledHandle used
template <class TAG>
class DataFromHandle
{
  public:
    typedef typename StandardizeTag<TAG>::type TargetTag;
    typedef typename TargetTag::Dependencies Dependencies;
    
    static std::string name() 
    { 
        return std::string("DataFromHandle<") + TargetTag::name() + " > (internal)";
        // static const std::string n = std::string("DataFromHandle<") + TargetTag::name() + " > (internal)";
        // return n;
    }
    
    template <class IndexDefinition, class TagFound=typename IndexDefinition::Tag>
    struct DataIndexSelector
    {
        static const int value = 1; // default: CoupledHandle holds data at index 1 
        
        template <class U, class NEXT>
        static typename CoupledHandleCast<value, CoupledHandle<U, NEXT> >::type::const_reference 
        exec(CoupledHandle<U, NEXT> const & t)
        {
            return vigra::get<value>(t);
        }
    };
    
    template <class IndexDefinition>
    struct DataIndexSelector<IndexDefinition, DataArgTag>
    {
        static const int value = IndexDefinition::value;
        
        template <class U, class NEXT>
        static typename CoupledHandleCast<value, CoupledHandle<U, NEXT> >::type::const_reference
        exec(CoupledHandle<U, NEXT> const & t)
        {
            return vigra::get<value>(t);
        }
    };
    
    template <class T, class BASE>
    struct SelectInputType
    {
        typedef typename LookupTag<DataArgTag, BASE>::type FindDataIndex;
        typedef DataIndexSelector<FindDataIndex> DataIndex;
        typedef typename CoupledHandleCast<DataIndex::value, T>::type::value_type type;
    };
    
    template <class T, class BASE>
    struct Impl
    : public TargetTag::template Impl<typename SelectInputType<T, BASE>::type, BASE>
    {
        typedef SelectInputType<T, BASE>                InputTypeSelector;
        typedef typename InputTypeSelector::DataIndex   DataIndex;
        typedef typename InputTypeSelector::type        input_type;
        typedef input_type const &                      argument_type;
        typedef argument_type                           first_argument_type;
        
        typedef typename TargetTag::template Impl<input_type, BASE> ImplType;
        
        using ImplType::reshape;
        
        template <class U, class NEXT>
        void reshape(CoupledHandle<U, NEXT> const & t)
        {
            ImplType::reshape(acc_detail::shapeOf(DataIndex::exec(t)));
        }
        
        template <class U, class NEXT>
        void update(CoupledHandle<U, NEXT> const & t)
        {
            ImplType::update(DataIndex::exec(t));
        }
        
        template <class U, class NEXT>
        void update(CoupledHandle<U, NEXT> const & t, double weight)
        {
            ImplType::update(DataIndex::exec(t), weight);
        }
    };
};

/** \brief Modifier. Compute statistic from pixel coordinates rather than from pixel values. 

    AccumulatorChain must be used with CoupledIterator in order to have access to pixel coordinates.
 */
template <class TAG>
class Coord
{
  public:
    typedef typename StandardizeTag<TAG>::type   TargetTag;
    typedef typename TargetTag::Dependencies     Dependencies;
    
    static std::string name() 
    { 
        return std::string("Coord<") + TargetTag::name() + " >";
        // static const std::string n = std::string("Coord<") + TargetTag::name() + " >";
        // return n;
    }
    
    template <class IndexDefinition, class TagFound=typename IndexDefinition::Tag>
    struct CoordIndexSelector
    {
        static const int value = 0; // default: CoupledHandle holds coordinates at index 0 
        
        template <class U, class NEXT>
        static typename CoupledHandleCast<value, CoupledHandle<U, NEXT> >::type::const_reference 
        exec(CoupledHandle<U, NEXT> const & t)
        {
            return vigra::get<value>(t);
        }
    };
    
    template <class IndexDefinition>
    struct CoordIndexSelector<IndexDefinition, CoordArgTag>
    {
        static const int value = IndexDefinition::value;
        
        template <class U, class NEXT>
        static typename CoupledHandleCast<value, CoupledHandle<U, NEXT> >::type::const_reference
        exec(CoupledHandle<U, NEXT> const & t)
        {
            return vigra::get<value>(t);
        }
    };
     
    template <class T, class BASE>
    struct SelectInputType
    {
        typedef typename LookupTag<CoordArgTag, BASE>::type FindDataIndex;
        typedef CoordIndexSelector<FindDataIndex> CoordIndex;
        typedef typename CoupledHandleCast<CoordIndex::value, T>::type::value_type type;
        static const int size = type::static_size;
    };
    
    template <class T, class BASE>
    struct Impl
    : public TargetTag::template Impl<TinyVector<double, SelectInputType<T, BASE>::size>, BASE>
    {
        typedef SelectInputType<T, BASE>                              InputTypeSelector;
        typedef typename InputTypeSelector::CoordIndex                CoordIndex;
        typedef TinyVector<double, SelectInputType<T, BASE>::size>    input_type;
        typedef input_type const &                                    argument_type;
        typedef argument_type                                         first_argument_type;
        
        typedef typename TargetTag::template Impl<input_type, BASE> ImplType;
        
        input_type offset_;
        
        Impl()
        : offset_()
        {}
        
        void setCoordinateOffset(input_type const & offset)
        {
            offset_ = offset;
        }
        
        using ImplType::reshape;
        
        template <class U, class NEXT>
        void reshape(CoupledHandle<U, NEXT> const & t)
        {
            ImplType::reshape(acc_detail::shapeOf(CoordIndex::exec(t)));
        }
        
        template <class U, class NEXT>
        void update(CoupledHandle<U, NEXT> const & t)
        {
            ImplType::update(CoordIndex::exec(t)+offset_);
        }
        
        template <class U, class NEXT>
        void update(CoupledHandle<U, NEXT> const & t, double weight)
        {
            ImplType::update(CoordIndex::exec(t)+offset_, weight);
        }
    };
};

/** \brief Specifies index of data in CoupledHandle. 

    If AccumulatorChain is used with CoupledIterator, WeightArg<INDEX> tells the accumulator chain which index of the Handle contains the weights. (Note that coordinates are always index 0.)
*/
template <int INDEX>
class WeightArg
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return std::string("WeightArg<") + asString(INDEX) + "> (internal)";
        // static const std::string n = std::string("WeightArg<") + asString(INDEX) + "> (internal)";
        // return n;
    }
    
    template <class T, class BASE>
    struct Impl
    : public BASE
    {
        typedef WeightArgTag Tag;
        typedef void value_type;
        typedef void result_type;

        static const int value = INDEX;
        static const unsigned int workInPass = 0;
    };
};

/** \brief Compute weighted version of the statistic.
*/
template <class TAG>
class Weighted
{
  public:
    typedef typename StandardizeTag<TAG>::type   TargetTag;
    typedef typename TargetTag::Dependencies     Dependencies;
    
    static std::string name() 
    { 
        return std::string("Weighted<") + TargetTag::name() + " >";
        // static const std::string n = std::string("Weighted<") + TargetTag::name() + " >";
        // return n;
    }
    
    template <class IndexDefinition, class TagFound=typename IndexDefinition::Tag>
    struct WeightIndexSelector
    {
        template <class U, class NEXT>
        static double exec(CoupledHandle<U, NEXT> const & t)
        {
            return (double)*t; // default: CoupledHandle holds weights at the last (outermost) index 
        }
    };
    
    template <class IndexDefinition>
    struct WeightIndexSelector<IndexDefinition, WeightArgTag>
    {
        template <class U, class NEXT>
        static double exec(CoupledHandle<U, NEXT> const & t)
        {
            return (double)get<IndexDefinition::value>(t);
        }
    };
    
    template <class T, class BASE>
    struct Impl
    : public TargetTag::template Impl<T, BASE>
    {
        typedef typename TargetTag::template Impl<T, BASE> ImplType;
        
        typedef typename LookupTag<WeightArgTag, BASE>::type FindWeightIndex;
                
        template <class U, class NEXT>
        void update(CoupledHandle<U, NEXT> const & t)
        {
            ImplType::update(t, WeightIndexSelector<FindWeightIndex>::exec(t));
        }
    };
};

// Centralize by subtracting the mean and cache the result
class Centralize
{
  public:
    typedef Select<Mean> Dependencies;
    
    static std::string name() 
    { 
         return "Centralize (internal)";
        // static const std::string n("Centralize (internal)");
        // return n;
    }
   
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        static const unsigned int workInPass = 2;
        
        typedef typename AccumulatorResultTraits<U>::element_promote_type element_type;
        typedef typename AccumulatorResultTraits<U>::SumType              value_type;
        typedef value_type const &                                  result_type;

        mutable value_type value_;
        
        Impl()
        : value_()  // call default constructor explicitly to ensure zero initialization
        {}
        
        void reset()
        {
            value_ = element_type();
        }
    
        template <class Shape>
        void reshape(Shape const & s)
        {
            acc_detail::reshapeImpl(value_, s);
        }
        
        void update(U const & t) const
        {
            using namespace vigra::multi_math;
            value_ = t - getDependency<Mean>(*this);
        }
        
        void update(U const & t, double) const
        {
            update(t);
        }
        
        result_type operator()(U const & t) const
        {
            update(t);
            return value_;
        }
        
        result_type operator()() const
        {
            return value_;
        }
    };
};

/** \brief Modifier. Substract mean before computing statistic. 

Works in pass 2, %operator+=() not supported (merging not supported).
*/
template <class TAG>
class Central
{
  public:
    typedef typename StandardizeTag<TAG>::type                    TargetTag;
    typedef Select<Centralize, typename TargetTag::Dependencies>  Dependencies;
    
    static std::string name() 
    { 
        return std::string("Central<") + TargetTag::name() + " >";
        // static const std::string n = std::string("Central<") + TargetTag::name() + " >";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public TargetTag::template Impl<typename AccumulatorResultTraits<U>::SumType, BASE>
    {
        typedef typename TargetTag::template Impl<typename AccumulatorResultTraits<U>::SumType, BASE> ImplType;
        
        static const unsigned int workInPass = 2;
        
        void operator+=(Impl const & o)
        {
            vigra_precondition(false,
                "Central<...>::operator+=(): not supported.");
        }
    
        template <class T>
        void update(T const & t)
        {
            ImplType::update(getDependency<Centralize>(*this));
        }
        
        template <class T>
        void update(T const & t, double weight)
        {
            ImplType::update(getDependency<Centralize>(*this), weight);
        }
    };
};

    // alternative implementation without caching 
    //
// template <class TAG>
// class Central
// {
  // public:
    // typedef typename StandardizeTag<TAG>::type TargetTag;
    // typedef TypeList<Mean, typename TransferModifiers<Central<TargetTag>, typename TargetTag::Dependencies::type>::type> Dependencies;
    
    // template <class U, class BASE>
    // struct Impl
    // : public TargetTag::template Impl<typename AccumulatorResultTraits<U>::SumType, BASE>
    // {
        // typedef typename TargetTag::template Impl<typename AccumulatorResultTraits<U>::SumType, BASE> ImplType;
        
        // static const unsigned int workInPass = 2;
        
        // void operator+=(Impl const & o)
        // {
            // vigra_precondition(false,
                // "Central<...>::operator+=(): not supported.");
        // }
    
        // template <class T>
        // void update(T const & t)
        // {
            // ImplType::update(t - getDependency<Mean>(*this));
        // }
        
        // template <class T>
        // void update(T const & t, double weight)
        // {
            // ImplType::update(t - getDependency<Mean>(*this), weight);
        // }
    // };
// };


class PrincipalProjection
{
  public:
    typedef Select<Centralize, Principal<CoordinateSystem> > Dependencies;
    
    static std::string name() 
    { 
        return "PrincipalProjection (internal)";
        // static const std::string n("PrincipalProjection (internal)");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        static const unsigned int workInPass = 2;
        
        typedef typename AccumulatorResultTraits<U>::element_promote_type element_type;
        typedef typename AccumulatorResultTraits<U>::SumType              value_type;
        typedef value_type const &                                  result_type;

        mutable value_type value_;
        
        Impl()
        : value_()  // call default constructor explicitly to ensure zero initialization
        {}
        
        void reset()
        {
            value_ = element_type();
        }
    
        template <class Shape>
        void reshape(Shape const & s)
        {
            acc_detail::reshapeImpl(value_, s);
        }
        
        void update(U const & t) const
        {
            for(unsigned int k=0; k<t.size(); ++k)
            {
                value_[k] = getDependency<Principal<CoordinateSystem> >(*this)(0, k)*getDependency<Centralize>(*this)[0];
                for(unsigned int d=1; d<t.size(); ++d)
                    value_[k] += getDependency<Principal<CoordinateSystem> >(*this)(d, k)*getDependency<Centralize>(*this)[d];
            }
        }
        
        void update(U const & t, double) const
        {
            update(t);
        }
        
        result_type operator()(U const & t) const
        {
            getAccumulator<Centralize>(*this).update(t);
            update(t);
            return value_;
        }
        
        result_type operator()() const
        {
            return value_;
        }
    };
};

/** \brief Modifier. Project onto PCA eigenvectors.

    Works in pass 2, %operator+=() not supported (merging not supported).
*/
template <class TAG>
class Principal
{
  public:
    typedef typename StandardizeTag<TAG>::type                             TargetTag;
    typedef Select<PrincipalProjection, typename TargetTag::Dependencies>  Dependencies;
    
    static std::string name() 
    { 
        return std::string("Principal<") + TargetTag::name() + " >";
        // static const std::string n = std::string("Principal<") + TargetTag::name() + " >";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public TargetTag::template Impl<typename AccumulatorResultTraits<U>::SumType, BASE>
    {
        typedef typename TargetTag::template Impl<typename AccumulatorResultTraits<U>::SumType, BASE> ImplType;
        
        static const unsigned int workInPass = 2;
        
        void operator+=(Impl const & o)
        {
            vigra_precondition(false,
                "Principal<...>::operator+=(): not supported.");
        }
    
        template <class T>
        void update(T const & t)
        {
            ImplType::update(getDependency<PrincipalProjection>(*this));
        }
        
        template <class T>
        void update(T const & t, double weight)
        {
            ImplType::update(getDependency<PrincipalProjection>(*this), weight);
        }
    };
};

/*
important notes on modifiers:
 * upon accumulator creation, modifiers are reordered so that data preparation is innermost, 
   and data access is outermost, e.g.:
        Coord<DivideByCount<Principal<PowerSum<2> > > >
 * modifiers are automatically transfered to dependencies as appropriate
 * modifiers for lookup (getAccumulator and get) of dependent accumulators are automatically adjusted
 * modifiers must adjust workInPass for the contained accumulator as appropriate
 * we may implement convenience versions of Select that apply a modifier to all 
   contained tags at once
 * weighted accumulators have their own Count object when used together
   with unweighted ones (this is as yet untested - FIXME)
 * certain accumulators must remain unchanged when wrapped in certain modifiers: 
    * Count: always except for Weighted<Count> and CoordWeighted<Count>
    * Sum: data preparation modifiers
    * FlatScatterMatrixImpl, CovarianceEigensystemImpl: Principal and Whitened
 * will it be useful to implement initPass<N>() or finalizePass<N>() ?
*/

/****************************************************************************/
/*                                                                          */
/*                        the actual accumulators                           */
/*                                                                          */
/****************************************************************************/

/** \brief Basic statistic. Identity matrix of appropriate size.
*/
class CoordinateSystem
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return "CoordinateSystem";
        // static const std::string n("CoordinateSystem");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef double              element_type;
        typedef Matrix<double>      value_type;
        typedef value_type const &  result_type;

        value_type value_;
        
        Impl()
        : value_()  // call default constructor explicitly to ensure zero initialization
        {}
        
        void reset()
        {
            value_ = element_type();
        }

        template <class Shape>
        void reshape(Shape const & s)
        {
            acc_detail::reshapeImpl(value_, s);
        }
        
        result_type operator()() const
        {
            return value_;
        }
    };
};

template <class BASE, class T, 
          class ElementType=typename AccumulatorResultTraits<T>::element_promote_type, 
          class SumType=typename AccumulatorResultTraits<T>::SumType>
struct SumBaseImpl
: public BASE
{
    typedef ElementType         element_type;
    typedef SumType             value_type;
    typedef value_type const &  result_type;

    value_type value_;
    
    SumBaseImpl()
    : value_()  // call default constructor explicitly to ensure zero initialization
    {}
    
    void reset()
    {
        value_ = element_type();
    }

    template <class Shape>
    void reshape(Shape const & s)
    {
        acc_detail::reshapeImpl(value_, s);
    }
    
    void operator+=(SumBaseImpl const & o)
    {
        value_ += o.value_;
    }

    result_type operator()() const
    {
        return value_;
    }
};

// Count
template <>
class PowerSum<0>
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return "PowerSum<0>";
        // static const std::string n("PowerSum<0>");
        // return n;
    }
    
    template <class T, class BASE>
    struct Impl
    : public SumBaseImpl<BASE, T, double, double>
    {
        void update(T const & t)
        {
            ++this->value_;
        }
        
        void update(T const & t, double weight)
        {
            this->value_ += weight;
        }
    };
};

// Sum
template <>
class PowerSum<1>
{
  public:
    typedef Select<> Dependencies;
     
    static std::string name() 
    { 
        return "PowerSum<1>";
        // static const std::string n("PowerSum<1>");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public SumBaseImpl<BASE, U>
    {
        void update(U const & t)
        {
            this->value_ += t;
        }
        
        void update(U const & t, double weight)
        {
            this->value_ += weight*t;
        }
    };
};

/** \brief Basic statistic. PowerSum<N> =@f$ \sum_i x_i^N @f$

    Works in pass 1, %operator+=() supported (merging supported).
*/
template <unsigned N>
class PowerSum
{
  public:
    typedef Select<> Dependencies;
     
    static std::string name() 
    { 
        return std::string("PowerSum<") + asString(N) + ">";
        // static const std::string n = std::string("PowerSum<") + asString(N) + ">";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public SumBaseImpl<BASE, U>
    {
        void update(U const & t)
        {
            using namespace vigra::multi_math;            
            this->value_ += pow(t, (int)N);
        }
        
        void update(U const & t, double weight)
        {
            using namespace vigra::multi_math;            
            this->value_ += weight*pow(t, (int)N);
        }
    };
};

template <>
class AbsPowerSum<1>
{
  public:
    typedef Select<> Dependencies;
     
    static std::string name() 
    { 
        return "AbsPowerSum<1>";
        // static const std::string n("AbsPowerSum<1>");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public SumBaseImpl<BASE, U>
    {
        void update(U const & t)
        {
            using namespace vigra::multi_math;            
            this->value_ += abs(t);
        }
        
        void update(U const & t, double weight)
        {
            using namespace vigra::multi_math;            
            this->value_ += weight*abs(t);
        }
    };
};

/** \brief Basic statistic. AbsPowerSum<N> =@f$ \sum_i |x_i|^N @f$

    Works in pass 1, %operator+=() supported (merging supported).
*/
template <unsigned N>
class AbsPowerSum
{
  public:
    typedef Select<> Dependencies;
     
    static std::string name() 
    { 
        return std::string("AbsPowerSum<") + asString(N) + ">";
        // static const std::string n = std::string("AbsPowerSum<") + asString(N) + ">";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public SumBaseImpl<BASE, U>
    {
        void update(U const & t)
        {
            using namespace vigra::multi_math;            
            this->value_ += pow(abs(t), (int)N);
        }
        
        void update(U const & t, double weight)
        {
            using namespace vigra::multi_math;            
            this->value_ += weight*pow(abs(t), (int)N);
        }
    };
};

template <class BASE, class VALUE_TYPE, class U>
struct CachedResultBase
: public BASE
{
    typedef typename AccumulatorResultTraits<U>::element_type  element_type;
    typedef VALUE_TYPE                                         value_type;
    typedef value_type const &                                 result_type;

    mutable value_type value_;
    
    CachedResultBase()
    : value_()  // call default constructor explicitly to ensure zero initialization
    {}
    
    void reset()
    {
        value_ = element_type();
        this->setClean();
    }

    template <class Shape>
    void reshape(Shape const & s)
    {
        acc_detail::reshapeImpl(value_, s);
    }

    void operator+=(CachedResultBase const &)
    {
        this->setDirty();
    }

    void update(U const &)
    {
        this->setDirty();
    }
    
    void update(U const &, double)
    {
         this->setDirty();
    }
};

// cached Mean and Variance
/** \brief Modifier. Divide statistic by Count:  DivideByCount<TAG> = TAG / Count .
*/
template <class TAG>
class DivideByCount
{
  public:
    typedef typename StandardizeTag<TAG>::type TargetTag;
    typedef Select<TargetTag, Count> Dependencies;
  
    static std::string name() 
    { 
        return std::string("DivideByCount<") + TargetTag::name() + " >";
        // static const std::string n = std::string("DivideByCount<") + TargetTag::name() + " >";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public CachedResultBase<BASE, typename LookupDependency<TargetTag, BASE>::value_type, U> 
    {
        typedef typename CachedResultBase<BASE, typename LookupDependency<TargetTag, BASE>::value_type, U>::result_type result_type;
        
        result_type operator()() const
        {
            if(this->isDirty())
            {
                using namespace multi_math;
                this->value_ = getDependency<TargetTag>(*this) / getDependency<Count>(*this);
                this->setClean();
            }
            return this->value_;
        }
    };
};

// UnbiasedVariance
/** \brief Modifier. Divide statistics by Count-1:  DivideUnbiased<TAG> = TAG / (Count-1)
*/
template <class TAG>
class DivideUnbiased
{
  public:
    typedef typename StandardizeTag<TAG>::type TargetTag;
    typedef Select<TargetTag, Count> Dependencies;
      
    static std::string name() 
    { 
        return std::string("DivideUnbiased<") + TargetTag::name() + " >";
        // static const std::string n = std::string("DivideUnbiased<") + TargetTag::name() + " >";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename LookupDependency<TargetTag, BASE>::value_type  value_type;
        typedef value_type                                       result_type;
        
        result_type operator()() const
        {
            using namespace multi_math;
            return getDependency<TargetTag>(*this) / (getDependency<Count>(*this) - 1.0);
        }
    };
};

// RootMeanSquares and StdDev
/** \brief Modifier. RootDivideByCount<TAG> = sqrt( TAG/Count )
*/
template <class TAG>
class RootDivideByCount
{
  public:
    typedef typename StandardizeTag<DivideByCount<TAG> >::type TargetTag;
    typedef Select<TargetTag> Dependencies;
    
    static std::string name() 
    { 
        typedef typename StandardizeTag<TAG>::type InnerTag;
        return std::string("RootDivideByCount<") + InnerTag::name() + " >";
        // static const std::string n = std::string("RootDivideByCount<") + InnerTag::name() + " >";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename LookupDependency<TargetTag, BASE>::value_type  value_type;
        typedef value_type                                       result_type;
        
        result_type operator()() const
        {
            using namespace multi_math;
            return sqrt(getDependency<TargetTag>(*this));
        }
    };
};

// UnbiasedStdDev
/** \brief Modifier. RootDivideUnbiased<TAG> = sqrt( TAG / (Count-1) )
*/
template <class TAG>
class RootDivideUnbiased
{
  public:
    typedef typename StandardizeTag<DivideUnbiased<TAG> >::type TargetTag;
    typedef Select<TargetTag> Dependencies;
    
    static std::string name() 
    { 
        typedef typename StandardizeTag<TAG>::type InnerTag;
        return std::string("RootDivideUnbiased<") + InnerTag::name() + " >";
        // static const std::string n = std::string("RootDivideUnbiased<") + InnerTag::name() + " >";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename LookupDependency<TargetTag, BASE>::value_type  value_type;
        typedef value_type                                       result_type;
        
        result_type operator()() const
        {
            using namespace multi_math;
            return sqrt(getDependency<TargetTag>(*this));
        }
    };
};

/** \brief Spezialization: works in pass 1, %operator+=() supported (merging supported).
*/
template <>
class Central<PowerSum<2> >
{
  public:
    typedef Select<Mean, Count> Dependencies;
     
    static std::string name() 
    { 
        return "Central<PowerSum<2> >";
        // static const std::string n("Central<PowerSum<2> >");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public SumBaseImpl<BASE, U>
    {
        void operator+=(Impl const & o)
        {
            using namespace vigra::multi_math;
            double n1 = getDependency<Count>(*this), n2 = getDependency<Count>(o);
            if(n1 == 0.0)
            {
                this->value_ = o.value_;
            }
            else if(n2 != 0.0)
            {
                this->value_ += o.value_ + n1 * n2 / (n1 + n2) * sq(getDependency<Mean>(*this) - getDependency<Mean>(o));
            }
        }
    
        void update(U const & t)
        {
            double n = getDependency<Count>(*this);
            if(n > 1.0)
            {
                using namespace vigra::multi_math;
                this->value_ += n / (n - 1.0) * sq(getDependency<Mean>(*this) - t);
            }
        }
        
        void update(U const & t, double weight)
        {
            double n = getDependency<Count>(*this);
            if(n > weight)
            {
                using namespace vigra::multi_math;
                this->value_ += n / (n - weight) * sq(getDependency<Mean>(*this) - t);
            }
        }
    };
};

/** \brief Specialization: works in pass 2, %operator+=() supported (merging supported).
*/
template <>
class Central<PowerSum<3> >
{
  public:
    typedef Select<Centralize, Count, Mean, Central<PowerSum<2> > > Dependencies;
     
    static std::string name() 
    { 
        return "Central<PowerSum<3> >";
        // static const std::string n("Central<PowerSum<3> >");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public SumBaseImpl<BASE, U>
    {
        typedef typename SumBaseImpl<BASE, U>::value_type value_type;

        static const unsigned int workInPass = 2;
        
        void operator+=(Impl const & o)
        {
            typedef Central<PowerSum<2> > Sum2Tag;
            
            using namespace vigra::multi_math;
            double n1 = getDependency<Count>(*this), n2 = getDependency<Count>(o);
            if(n1 == 0.0)
            {
                this->value_ = o.value_;
            }
            else if(n2 != 0.0)
            {
                double n = n1 + n2;
                double weight = n1 * n2 * (n1 - n2) / sq(n);
                value_type delta = getDependency<Mean>(o) - getDependency<Mean>(*this);
                this->value_ += o.value_ + weight * pow(delta, 3) +
                               3.0 / n * delta * (n1 * getDependency<Sum2Tag>(o) - n2 * getDependency<Sum2Tag>(*this));
            }
        }
    
        void update(U const & t)
        {
            using namespace vigra::multi_math;            
            this->value_ += pow(getDependency<Centralize>(*this), 3);
        }
        
        void update(U const & t, double weight)
        {
            using namespace vigra::multi_math;            
            this->value_ += weight*pow(getDependency<Centralize>(*this), 3);
        }
    };
};
/** \brief Specialization: works in pass 2, %operator+=() supported (merging supported).
*/
template <>
class Central<PowerSum<4> >
{
  public:
    typedef Select<Centralize, Central<PowerSum<3> > > Dependencies;
     
    static std::string name() 
    { 
        return "Central<PowerSum<4> >";
        // static const std::string n("Central<PowerSum<4> >");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public SumBaseImpl<BASE, U>
    {
        typedef typename SumBaseImpl<BASE, U>::value_type value_type;

        static const unsigned int workInPass = 2;
        
        void operator+=(Impl const & o)
        {
            typedef Central<PowerSum<2> > Sum2Tag;
            typedef Central<PowerSum<3> > Sum3Tag;

            using namespace vigra::multi_math;
            double n1 = getDependency<Count>(*this), n2 = getDependency<Count>(o);
            if(n1 == 0.0)
            {
                this->value_ = o.value_;
            }
            else if(n2 != 0.0)
            {
                double n = n1 + n2;
                double n1_2 = sq(n1);
                double n2_2 = sq(n2);
                double n_2 = sq(n);
                double weight = n1 * n2 * (n1_2 - n1*n2 + n2_2) / n_2 / n;
                value_type delta = getDependency<Mean>(o) - getDependency<Mean>(*this);
                this->value_ += o.value_ + weight * pow(delta, 4) +
                              6.0 / n_2 * sq(delta) * (n1_2 * getDependency<Sum2Tag>(o) + n2_2 * getDependency<Sum2Tag>(*this)) +
                              4.0 / n * delta * (n1 * getDependency<Sum3Tag>(o) - n2 * getDependency<Sum3Tag>(*this));
            }
        }
    
        void update(U const & t)
        {
            using namespace vigra::multi_math;            
            this->value_ += pow(getDependency<Centralize>(*this), 4);
        }
        
        void update(U const & t, double weight)
        {
            using namespace vigra::multi_math;            
            this->value_ += weight*pow(getDependency<Centralize>(*this), 4);
        }
    };
};

/** \brief Basic statistic. Skewness. 

    %Skewness =@f$ \frac{ \frac{1}{n}\sum_i (x_i-\hat{x})^3 }{ (\frac{1}{n}\sum_i (x_i-\hat{x})^2)^{3/2} } @f$ .
    Works in pass 2, %operator+=() supported (merging supported).
*/
class Skewness
{
  public:
    typedef Select<Central<PowerSum<2> >, Central<PowerSum<3> > > Dependencies;
    
    static std::string name() 
    { 
        return "Skewness";
        // static const std::string n("Skewness");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        static const unsigned int workInPass = 2;
        
        typedef typename LookupDependency<Central<PowerSum<3> >, BASE>::value_type   value_type;
        typedef value_type                                                    result_type;

        result_type operator()() const
        {
            typedef Central<PowerSum<3> > Sum3;
            typedef Central<PowerSum<2> > Sum2;
        
                        using namespace multi_math;
            return sqrt(getDependency<Count>(*this)) * getDependency<Sum3>(*this) / pow(getDependency<Sum2>(*this), 1.5);
        }
    };
};

/** \brief Basic statistic. Unbiased Skewness.

    Works in pass 2, %operator+=() supported (merging supported).
*/
class UnbiasedSkewness
{
  public:
    typedef Select<Skewness> Dependencies;
    
    static std::string name() 
    { 
        return "UnbiasedSkewness";
        // static const std::string n("UnbiasedSkewness");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        static const unsigned int workInPass = 2;
        
        typedef typename LookupDependency<Central<PowerSum<3> >, BASE>::value_type   value_type;
        typedef value_type                                                    result_type;

        result_type operator()() const
        {
                        using namespace multi_math;
            double n = getDependency<Count>(*this);
            return sqrt(n*(n-1.0)) / (n - 2.0) * getDependency<Skewness>(*this);
        }
    };
};

/** \brief Basic statistic. Kurtosis. 

    %Kurtosis = @f$ \frac{ \frac{1}{n}\sum_i (x_i-\bar{x})^4 }{
    (\frac{1}{n} \sum_i(x_i-\bar{x})^2)^2 } - 3 @f$ . 
    Works in pass 2, %operator+=() supported (merging supported).
*/
class Kurtosis
{
  public:
    typedef Select<Central<PowerSum<2> >, Central<PowerSum<4> > > Dependencies;
    
    static std::string name() 
    { 
        return "Kurtosis";
        // static const std::string n("Kurtosis");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        static const unsigned int workInPass = 2;
        
        typedef typename LookupDependency<Central<PowerSum<4> >, BASE>::value_type value_type;
        typedef value_type                                                  result_type;

        result_type operator()() const
        {
            typedef Central<PowerSum<4> > Sum4;
            typedef Central<PowerSum<2> > Sum2;
        
                        using namespace multi_math;
            return getDependency<Count>(*this) * getDependency<Sum4>(*this) / sq(getDependency<Sum2>(*this)) - value_type(3.0);
        }
    };
};

/** \brief Basic statistic. Unbiased Kurtosis.

    Works in pass 2, %operator+=() supported (merging supported).
*/
class UnbiasedKurtosis
{
  public:
    typedef Select<Kurtosis> Dependencies;
    
    static std::string name() 
    { 
        return "UnbiasedKurtosis";
        // static const std::string n("UnbiasedKurtosis");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        static const unsigned int workInPass = 2;
        
        typedef typename LookupDependency<Central<PowerSum<4> >, BASE>::value_type value_type;
        typedef value_type                                                  result_type;

        result_type operator()() const
        {
                        using namespace multi_math;
            double n = getDependency<Count>(*this);
            return (n-1.0)/((n-2.0)*(n-3.0))*((n+1.0)*getDependency<Kurtosis>(*this) + value_type(6.0));
        }
    };
};

namespace acc_detail {

template <class Scatter, class Sum>
void updateFlatScatterMatrix(Scatter & sc, Sum const & s, double w)
{
    int size = s.size();
    for(MultiArrayIndex j=0, k=0; j<size; ++j)
        for(MultiArrayIndex i=j; i<size; ++i, ++k)
            sc[k] += w*s[i]*s[j];
}

template <class Sum>
void updateFlatScatterMatrix(double & sc, Sum const & s, double w)
{
    sc += w*s*s;
}

template <class Cov, class Scatter>
void flatScatterMatrixToScatterMatrix(Cov & cov, Scatter const & sc)
{
    int size = cov.shape(0), k=0;
    for(MultiArrayIndex j=0; j<size; ++j)
    {
        cov(j,j) = sc[k++];
        for(MultiArrayIndex i=j+1; i<size; ++i)
        {
            cov(i,j) = sc[k++];
            cov(j,i) = cov(i,j);
        }
    }
}

template <class Scatter>
void flatScatterMatrixToScatterMatrix(double & cov, Scatter const & sc)
{
    cov = sc;
}

template <class Cov, class Scatter>
void flatScatterMatrixToCovariance(Cov & cov, Scatter const & sc, double n)
{
    int size = cov.shape(0), k=0;
    for(MultiArrayIndex j=0; j<size; ++j)
    {
        cov(j,j) = sc[k++] / n;
        for(MultiArrayIndex i=j+1; i<size; ++i)
        {
            cov(i,j) = sc[k++] / n;
            cov(j,i) = cov(i,j);
        }
    }
}

template <class Scatter>
void flatScatterMatrixToCovariance(double & cov, Scatter const & sc, double n)
{
    cov = sc / n;
}

} // namespace acc_detail

// we only store the flattened upper triangular part of the scatter matrix
/** \brief Basic statistic. Flattened uppter-triangular part of scatter matrix.

    Works in pass 1, %operator+=() supported (merging supported).
*/
class FlatScatterMatrix
{
  public:
    typedef Select<Mean, Count> Dependencies;
    
    static std::string name() 
    { 
        return "FlatScatterMatrix";
        // static const std::string n("FlatScatterMatrix");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename AccumulatorResultTraits<U>::element_promote_type  element_type;
        typedef typename AccumulatorResultTraits<U>::FlatCovarianceType    value_type;
        typedef value_type const &                                   result_type;
       
        typedef typename AccumulatorResultTraits<U>::SumType        SumType;

        value_type value_;
        SumType     diff_;
        
        Impl()
        : value_(),  // call default constructor explicitly to ensure zero initialization
          diff_()
        {}
        
        void reset()
        {
            value_ = element_type();
        }
    
        template <class Shape>
        void reshape(Shape const & s)
        {
            int size = prod(s);
            acc_detail::reshapeImpl(value_, Shape1(size*(size+1)/2));
            acc_detail::reshapeImpl(diff_, s);
        }
        
        void operator+=(Impl const & o)
        {
            double n1 = getDependency<Count>(*this), n2 = getDependency<Count>(o);
            if(n1 == 0.0)
            {
                value_ = o.value_;
            }
            else if(n2 != 0.0)
            {
                using namespace vigra::multi_math;
                diff_ = getDependency<Mean>(*this) - getDependency<Mean>(o);
                acc_detail::updateFlatScatterMatrix(value_, diff_, n1 * n2 / (n1 + n2));
                value_ += o.value_;
            }
        }
    
        void update(U const & t)
        {
            compute(t);
        }
        
        void update(U const & t, double weight)
        {
            compute(t, weight);
        }
        
        result_type operator()() const
        {
            return value_;
        }
        
      private:
        void compute(U const & t, double weight = 1.0)
        {
            double n = getDependency<Count>(*this);
            if(n > weight)
            {
                using namespace vigra::multi_math;
                diff_ = getDependency<Mean>(*this) - t;
                acc_detail::updateFlatScatterMatrix(value_, diff_, n * weight / (n - weight));
            }
        }
    };
};

// Covariance
template <>
class DivideByCount<FlatScatterMatrix>
{
  public:
    typedef Select<FlatScatterMatrix, Count> Dependencies;
    
    static std::string name() 
    { 
        return "DivideByCount<FlatScatterMatrix>";
        // static const std::string n("DivideByCount<FlatScatterMatrix>");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public CachedResultBase<BASE, typename AccumulatorResultTraits<U>::CovarianceType, U>
    {
        typedef CachedResultBase<BASE, typename AccumulatorResultTraits<U>::CovarianceType, U> BaseType;      
        typedef typename BaseType::result_type result_type;
        
        template <class Shape>
        void reshape(Shape const & s)
        {
            int size = prod(s);
            acc_detail::reshapeImpl(this->value_, Shape2(size,size));
        }
        
        result_type operator()() const
        {
            if(this->isDirty())
            {
                acc_detail::flatScatterMatrixToCovariance(this->value_, getDependency<FlatScatterMatrix>(*this), getDependency<Count>(*this));
                this->setClean();
            }
            return this->value_;
        }
    };
};

// UnbiasedCovariance
template <>
class DivideUnbiased<FlatScatterMatrix>
{
  public:
    typedef Select<FlatScatterMatrix, Count> Dependencies;
    
    static std::string name() 
    { 
        return "DivideUnbiased<FlatScatterMatrix>";
        // static const std::string n("DivideUnbiased<FlatScatterMatrix>");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public CachedResultBase<BASE, typename AccumulatorResultTraits<U>::CovarianceType, U>
    {
        typedef CachedResultBase<BASE, typename AccumulatorResultTraits<U>::CovarianceType, U> BaseType;      
        typedef typename BaseType::result_type result_type;
        
        template <class Shape>
        void reshape(Shape const & s)
        {
            int size = prod(s);
            acc_detail::reshapeImpl(this->value_, Shape2(size,size));
        }
        
        result_type operator()() const
        {
            if(this->isDirty())
            {
                acc_detail::flatScatterMatrixToCovariance(this->value_, getDependency<FlatScatterMatrix>(*this), getDependency<Count>(*this) - 1.0);
                this->setClean();
            }
            return this->value_;
        }
    };
};

/** Basic statistic. ScatterMatrixEigensystem (?)
*/
class ScatterMatrixEigensystem
{
  public:
    typedef Select<FlatScatterMatrix> Dependencies;
    
    static std::string name() 
    { 
        return "ScatterMatrixEigensystem";
        // static const std::string n("ScatterMatrixEigensystem");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename AccumulatorResultTraits<U>::element_promote_type  element_type;
        typedef typename AccumulatorResultTraits<U>::SumType               EigenvalueType;
        typedef typename AccumulatorResultTraits<U>::CovarianceType        EigenvectorType;
        typedef std::pair<EigenvalueType, EigenvectorType>                 value_type;
        typedef value_type const &                                         result_type;

        mutable value_type value_;
        
        Impl()
        : value_()
        {}
        
        void operator+=(Impl const & o)
        {
            if(!acc_detail::hasDataImpl(value_.second))
            {
                acc_detail::copyShapeImpl(o.value_.first, value_.first);
                acc_detail::copyShapeImpl(o.value_.second, value_.second);
            }
            this->setDirty();
        }

        void update(U const &)
        {
            this->setDirty();
        }
        
        void update(U const &, double)
        {
             this->setDirty();
        }

        void reset()
        {
            value_.first = element_type();
            value_.second = element_type();
            this->setClean();
        }
    
        template <class Shape>
        void reshape(Shape const & s)
        {
            int size = prod(s);
            acc_detail::reshapeImpl(value_.first, Shape1(size));
            acc_detail::reshapeImpl(value_.second, Shape2(size,size));
        }
        
        result_type operator()() const
        {
            if(this->isDirty())
            {
                compute(getDependency<FlatScatterMatrix>(*this), value_.first, value_.second);
                this->setClean();
            }
            return value_;
        }
        
      private:
        template <class Flat, class EW, class EV>
        static void compute(Flat const & flatScatter, EW & ew, EV & ev)
        {
            EigenvectorType scatter(ev.shape());
            acc_detail::flatScatterMatrixToScatterMatrix(scatter, flatScatter);
            // create a view because EW could be a TinyVector
            MultiArrayView<2, element_type> ewview(Shape2(ev.shape(0), 1), &ew[0]);
            symmetricEigensystem(scatter, ewview, ev);
        }
        
        static void compute(double v, double & ew, double & ev)
        {
            ew = v;
            ev = 1.0;
        }
    };
};

// CovarianceEigensystem
template <>
class DivideByCount<ScatterMatrixEigensystem>
{
  public:
    typedef Select<ScatterMatrixEigensystem, Count> Dependencies;
    
    static std::string name() 
    { 
        return "DivideByCount<ScatterMatrixEigensystem>";
        // static const std::string n("DivideByCount<ScatterMatrixEigensystem>");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename LookupDependency<ScatterMatrixEigensystem, BASE>::type  SMImpl;
        typedef typename SMImpl::element_type                             element_type;
        typedef typename SMImpl::EigenvalueType                           EigenvalueType;
        typedef typename SMImpl::EigenvectorType                          EigenvectorType;
        typedef std::pair<EigenvalueType, EigenvectorType const &>        value_type;
        typedef value_type const &                                        result_type;

        mutable value_type value_;
        
        Impl()
        : value_(EigenvalueType(), BASE::template call_getDependency<ScatterMatrixEigensystem>().second)
        {}
        
        void operator+=(Impl const &)
        {
            this->setDirty();
        }

        void update(U const &)
        {
            this->setDirty();
        }
        
        void update(U const &, double)
        {
             this->setDirty();
        }

        void reset()
        {
            value_.first = element_type();
            this->setClean();
        }
    
        template <class Shape>
        void reshape(Shape const & s)
        {
            int size = prod(s);
            acc_detail::reshapeImpl(value_.first, Shape2(size,1));
        }
        
        result_type operator()() const
        {
            if(this->isDirty())
            {
                value_.first = getDependency<ScatterMatrixEigensystem>(*this).first / getDependency<Count>(*this);
                this->setClean();
            }
            return value_;
        }
    };
};

// alternative implementation of CovarianceEigensystem - solve eigensystem directly
//
// template <>
// class DivideByCount<ScatterMatrixEigensystem>
// {
  // public:
    // typedef Select<Covariance> Dependencies;
    
    // template <class U, class BASE>
    // struct Impl
    // : public BASE
    // {
        // typedef typename AccumulatorResultTraits<U>::element_promote_type  element_type;
        // typedef typename AccumulatorResultTraits<U>::SumType               EigenvalueType;
        // typedef typename AccumulatorResultTraits<U>::CovarianceType        EigenvectorType;
        // typedef std::pair<EigenvalueType, EigenvectorType>                 value_type;
        // typedef value_type const &                                         result_type;

        // mutable value_type value_;
        
        // Impl()
        // : value_()
        // {}
        
        // void operator+=(Impl const &)
        // {
            // this->setDirty();
        // }

        // void update(U const &)
        // {
            // this->setDirty();
        // }
        
        // void update(U const &, double)
        // {
             // this->setDirty();
        // }

        // void reset()
        // {
            // value_.first = element_type();
            // value_.second = element_type();
            // this->setClean();
        // }
    
        // template <class Shape>
        // void reshape(Shape const & s)
        // {
            // int size = prod(s);
            // acc_detail::reshapeImpl(value_.first, Shape2(size,1));
            // acc_detail::reshapeImpl(value_.second, Shape2(size,size));
        // }
        
        // result_type operator()() const
        // {
            // if(this->isDirty())
            // {
                // compute(getDependency<Covariance>(*this), value_.first, value_.second);
                // this->setClean();
            // }
            // return value_;
        // }
        
      // private:
        // template <class Cov, class EW, class EV>
        // static void compute(Cov const & cov, EW & ew, EV & ev)
        // {
            // // create a view because EW could be a TinyVector
            // MultiArrayView<2, element_type> ewview(Shape2(cov.shape(0), 1), &ew[0]);
            // symmetricEigensystem(cov, ewview, ev);
        // }
        
        // static void compute(double cov, double & ew, double & ev)
        // {
            // ew = cov;
            // ev = 1.0;
        // }
    // };
// };

// covariance eigenvalues
/** \brief Specialization (covariance eigenvalues): works in pass 1, %operator+=() supported (merging).
*/
template <>
class Principal<PowerSum<2> >
{
  public:
    typedef Select<ScatterMatrixEigensystem> Dependencies;
     
    static std::string name() 
    { 
        return "Principal<PowerSum<2> >";
        // static const std::string n("Principal<PowerSum<2> >");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename LookupDependency<ScatterMatrixEigensystem, BASE>::type::EigenvalueType value_type;
        typedef value_type const &                                                       result_type;
        
        result_type operator()() const
        {
            return getDependency<ScatterMatrixEigensystem>(*this).first;
        }
    };
};


// Principal<CoordinateSystem> == covariance eigenvectors
/** \brief Specialization (covariance eigenvectors): works in pass 1, %operator+=() supported (merging).
*/
template <>
class Principal<CoordinateSystem>
{
  public:
    typedef Select<ScatterMatrixEigensystem> Dependencies;
     
    static std::string name() 
    { 
        return "Principal<CoordinateSystem>";
        // static const std::string n("Principal<CoordinateSystem>");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename LookupDependency<ScatterMatrixEigensystem, BASE>::type::EigenvectorType value_type;
        typedef value_type const &                                                        result_type;
        
        result_type operator()() const
        {
            return getDependency<ScatterMatrixEigensystem>(*this).second;
        }
    };
};

/** \brief Basic statistic. %Minimum value.

    Works in pass 1, %operator+=() supported (merging supported).
*/
class Minimum
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return "Minimum";
        // static const std::string n("Minimum");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename AccumulatorResultTraits<U>::element_type element_type;
        typedef typename AccumulatorResultTraits<U>::MinmaxType   value_type;
        typedef value_type const &                                result_type;

        value_type value_;
        
        Impl()
        {
            value_ = NumericTraits<element_type>::max();
        }
        
        void reset()
        {
            value_ = NumericTraits<element_type>::max();
        }
    
        template <class Shape>
        void reshape(Shape const & s)
        {
            acc_detail::reshapeImpl(value_, s, NumericTraits<element_type>::max());
        }
        
        void operator+=(Impl const & o)
        {
            updateImpl(o.value_); // necessary because std::min causes ambiguous overload
        }
    
        void update(U const & t)
        {
            updateImpl(t);
        }
        
        void update(U const & t, double)
        {
            updateImpl(t);
        }
        
        result_type operator()() const
        {
            return value_;
        }
        
      private:
        template <class T>
        void updateImpl(T const & o)
        {
            using namespace multi_math;
            value_ = min(value_, o);
        }
        
        template <class T, class Alloc>
        void updateImpl(MultiArray<1, T, Alloc> const & o)
        {
            value_ = multi_math::min(value_, o);
        }
    };
};

/** \brief Basic statistic. %Maximum value.

    Works in pass 1, %operator+=() supported (merging supported).
*/
class Maximum
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return "Maximum";
        // static const std::string n("Maximum");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename AccumulatorResultTraits<U>::element_type element_type;
        typedef typename AccumulatorResultTraits<U>::MinmaxType   value_type;
        typedef value_type const &                                result_type;

        value_type value_;
        
        Impl()
        {
            value_ = NumericTraits<element_type>::min();
        }
        
        void reset()
        {
            value_ = NumericTraits<element_type>::min();
        }
    
        template <class Shape>
        void reshape(Shape const & s)
        {
            acc_detail::reshapeImpl(value_, s, NumericTraits<element_type>::min());
        }
        
        void operator+=(Impl const & o)
        {
            updateImpl(o.value_); // necessary because std::max causes ambiguous overload
        }
    
        void update(U const & t)
        {
            updateImpl(t);
        }
        
        void update(U const & t, double)
        {
            updateImpl(t);
        }
        
        result_type operator()() const
        {
            return value_;
        }
        
      private:
        template <class T>
        void updateImpl(T const & o)
        {
            using namespace multi_math;
            value_ = max(value_, o);
        }
        
        template <class T, class Alloc>
        void updateImpl(MultiArray<1, T, Alloc> const & o)
        {
            value_ = multi_math::max(value_, o);
        }
    };
};

/** \brief Basic statistic. Data value where weight assumes its minimal value. 

    Weights must be given. Coord<ArgMinWeight> gives coordinate where weight assumes its minimal value. Works in pass 1, %operator+=() supported (merging supported).
*/
class ArgMinWeight
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return "ArgMinWeight";
        // static const std::string n("ArgMinWeight");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename AccumulatorResultTraits<U>::element_type element_type;
        typedef typename AccumulatorResultTraits<U>::MinmaxType   value_type;
        typedef value_type const &                                result_type;

        double min_weight_;
        value_type value_;
        
        Impl()
        : min_weight_(NumericTraits<double>::max()),
          value_()
        {}
        
        void reset()
        {
            min_weight_ = NumericTraits<double>::max();
            value_ = element_type();
        }
    
        template <class Shape>
        void reshape(Shape const & s)
        {
            acc_detail::reshapeImpl(value_, s);
        }
        
        void operator+=(Impl const & o)
        {
            using namespace multi_math;
            if(o.min_weight_ < min_weight_)
            {
                min_weight_ = o.min_weight_;
                value_ = o.value_;
            }
        }
    
        void update(U const & t)
        {
            vigra_precondition(false, "ArgMinWeight::update() needs weights.");
        }
        
        void update(U const & t, double weight)
        {
            if(weight < min_weight_)
            {
                min_weight_ = weight;
                value_ = t;
            }
        }
        
        result_type operator()() const
        {
            return value_;
        }
    };
};

/** \brief Basic statistic. Data where weight assumes its maximal value. 

    Weights must be given. Coord<ArgMinWeight> gives coordinate where weight assumes its maximal value. Works in pass 1, %operator+=() supported (merging supported).
*/
class ArgMaxWeight
{
  public:
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return "ArgMaxWeight";
        // static const std::string n("ArgMaxWeight");
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public BASE
    {
        typedef typename AccumulatorResultTraits<U>::element_type element_type;
        typedef typename AccumulatorResultTraits<U>::MinmaxType   value_type;
        typedef value_type const &                                result_type;

        double max_weight_;
        value_type value_;
        
        Impl()
        : max_weight_(NumericTraits<double>::min()),
          value_()
        {}
        
        void reset()
        {
            max_weight_ = NumericTraits<double>::min();
            value_ = element_type();
        }
    
        template <class Shape>
        void reshape(Shape const & s)
        {
            acc_detail::reshapeImpl(value_, s);
        }
        
        void operator+=(Impl const & o)
        {
            using namespace multi_math;
            if(o.max_weight_ > max_weight_)
            {
                max_weight_ = o.max_weight_;
                value_ = o.value_;
            }
        }
    
        void update(U const & t)
        {
            vigra_precondition(false, "ArgMaxWeight::update() needs weights.");
        }
        
        void update(U const & t, double weight)
        {
            if(weight > max_weight_)
            {
                max_weight_ = weight;
                value_ = t;
            }
        }
        
        result_type operator()() const
        {
            return value_;
        }
    };
};


template <class BASE, int BinCount>
class HistogramBase
: public BASE
{
  public:
  
    typedef double                        element_type;
    typedef TinyVector<double, BinCount>  value_type;
    typedef value_type const &            result_type;
    
    value_type value_;
    double left_outliers, right_outliers;
    
    HistogramBase()
    : value_(),
      left_outliers(), 
      right_outliers()
    {}
    
    void reset()
    {
        value_ = element_type();
        left_outliers = 0.0;
        right_outliers = 0.0;
    }

    void operator+=(HistogramBase const & o)
    {
        value_ += o.value_;
        left_outliers += o.left_outliers;
        right_outliers += o.right_outliers;
    }
        
    result_type operator()() const
    {
        return value_;
    }
};

template <class BASE>
class HistogramBase<BASE, 0>
: public BASE
{
  public:
  
    typedef double                        element_type;
    typedef MultiArray<1, double>         value_type;
    typedef value_type const &            result_type;
    
    value_type value_;
    double left_outliers, right_outliers;
    
    HistogramBase()
    : value_(),
      left_outliers(), 
      right_outliers()
    {}
    
    void reset()
    {
        value_ = element_type();
        left_outliers = 0.0;
        right_outliers = 0.0;
    }
    
    void operator+=(HistogramBase const & o)
    {
        if(value_.size() == 0)
        {
            value_ = o.value_;
        }
        else if(o.value_.size() > 0)
        {
            vigra_precondition(value_.size() == o.value_.size(),
                "HistogramBase::operator+=(): bin counts must be equal.");
            value_ += o.value_;
        }
        left_outliers += o.left_outliers;
        right_outliers += o.right_outliers;
    }
        
    void setBinCount(int binCount)
    {
        vigra_precondition(binCount > 0,
            "HistogramBase:.setBinCount(): binCount > 0 required.");
        value_type(Shape1(binCount)).swap(value_);
    }

    result_type operator()() const
    {
        return value_;
    }
};

template <class BASE, int BinCount, class U=typename BASE::input_type>
class RangeHistogramBase
: public HistogramBase<BASE, BinCount>
{
  public:
    double scale_, offset_, inverse_scale_;
    
    RangeHistogramBase()
    : scale_(),
      offset_(), 
      inverse_scale_()
    {}
    
    void reset()
    {
        scale_ = 0.0;
        offset_ = 0.0;
        inverse_scale_ = 0.0;
        HistogramBase<BASE, BinCount>::reset();
    }

    void operator+=(RangeHistogramBase const & o)
    {
        vigra_precondition(scale_ == 0.0 || o.scale_ == 0.0 || (scale_ == o.scale_ && offset_ == o.offset_),
            "RangeHistogramBase::operator+=(): cannot merge histograms with different data mapping.");
        
        HistogramBase<BASE, BinCount>::operator+=(o);
        if(scale_ == 0.0)
        {
            scale_ = o.scale_;
            offset_ = o.offset_;
            inverse_scale_ = o.inverse_scale_;
        }
    }

    void update(U const & t)
    {
        update(t, 1.0);
    }
    
    void update(U const & t, double weight)
    {
        double m = mapItem(t);
        int index =  (m == (double)this->value_.size())
                       ? (int)m - 1
                       : (int)m;
        if(index < 0)
            this->left_outliers += weight;
        else if(index >= (int)this->value_.size())
            this->right_outliers += weight;
        else
            this->value_[index] += weight;
    }
    
    void setMinMax(double mi, double ma)
    {
        vigra_precondition(this->value_.size() > 0,
            "RangeHistogramBase::setMinMax(...): setBinCount(...) has not been called.");
        vigra_precondition(mi < ma,
            "RangeHistogramBase::setMinMax(...): min < max required.");
        offset_ = mi;
        scale_ = (double)this->value_.size() / (ma - mi);
        inverse_scale_ = 1.0 / scale_;
    }
    
    double mapItem(double t) const
    {
        return scale_ * (t - offset_);
    }
    
    double mapItemInverse(double t) const
    {
        return inverse_scale_ * t + offset_;
    }
    
    template <class ArrayLike>
    void computeStandardQuantiles(double minimum, double maximum, double count, 
                                  ArrayLike const & desiredQuantiles, ArrayLike & res) const
    {
        if(count == 0.0) {
            return;
        }
        
        ArrayVector<double> keypoints, cumhist;
        double mappedMinimum = mapItem(minimum);
        double mappedMaximum = mapItem(maximum);
        
        keypoints.push_back(mappedMinimum);
        cumhist.push_back(0.0);
        
        if(this->left_outliers > 0.0)
        {
            keypoints.push_back(0.0);
            cumhist.push_back(this->left_outliers);
        }
        
        int size = (int)this->value_.size();
        double cumulative = this->left_outliers;
        for(int k=0; k<size; ++k)
        {
            if(this->value_[k] > 0.0)
            {
                if(keypoints.back() <= k)
                {
                    keypoints.push_back(k);
                    cumhist.push_back(cumulative);
                }
                cumulative += this->value_[k];
                keypoints.push_back(k+1);
                cumhist.push_back(cumulative);
            }
        }
        
        if(this->right_outliers > 0.0)
        {
            if(keypoints.back() != size)
            {
                keypoints.push_back(size);
                cumhist.push_back(cumulative);
            }
            keypoints.push_back(mappedMaximum);
            cumhist.push_back(count);
        }
        else
        {
            keypoints.back() = mappedMaximum;
            cumhist.back() = count;
        }
        
        int quantile = 0, end = (int)desiredQuantiles.size();
        
        if(desiredQuantiles[0] == 0.0)
        {
            res[0] = minimum;
            ++quantile;
        }
        if(desiredQuantiles[end-1] == 1.0)
        {
            res[end-1] = maximum;
            --end;
        }
        
        int point = 0;
        double qcount = count * desiredQuantiles[quantile];
        while(quantile < end)
        {
            if(cumhist[point] < qcount && cumhist[point+1] >= qcount)
            {
                double t = (qcount - cumhist[point]) / (cumhist[point+1] - cumhist[point]) * (keypoints[point+1] - keypoints[point]);
                res[quantile] = mapItemInverse(t + keypoints[point]);
                ++quantile;
                qcount = count * desiredQuantiles[quantile];
            }
            else
            {
                ++point;
            }
        }
    }
};

/** \brief Histogram where data values are equal to bin indices.

    - If BinCount != 0, the return type of the accumulator is TinyVector<double, BinCount> .
    - If BinCount == 0, the return type of the accumulator is MultiArray<1, double> . BinCount can be set by calling getAccumulator<IntegerHistogram<0> >(acc_chain).setBinCount(bincount).  
    - Outliers can be accessed via getAccumulator<IntegerHistogram<Bincount>>(a).left_outliers and getAccumulator<...>(acc_chain).right_outliers.
    - Note that histogram options (for all histograms in the accumulator chain) can also be set by passing an instance of HistogramOptions to the accumulator chain via acc_chain.setHistogramOptions().
    Works in pass 1, %operator+=() supported (merging supported).
*/
template <int BinCount>
class IntegerHistogram
{
  public:
    
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return std::string("IntegerHistogram<") + asString(BinCount) + ">";
        // static const std::string n = std::string("IntegerHistogram<") + asString(BinCount) + ">";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public HistogramBase<BASE, BinCount>
    {
        void update(int index)
        {
            if(index < 0)
                ++this->left_outliers;
            else if(index >= (int)this->value_.size())
                ++this->right_outliers;
            else
                ++this->value_[index];
        }
        
        void update(int index, double weight)
        {
            // cannot compute quantile from weighted integer histograms,
            // so force people to use UserRangeHistogram or AutoRangeHistogram
            vigra_precondition(false, "IntegerHistogram::update(): weighted histograms not supported, use another histogram type.");
        }
    
        template <class ArrayLike>
        void computeStandardQuantiles(double minimum, double maximum, double count, 
                                      ArrayLike const & desiredQuantiles, ArrayLike & res) const
        {
            int quantile = 0, end = (int)desiredQuantiles.size();
            
            if(desiredQuantiles[0] == 0.0)
            {
                res[0] = minimum;
                ++quantile;
            }
            if(desiredQuantiles[end-1] == 1.0)
            {
                res[end-1] = maximum;
                --end;
            }
            
            count -= 1.0;
            int currentBin = 0, size = (int)this->value_.size();
            double cumulative1 = this->left_outliers,
                   cumulative2 = this->value_[currentBin] + cumulative1;
            
            // add a to the quantiles to account for the fact that counting
            // corresponds to 1-based indexing (one element == index 1)
            double qcount = desiredQuantiles[quantile]*count + 1.0;
            
            while(quantile < end)
            {
                if(cumulative2 == qcount)
                {
                    res[quantile] = currentBin;
                    ++quantile;
                    qcount = desiredQuantiles[quantile]*count + 1.0;
                }
                else if(cumulative2 > qcount)
                {
                    if(cumulative1 > qcount) // in left_outlier bin
                    {
                        res[quantile] = minimum;
                    }
                    if(cumulative1 + 1.0 > qcount) // between bins
                    {
                        res[quantile] = currentBin - 1 + qcount - std::floor(qcount);
                    }
                    else // standard case
                    {
                        res[quantile] = currentBin;
                    }
                    ++quantile;
                    qcount = desiredQuantiles[quantile]*count + 1.0;
                }
                else if(currentBin == size-1) // in right outlier bin
                {
                    res[quantile] = maximum;
                    ++quantile;
                    qcount = desiredQuantiles[quantile]*count + 1.0;
                }
                else
                {
                    ++currentBin;
                    cumulative1 = cumulative2;
                    cumulative2 += this->value_[currentBin];
                }
            }
        }
    };
};

/** \brief Histogram where user provides bounds for linear range mapping from values to indices.

    - If BinCount != 0, the return type of the accumulator is TinyVector<double, BinCount> .
    - If BinCount == 0, the return type of the accumulator is MultiArray<1, double> . BinCount can be set by calling getAccumulator<UserRangeHistogram<0> >(acc_chain).setBinCount(bincount).
    - Bounds for the mapping (min/max) must be set before seeing data by calling getAccumulator<UserRangeHistogram<BinCount> >.setMinMax(min, max).
    - Options can also be passed to the accumulator chain via an instance of HistogramOptions .
    - Works in pass 1, %operator+=() is supported (merging) if both histograms have the same data mapping.
    - Outliers can be accessed via getAccumulator<...>(a).left_outliers and getAccumulator<...>(a).right_outliers.
    - Note that histogram options (for all histograms in the accumulator chain) can also be set by passing an instance of HistogramOptions to the accumulator chain via acc_chain.setHistogramOptions().
*/
template <int BinCount>
class UserRangeHistogram
{
  public:
    
    typedef Select<> Dependencies;
    
    static std::string name() 
    { 
        return std::string("UserRangeHistogram<") + asString(BinCount) + ">";
        // static const std::string n = std::string("UserRangeHistogram<") + asString(BinCount) + ">";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public RangeHistogramBase<BASE, BinCount, U>
    {
        void update(U const & t)
        {
            update(t, 1.0);
        }
        
        void update(U const & t, double weight)
        {
            vigra_precondition(this->scale_ != 0.0,
                "UserRangeHistogram::update(): setMinMax(...) has not been called.");
                
            RangeHistogramBase<BASE, BinCount, U>::update(t, weight);
        }
    };
};

/** \brief Histogram where range mapping bounds are defined by minimum and maximum of data.

    - If BinCount != 0, the return type of the accumulator is TinyVector<double, BinCount> .
    - If BinCount == 0, the return type of the accumulator is MultiArray<1, double> . BinCount can be set by calling getAccumulator<AutoRangeHistogram>(acc_chain).setBinCount(bincount).
    - Becomes a UserRangeHistogram if min/max is set.
    - Works in pass 2, %operator+=() is supported (merging) if both histograms have the same data mapping.
    - Outliers can be accessed via getAccumulator<...>(acc_chain).left_outliers and getAccumulator<...>(acc_chain).right_outliers .
    - Note that histogram options (for all histograms in the accumulator chain) can also be set by passing an instance of HistogramOptions to the accumulator chain via acc_chain.setHistogramOptions().
*/
template <int BinCount>
class AutoRangeHistogram
{
  public:
    
    typedef Select<Minimum, Maximum> Dependencies;
    
    static std::string name() 
    { 
        return std::string("AutoRangeHistogram<") + asString(BinCount) + ">";
        // static const std::string n = std::string("AutoRangeHistogram<") + asString(BinCount) + ">";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public RangeHistogramBase<BASE, BinCount, U>
    {
        static const unsigned int workInPass = LookupDependency<Minimum, BASE>::type::workInPass + 1;
        
        void update(U const & t)
        {
            update(t, 1.0);
        }
        
        void update(U const & t, double weight)
        {
            if(this->scale_ == 0.0)
                this->setMinMax(getDependency<Minimum>(*this), getDependency<Maximum>(*this));
                
            RangeHistogramBase<BASE, BinCount, U>::update(t, weight);
        }
    };
};

/** \brief Like AutoRangeHistogram, but use global min/max rather than region min/max.

    - If BinCount != 0, the return type of the accumulator is TinyVector<double, BinCount> .
    - If BinCount == 0, the return type of the accumulator is MultiArray<1, double> . BinCount can be set by calling getAccumulator<GlobalRangeHistogram<0>>(acc_chain).setBinCount(bincount).
    - Becomes a UserRangeHistogram if min/max is set.
    - Works in pass 2, %operator+=() is supported (merging) if both histograms have the same data mapping.
    - Outliers can be accessed via getAccumulator<GlobalRangeHistogram<Bincount>>(acc_chain).left_outliers and getAccumulator<...>(acc_chain).right_outliers .
    - Histogram options (for all histograms in the accumulator chain) can also be set by passing an instance of HistogramOptions to the accumulator chain via acc_chain.setHistogramOptions().
*/
template <int BinCount>
class GlobalRangeHistogram
{
  public:
    
    typedef Select<Global<Minimum>, Global<Maximum>, Minimum, Maximum> Dependencies;
    
    static std::string name() 
    { 
        return std::string("GlobalRangeHistogram<") + asString(BinCount) + ">";
        // static const std::string n = std::string("GlobalRangeHistogram<") + asString(BinCount) + ">";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public RangeHistogramBase<BASE, BinCount, U>
    {
        static const unsigned int workInPass = LookupDependency<Minimum, BASE>::type::workInPass + 1;
        
        bool useLocalMinimax_;
        
        Impl()
        : useLocalMinimax_(false)
        {}
        
        void setRegionAutoInit(bool locally)
        {
            this->scale_ = 0.0;
            useLocalMinimax_ = locally;
        }
        
        void update(U const & t)
        {
            update(t, 1.0);
        }
        
        void update(U const & t, double weight)
        {
            if(this->scale_ == 0.0)
            {
                if(useLocalMinimax_)
                    this->setMinMax(getDependency<Minimum>(*this), getDependency<Maximum>(*this));
                else
                    this->setMinMax(getDependency<Global<Minimum> >(*this), getDependency<Global<Maximum> >(*this));
            }
            
            RangeHistogramBase<BASE, BinCount, U>::update(t, weight);
        }
    };
};

/** \brief Compute (0%, 10%, 25%, 50%, 75%, 90%, 100%) quantiles from given histogram.

    Return type is TinyVector<double, 7> . 
*/
template <class HistogramAccumulator> 
class StandardQuantiles
{
  public:
    
    typedef typename StandardizeTag<HistogramAccumulator>::type HistogramTag;
    typedef Select<HistogramTag, Minimum, Maximum, Count> Dependencies;

    static std::string name() 
    { 
        return std::string("StandardQuantiles<") + HistogramTag::name() + " >";
        // static const std::string n = std::string("StandardQuantiles<") + HistogramTag::name() + " >";
        // return n;
    }
    
    template <class U, class BASE>
    struct Impl
    : public CachedResultBase<BASE, TinyVector<double, 7>, U>
    {
        typedef typename CachedResultBase<BASE, TinyVector<double, 7>, U>::result_type result_type;
        typedef typename CachedResultBase<BASE, TinyVector<double, 7>, U>::value_type  value_type;
        
        static const unsigned int workInPass = LookupDependency<HistogramTag, BASE>::type::workInPass;
        
        result_type operator()() const
        {
            if(this->isDirty())
            {
                double desiredQuantiles[] = {0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0 };
                getAccumulator<HistogramTag>(*this).computeStandardQuantiles(getDependency<Minimum>(*this), getDependency<Maximum>(*this), 
                                                                             getDependency<Count>(*this), value_type(desiredQuantiles), 
                                                                             this->value_);
                this->setClean();
            }
            return this->value_;
        }
    };
};

}} // namespace vigra::acc

#endif // VIGRA_ACCUMULATOR_HXX