summaryrefslogtreecommitdiffstats
path: root/applications/rview/rviewUtils.cpp
blob: 762ee100a1dcdea99686fa56de17678a51576697 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
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
/*
* This file is part of rasdaman community.
*
* Rasdaman community is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Rasdaman community is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with rasdaman community.  If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Peter Baumann /
rasdaman GmbH.
*
* For more information please see <http://www.rasdaman.org>
* or contact Peter Baumann via <baumann@rasdaman.com>.
/

/**
*  PURPOSE:
*
*  Central definitions of shared objects and constants, global tool functions.
*
*  - All menu codes used in the program (MENU_...)
*  - Global tool functions for handling collections, base types, projection
*    strings, X events, ... . See ``Global functions''.
*  - rviewFrame class which must be the base class of all frames used in rView.
*  - rviewFrameMgr class for handling all of rView's frames (dispatching events
*    etc)
*  - rviewMultiline class for displaying several lines of non-editable text.
*  - rviewDialog class which is the base class for all rView's dialog windows.
*  - rviewErrorbox class, derived from rviewDialog.
*  - rviewProgress class, derived from rviewDialog.
*  - rviewResults class for displaying database results and dispatching object
*    viewers. Relies on code provided by rviewMDD for scaling/resampling/endian
*    conversions.
*  - rviewAbout class for displaying information about rView itself.
*  - rviewStringSet class for displaying a set of strings in a scrollable
*    list box.
*
*  COMMENTS:
* 		 none
*/


// Was file included via header? Then mask out all non-template code
#if (!defined(EARLY_TEMPLATE) || !defined(__EXECUTABLE__))

// Standard wxWindows preamble.
#ifdef __GNUG__
#pragma implementation
#endif


// changed in wxWindows 2.4.2:
//#include "wx_prec.h"
#include <wx/wxprec.h>

#ifdef __BORLANDC__
#pragma hdrstop
#endif


#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif

// #include "wb_timer.h" -- PB 2006-jan-01


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <iostream.h>



#ifdef EARLY_TEMPLATE
#define __EXECUTABLE__
#endif


#include "raslib/rmdebug.hh"
#include "raslib/primitivetype.hh"
#include "raslib/structuretype.hh"

#include "rviewUtils.hh"
#include "rviewMDD.hh"
#include "rviewPrefs.hh"
#include "rviewColMap.hh"
#include "rviewDModes.hh"
#include "rviewOSection.hh"
#include "rviewTypes.hh"
#include "rviewThumb.hh"
#include "rviewSound.hh"
#include "rviewTypeMan.hh"
#include "labelManager.hh"


#ifdef __VISUALC__
const int rview_window_extra_height = 24;
const int rview_choice_sub_width = 0;
#else
const int rview_window_extra_height = 0;
const int rview_choice_sub_width = 32;
#endif






/*
 *  Global data
 */

// Base type to string translation tables

#if (MAXIMUM_DIMENSIONS != 4)
#error "Adapt tables for MAXIMUM DIMENSIONS!"
#endif

// String names of base types
char *rviewBaseTypes[] = {
  "none",
  "Boolean",
  "Char",
  "Octet",
  "Short",
  "UShort",
  "Long",
  "ULong",
  "RGBPixel",
  "Float",
  "Double"
};

// String names of objects of baseType x and dimension y (-> rviewBaseType)
char *rviewTypeNames[][MAXIMUM_DIMENSIONS] = {
  {"?", "?", "?", "?"},
  {"BoolString", "BoolImage", "BoolCube", "BoolCube4"},
  {"GreyString", "GreyImage", "GreyCube", "GreyCube4"},
  {"OctetString", "OctetImage", "OctetCube", "OctetCube4"},
  {"ShortString", "ShortImage", "ShortCube", "ShortCube4"},
  {"UShortString", "UShortImage", "UShortCube", "UShortCube4"},
  {"LongString", "LongImage", "LongCube", "LongCube4"},
  {"ULongString", "ULongImage", "ULongCube", "ULongCube4"},
  {"RGBString", "RGBImage", "RGBCube", "RGBCube4"},
  {"FloatString", "FloatImage", "FloatCube", "FloatCube4"},
  {"DoubleString", "DoubleImage" "DoubleCube", "DoubleCube4"}
};

// The same for sets
char *rviewSetNames[][MAXIMUM_DIMENSIONS] = {
  {"?", "?", "?", "?"},
  {"BoolSet1", "BoolSet", "BoolSet3", "BoolSet4"},
  {"GreySet1", "GreySet", "GreySet3", "GreySet4"},
  {"OctetSet1", "OctetSet", "OctetSet3", "OctetSet4"},
  {"ShortSet1", "ShortSet", "ShortSet3", "ShortSet4"},
  {"UShortSet1", "UShortSet", "UShortSet3", "UShortSet4"},
  {"LongSet1", "LongSet", "LongSet3", "LongSet4"},
  {"ULongSet1", "ULongSet", "ULongSet3", "ULongSet4"},
  {"RGBSet1", "RGBSet", "RGBSet3", "RGBSet4"},
  {"FloatSet1", "FloatSet", "FloatSet3", "FloatSet4"},
  {"DoubleSet1", "DoubleSet", "DoubleSet3", "DoubleSet4"}
};



unsigned char lowerCaseTable[256];



// Various support classes
rviewFrameMgr *frameManager = NULL;

labelManager *lman = NULL;






/*
 *  GLOBAL functions
 */

// Frees all memory allocated by a collection descriptor.
void rviewDeleteCollection(collection_desc *coll)
{
  if (coll != NULL)
  {
    int i;
    collection_desc *ptr = coll;

    if (coll->collName != NULL) delete [] coll->collName;
    if (coll->collType != NULL) delete [] coll->collType;
    if (coll->collInfo != NULL) delete [] coll->collInfo;

    for (i=0; i<coll->number; i++)
    {
      if (coll->mddObjs != NULL)
      {
	if (!coll->mddObjs[i].mdd.is_null())
	{
	  coll->mddObjs[i].mdd.destroy();
	}
      }
      else if (coll->strObjs != NULL)
      {
	if (coll->strObjs[i] != NULL)
	{
	  delete [] coll->strObjs[i];
	}
      }
    }
    if (coll->mddObjs != NULL) delete [] coll->mddObjs;
    if (coll->strObjs != NULL) delete [] coll->strObjs;

    delete coll;
  }
}



/*
 *  Support function for rviewParseProjection
 */
static const char *rviewParseIndexMapping(const char *s, int idx, int dims, r_Point *mapIndex)
{
  const char *b, *d;
  r_Range value;

  b = s+1;
  if (mapIndex == NULL)
  {
    cerr << "Mode doesn't support reordering of dimensions." << endl;
  }

  value = (r_Range)strtol(b, (char**)&d, 0);
  if (b == d) return NULL;

  if ((value < 0) || (value >= (r_Range)dims))
  {
    cerr << "Bad dimension index " << value << endl;
    value = (r_Range)idx;
  }
  if (mapIndex != NULL) (*mapIndex)[idx] = value;

  while ((*d == ' ') || (*d == '\t')) d++;
  if (*d == ']') return d+1;
  return NULL;
}


/*
 *  Translate a projection string (now RasDaMan style, i.e. things
 *  like *:* are also allowed) into two diagonal r_Points. Returns
 *  number of dimension of projection string for success, 0 for an error.
 */

int rviewParseProjection(const r_Minterval &interv, r_Point &pt1, r_Point &pt2, const char *projString, unsigned int *freeDims, r_Point *mapIndex)
{
  int dims, i;
  const char *b, *d;
  r_Range value;

  if (freeDims != NULL) *freeDims = 0;
  dims = interv.dimension();
  pt1 = r_Point(dims); pt2 = r_Point(dims);

  b = projString; i = 0;
  while (*b != '\0')
  {
    while ((*b == ' ') || (*b == '\t')) b++;
    if (*b == ',') b++;
    while ((*b == ' ') || (*b == '\t')) b++;
    if (*b == '\0') break;
    if (i >= dims) return 0;
    if (*b == '*')
    {
      pt1[i] = interv[i].low(); pt2[i] = interv[i].high(); b++;
    }
    else
    {
      value = (r_Range)strtol(b, (char**)&d, 0);
      // no valid number found?
      if (b == d) return 0;
      b = d;
      if ((value < interv[i].low()) || (value > interv[i].high())) return 0;
      pt1[i] = value; pt2[i] = value;
    }
    if (mapIndex != NULL) (*mapIndex)[i] = i;
    while ((*b == ' ') || (*b == '\t')) b++;
    if (*b == '[')	// Explicit index-mapping?
    {
      if ((b = rviewParseIndexMapping(b, i, dims, mapIndex)) == NULL) return 0;
    }
    else if (*b == ':')	// the upper boundaries follow after a colon.
    {
      if (freeDims != NULL) *freeDims |= (1<<i);
      b++;
      if (*b == '\0') break;
      if (*b == '*')
      {
	value = interv[i].high(); b++;
      }
      else
      {
	value = (r_Range)strtol(b, (char**)&d, 0);
	if (b == d) return 0;
	b = d;
	if ((value < interv[i].low()) || (value > interv[i].high())) return 0;
      }
      pt2[i] = value;
      while ((*b == ' ') || (*b == '\t')) b++;
      if (*b == '[')
      {
	if ((b = rviewParseIndexMapping(b, i, dims, mapIndex)) == NULL) return 0;
      }
    }
    i++;
  }
  return i;
}





/*
 *  Determine the base type of an MDD object, returning a simple identifier.
 */
rviewBaseType rviewGetBasetype(r_Object *obj)
{
  rviewBaseType baseType;
  const r_Type *bt;

  baseType = rbt_none;

  // New type schema...
  bt = obj->get_type_schema();
  if (bt->type_id() == r_Type::MARRAYTYPE)
    bt = ((r_GMarray*)obj)->get_base_type_schema();
  else if (bt->type_id() == r_Type::COLLECTIONTYPE)
    bt = ((r_Collection<r_Ref_Any>*)obj)->get_element_type_schema();

  if (bt != NULL)
  {
    if (((r_Type*)bt)->isStructType())
    {
      if (((r_Base_Type*)bt)->size() == 3)
	baseType = rbt_rgb;
      else
	baseType = rbt_none;
    }
    else
    {
      r_Primitive_Type *pt = (r_Primitive_Type *)bt;

      switch (pt->type_id())
      {
        case r_Primitive_Type::BOOL: baseType = rbt_bool; break;
        case r_Primitive_Type::CHAR: baseType = rbt_char; break;
        case r_Primitive_Type::OCTET: baseType = rbt_uchar; break;
        case r_Primitive_Type::SHORT: baseType = rbt_short; break;
        case r_Primitive_Type::USHORT: baseType = rbt_ushort; break;
        case r_Primitive_Type::LONG: baseType = rbt_long; break;
        case r_Primitive_Type::ULONG: baseType = rbt_ulong; break;
        case r_Primitive_Type::FLOAT: baseType = rbt_float; break;
        case r_Primitive_Type::DOUBLE: baseType = rbt_double; break;
        default: baseType = rbt_none; break;
      }
    }
  }
  else
  {
    char *name = (char*)(obj->get_type_name());
    if (name != NULL)
    {
      if (strcmp(name, "GreyImage") == 0) baseType = rbt_char;
      else if (strcmp(name, "BoolImage") == 0) baseType = rbt_bool;
      else if (strcmp(name, "RGBImage") == 0) baseType = rbt_rgb;
    }
  }
  return baseType;
}



/*
 *  rviewPrintTypedCell() prints the contents of a cell with a given base type into the buffer,
 *  returning the number of characters written.
 */

// For internal use only
static void printPrimitiveCell(r_Primitive_Type *primType, char **buff, char *data, int numberBase)
{
  char *b = *buff;

  switch (numberBase)
  {
    case 8:
      switch (primType->type_id())
      {
	case r_Primitive_Type::BOOL:
	  b += sprintf(b, "%3o", *((r_Boolean*)data)); break;
	case r_Primitive_Type::CHAR:
	  b += sprintf(b, "%3o", *((r_Char*)data)); break;
	case r_Primitive_Type::OCTET:
	  b += sprintf(b, "%3o", *((r_Octet*)data)); break;
	case r_Primitive_Type::SHORT:
	  b += sprintf(b, "%6o", *((r_Short*)data)); break;
	case r_Primitive_Type::USHORT:
	  b += sprintf(b, "%6o", *((r_UShort*)data)); break;
	case r_Primitive_Type::LONG:
	  b += sprintf(b, "%11lo", *((r_Long*)data)); break;
	case r_Primitive_Type::ULONG:
	  b += sprintf(b, "%11lo", *((r_ULong*)data)); break;
	case r_Primitive_Type::FLOAT:
	  b += sprintf(b, "%011o", *((r_Long*)data)); break;
	case r_Primitive_Type::DOUBLE:
	  b += sprintf(b, "%011o:%011o", ((r_Long*)data)[0], ((r_Long*)data)[1]); break;
	default:
	  break;
      }
      break;
    case 16:
      switch (primType->type_id())
      {
	case r_Primitive_Type::BOOL:
	  b += sprintf(b, "%02x", *((r_Boolean*)data)); break;
	case r_Primitive_Type::CHAR:
	  b += sprintf(b, "%02x", *((r_Char*)data)); break;
	case r_Primitive_Type::OCTET:
	  b += sprintf(b, "%02x", *((r_Octet*)data)); break;
	case r_Primitive_Type::SHORT:
	  b += sprintf(b, "%04x", *((r_Short*)data)); break;
	case r_Primitive_Type::USHORT:
	  b += sprintf(b, "%04x", *((r_UShort*)data)); break;
	case r_Primitive_Type::LONG:
	  b += sprintf(b, "%08x", *((r_Long*)data)); break;
	case r_Primitive_Type::ULONG:
	  b += sprintf(b, "%08x", *((r_ULong*)data)); break;
	case r_Primitive_Type::FLOAT:
	  b += sprintf(b, "%08x", *((r_Long*)data)); break;
	case r_Primitive_Type::DOUBLE:
	  b += sprintf(b, "%08x:%08x", ((r_Long*)data)[0], ((r_Long*)data)[1]); break;
	default:
	  break;
      }
      break;
    default:
      switch (primType->type_id())
      {
	case r_Primitive_Type::BOOL:
	  b += sprintf(b, "%3d", *((r_Boolean*)data)); break;
	case r_Primitive_Type::CHAR:
	  b += sprintf(b, "%3d", *((r_Char*)data)); break;
	case r_Primitive_Type::OCTET:
	  b += sprintf(b, "%3d", *((r_Octet*)data)); break;
	case r_Primitive_Type::SHORT:
	  b += sprintf(b, "%5d", *((r_Short*)data)); break;
	case r_Primitive_Type::USHORT:
	  b += sprintf(b, "%5d", *((r_UShort*)data)); break;
	case r_Primitive_Type::LONG:
	  b += sprintf(b, "%10ld", *((r_Long*)data)); break;
	case r_Primitive_Type::ULONG:
	  b += sprintf(b, "%10ld", *((r_ULong*)data)); break;
	case r_Primitive_Type::FLOAT:
	  b += sprintf(b, "%g", *((r_Float*)data)); break;
	case r_Primitive_Type::DOUBLE:
	  b += sprintf(b, "%g", *((r_Double*)data)); break;
	default:
	  break;
      }
      break;
  }
  *buff = b;
}

// For internal use only
void printStructuredCell(r_Structure_Type *structType, char **buff, char *data, int numberBase)
{
  r_Type *newType;
  unsigned long off;
  char *b;
  
  b = *buff;
  *b++ = '{';
  r_Structure_Type::attribute_iterator iter(structType->defines_attribute_begin());
  while (iter != structType->defines_attribute_end())
  {
    newType = (*iter).type_of().clone();
    off = (*iter).offset();
 
    if (newType->isStructType())
    {
      r_Structure_Type *newStructType = (r_Structure_Type*)newType;
      printStructuredCell(newStructType, &b, data + off, numberBase);
    }
    else
    {
      r_Primitive_Type *newPrimType = (r_Primitive_Type*)newType;
      printPrimitiveCell(newPrimType, &b, data + off, numberBase);
    }
    delete newType;
    *b++ = ',';
    iter++;
  }
  b[-1] = '}'; *b = '\0';
  *buff = b;
}

int rviewPrintTypedCell(const r_Type *baseType, char *buffer, char *data, int numberBase)
{
  char *b = buffer;

  if (((r_Type*)baseType)->isStructType())
  {
    r_Structure_Type *structType = (r_Structure_Type*)baseType;
    printStructuredCell(structType, &b, data, numberBase);
  }
  else
  {
    r_Primitive_Type *primType = (r_Primitive_Type*)baseType;
    printPrimitiveCell(primType, &b, data, numberBase);
  }
  return (int)(b - buffer);
}




/*
 *  Quicksort a char *[]
 */

#define QUICKSORT_STRING_SWAP(x,y)	h=array[x]; array[x]=array[y]; array[y]=h;

void rviewQuicksortStrings(char *array[], int from, int to)
{
  while (from < to)
  {
    int i, j;
    char *h;

    j = (from+to)/2;
    QUICKSORT_STRING_SWAP(from, j); j=from;
    for (i=from+1; i<=to; i++)
    {
      if (strcmp(array[i], array[from]) < 0)
      {
	j++;
	QUICKSORT_STRING_SWAP(i, j);
      }
    }
    QUICKSORT_STRING_SWAP(from, j);

    if ((j-from) < (to-j))
    {
      rviewQuicksortStrings(array, from, j-1);
      from = j+1;
    }
    else
    {
      rviewQuicksortStrings(array, j+1, to);
      to = j-1;
    }
  }
}



/*
 *  Init character lookup tables (e.g. lower case table)
 */
void rviewInitCharacterTables(void)
{
  int i;

  for (i=0; i<256; i++) lowerCaseTable[i] = tolower(i);
}



#define LOOKUP_KEYWORD_CORE \
  while (count != 0) \
  { \
    b = (const unsigned char*)(kti[pos].keyword); \
    d = (const unsigned char*)key; \
    while (TRANSLATE_CHARACTER(b) == TRANSLATE_CHARACTER(d)) \
    { \
      if (*b == 0) break; b++; d++; \
    } \
    if ((*b == 0) && (*d == 0)) return kti[pos].ident; \
    if (TRANSLATE_CHARACTER(b) >= TRANSLATE_CHARACTER(d)) \
    { \
      pos -= step; if (pos < 0) pos = 0; \
    } \
    else \
    { \
      pos += step; if (pos >= tabsize) pos = tabsize - 1; \
    } \
    step = (step+1) >> 1; count >>= 1; \
  }

/*
 *  Lookup a keyword in a SORTED keyword_to_ident table. Case sensitivity
 *  is optional but has to match the sorting order of the table, of course.
 */
int rviewLookupKeyword(const char *key, const keyword_to_ident_c *kti, int tabsize, bool caseSensitive)
{
  int pos, step, count;
  const unsigned char *b, *d;

  count = tabsize;
  pos = (tabsize + 1) >> 1; if (pos >= tabsize) pos = tabsize - 1;
  step = (pos + 1) >> 1;
  if (caseSensitive)
  {
#define TRANSLATE_CHARACTER(x)	(*x)
    LOOKUP_KEYWORD_CORE;
#undef TRANSLATE_CHARACTER
  }
  else
  {
#define TRANSLATE_CHARACTER(x)	lowerCaseTable[(*x)]
    LOOKUP_KEYWORD_CORE;
#undef TRANSLATE_CHARACTER
  }
  return -1;
}



/* Helper function making sure min/max of the init structure is used by the
   colourspace mapper */

static void rviewEnsureCspaceRange(colourspaceMapper *csmap, const colourspace_params *cp)
{
  // make sure the min/max values are taken from the init structure as well
  if (cp != NULL)
  {
    // assume it's initialized if either values differs from 0
    if ((cp->minVal != 0.0) || (cp->maxVal != 0.0))
    {
      colourspace_params par;
      csmap->getParameters(&par);
      par.minVal = cp->minVal;
      par.maxVal = cp->maxVal;
      // do not do auto-update, otherwise we're stuck in an infinite loop
      csmap->colourspaceChanged(&par, FALSE);
      //cout << "MIN " << par.minVal << ", MAX " << par.maxVal << endl;
    }
  }
}


/*
 *  Check whether colourspace mapping is possible for the given
 *  base type and return 1 if so. *csmap must be a pointer to the
 *  colourspaceMapper to use or NULL if there isn't one yet in
 *  which case a new one will have been created on returning 1.
 *  If cmap == NULL the function just returns 0 or 1. If the int*
 *  arguments are not NULL they're set up correctly on exit too.
 */
int rviewCheckInitCspace(rviewBaseType baseType, colourspaceMapper **csmap, r_Ref<r_GMarray> &mddObj, bool fullRange, r_Minterval *domain, int w, int *newPitch, int *newDepth, int *newPad, int *virtualPitch, const colourspace_params *cp)
{
  colourspace_params par;

  switch (baseType)
  {
    case rbt_char:
    case rbt_uchar:
    case rbt_short:
    case rbt_ushort:
      if (csmap == NULL) return 1;
      if (*csmap == NULL)
      {
	memcpy(&par, (cp == NULL) ? &(prefs->csp) : cp, sizeof(colourspace_params));
        *csmap = new colourspaceMapper(mddObj, baseType, &par, fullRange, domain);
      }
      else
	(*csmap)->bindMapper(mddObj, baseType, fullRange, domain, cp);

      rviewEnsureCspaceRange(*csmap, cp);

      // always call this and let the mapper sort out whether it has to update
      (*csmap)->buildCSTab15();
      if (newPitch == NULL) return 1;
      if (*newPad < 32) *newPad = 32;
      *newDepth = 15;
      switch (*newPad)
      {
	case 32: *newPitch = (w*2 + 3) & ~3; break;
        case 64: *newPitch = (w*2 + 7) & ~7; break;
	case 128: *newPitch = (w*2 + 15) & ~15; break;
        case 256: *newPitch = (w*2 + 31) & ~31; break;
	default:
	  cerr << "Bad pad " << *newPad << endl;
	  return 0;
      }
      if (virtualPitch != NULL) *virtualPitch = *newPitch;
      return 1;
      break;
    case rbt_long:
    case rbt_ulong:	// using 24bpp only makes sense for long
    case rbt_float:
    case rbt_double:	// ... or larger types
      {
	int baseWidth;

	baseWidth = 4*w;

	if (csmap == NULL) return 1;
	if (*csmap == NULL)
	{
	  memcpy(&par, (cp == NULL) ? &(prefs->csp) : cp, sizeof(colourspace_params));
	  *csmap = new colourspaceMapper(mddObj, baseType, &par, fullRange, domain);
	}
	else
	  (*csmap)->bindMapper(mddObj, baseType, fullRange, domain, cp);

	rviewEnsureCspaceRange(*csmap, cp);

	(*csmap)->buildCSTab24();
	if (newPitch == NULL) return 1;
	if (*newPad < 32) *newPad = 32;
	*newDepth = 32;
	switch (*newPad)
	{
	  case 32: *newPitch = (baseWidth + 3) & ~3; break;
	  case 64: *newPitch = (baseWidth + 7) & ~7; break;
	  case 128: *newPitch = (baseWidth + 15) & ~15; break;
	  case 256: *newPitch = (baseWidth + 31) & ~31; break;
	  default: cerr << "Bad pad " << *newPad << endl;
	    return 0;
	}
	if (virtualPitch != NULL)
	  *virtualPitch = (baseType == rbt_double) ? 2*(*newPitch) : (*newPitch);
	return 1;
      }
      break;
    default: break;
  }
  return 0;
}



/*
 *  Smart number conversion functions. They also understand the 0x
 *  prefix and convert the number correctly.
 */

long asctol(const char *str)
{
  return stringtol(str, NULL);
}

int asctoi(const char *str)
{
  return (int)stringtol(str, NULL);
}

double asctof(const char *str)
{
  return stringtof(str, NULL);
}

long stringtol(const char *str, char **endptr)
{
  const char *b = str;
  long value;

  while (isspace((unsigned int)(*b))) b++;
  if ((b[0] == '0') && ((b[1] == 'x') || (b[1] == 'X')))
  {
    b += 2;
    value = strtol(b, endptr, 16);
  }
  else
  {
    value = strtol(b, endptr, 10);
  }
  if ((endptr != NULL) && ((const char*)(*endptr) == b)) *endptr = (char*)str;
  return value;
}

double stringtof(const char *str, char **endptr)
{
  const char *b = str;
  double value;

  while (isspace((unsigned int)(*b))) b++;
  if ((b[0] == '0') && ((b[1] == 'x') || (b[1] == 'X')))
  {
    b += 2;
    value = (double)strtol(b, endptr, 16);
  }
  else
  {
    value = strtod(b, endptr);
  }
  if ((endptr != NULL) && ((const char*)(*endptr) == b)) *endptr = (char*)str;
  return value;
}





/*
 *  Dynamic string class for easy management of dynamically allocated string storage
 */

const char DynamicString::emptyString[] = "";


DynamicString::DynamicString(void)
{
  myString = NULL;
}

DynamicString::DynamicString(const DynamicString &ms)
{
  if (ms.myString == NULL)
  {
    myString = NULL;
  }
  else
  {
    myString = new char[strlen(ms.myString) + 1];
    strcpy(myString, ms.myString);
  }
}


DynamicString::DynamicString(const char *str)
{
  if (str == NULL)
  {
    myString = NULL;
  }
  else
  {
    myString = new char[strlen(str) + 1];
    strcpy(myString, str);
  }
}


DynamicString::~DynamicString(void)
{
  if (myString != NULL) delete [] myString;
}


DynamicString &DynamicString::first(const char *str, unsigned int num)
{
  if (myString != NULL)
  {
    delete [] myString; myString = NULL;
  }
  if (num != 0)
  {
    unsigned int len = strlen(str);
    if (len > num) len = num;
    myString = new char[len + 1];
    strncpy(myString, str, len);
    myString[len] = '\0';
  }
  return *this;
}


DynamicString &DynamicString::operator=(const DynamicString &ms)
{
  if (myString != NULL)
  {
    delete [] myString; myString = NULL;
  }
  if (ms.myString != NULL)
  {
    myString = new char[strlen(ms.myString) + 1];
    strcpy(myString, ms.myString);
  }
  return *this;
}


DynamicString &DynamicString::operator=(const char *str)
{
  if (myString != NULL)
  {
    delete [] myString; myString = NULL;
  }
  if (str != NULL)
  {
    myString = new char[strlen(str) + 1];
    strcpy(myString, str);
  }
  return *this;
}


const char *DynamicString::ptr(void) const
{
  if (myString == NULL) return emptyString;
  return myString;
}

DynamicString::operator const char*(void) const
{
  return ptr();
}


bool DynamicString::operator==(const DynamicString &str) const
{
  return (strcmp(ptr(), str.ptr()) == 0);
}


bool DynamicString::operator==(const char *str) const
{
  return (strcmp(ptr(), str) == 0);
}






/*
 *  Generic handler function for events like button- and key-presses.
 *  It passes the event to the frameManager which then broadcasts
 *  it to all the frames it knows. If a frame recognizes obj as one
 *  of its children it claims the event, thus aborting the broadcast.
 */

void rviewEventHandler(wxObject &obj, wxEvent &evt)
{
  if (frameManager != NULL)
    frameManager->broadcastEvent(obj, evt);
  //cout << endl;
}






/*
 *  rviewFrame member functions.
 *  This is an abstract class that is only used for deriving other
 *  (window/frame) classes from it.
 */

rviewFrame::rviewFrame(wxFrame *parent, char *title, int x, int y, int w, int h) : wxFrame(parent, title, x, y, w, h)
{
  RMDBGONCE( 3, RMDebug::module_applications, "rviewFrame", "rviewFrame( " << this << ", ...)" );

  if (frameManager != NULL)
    frameManager->registerFrame(this);

  parentFrame = NULL;
  // Init the size with illegal values to make sure the first OnSize gets through
  frameWidth = -1; frameHeight = -1;
  // All the frame's children should be destroyed when the frame is destroyed.
  frames = new rviewFrameMgr(TRUE);
}


rviewFrame::~rviewFrame(void)
{
  RMDBGONCE( 3, RMDebug::module_applications, "rviewFrame", "~rviewFrame()  " << this );

  delete frames;

  if (frameManager != NULL)
    frameManager->deregisterFrame(this);

  if (parentFrame != NULL)
  {
    parentFrame->deregisterChild(this);
  }
}


const char *rviewFrame::getFrameName(void) const
{
  return "rviewFrame";
}

rviewFrameType rviewFrame::getFrameType(void) const
{
  return rviewFrameTypeGeneric;
}


void rviewFrame::setParent(rviewFrame *parent)
{
  parentFrame = parent;
}


void rviewFrame::registerChild(rviewFrame *child)
{
  child->setParent(this);
  frames->registerFrame(child);
}


void rviewFrame::deregisterChild(rviewFrame *child)
{
  frames->deregisterFrame(child);
  child->setParent(NULL);
}


// Called by the global frame manager when the application is about to die.
int rviewFrame::requestQuit(int level)
{
  // Default action on a hard quit: die
  if (level != 0)
  {
    // Do not delete the children, that would upset the frame manager's loop.
    frames->setDeleteMode(FALSE); setParent(NULL);
    //delete this;
    Close(TRUE);
  }
  return 0;
}



// Called on a user event
int rviewFrame::userEvent(const user_event &ue)
{
  // Default action: nothing. Overload function in derived class if you're
  // interested in user messages.
  return 0;
}


// Called by the rviewFrameMgr object to determine which frame receives an event
int rviewFrame::checkobj(wxObject &obj)
{
  return checkobj_rec((wxWindow*)this, obj);
}


// Used internally by rviewFrame::checkobj(); don't access directly. Checks
// recursively all the children of a given frame against obj.
int rviewFrame::checkobj_rec(wxWindow *whence, wxObject &obj)
{
  if (&obj == (wxObject*)whence) return 1;
  else
  {
    int i, n;
    wxList *list;

    list = whence->GetChildren();
    n = list->Number();
    for (i=0; i<n; i++)
    {
      if (checkobj_rec((wxWindow*)(list->Nth(i)->Data()), obj) != 0) return 1;
    }
  }
  return 0;
}



// Virtual function. If a derived frame class should refuse to die in some
// circumstances, it must overload his function.
bool rviewFrame::OnClose(void)
{
  return TRUE;
}


void rviewFrame::childMouseEvent(wxWindow *child, wxMouseEvent &mevt)
{
  // by default this is ignored.
}






/*
 *  rviewFrameMgr member functions
 */

rviewFrameMgr::rviewFrameMgr(void)
{
  listLength = 0; deleteChildren = FALSE;
  frameList = NULL; tailList = NULL;
}


rviewFrameMgr::rviewFrameMgr(bool delChild)
{
  listLength = 0; deleteChildren = delChild;
  frameList = NULL; tailList = NULL;
}


rviewFrameMgr::~rviewFrameMgr(void)
{
  int i;
  frame_list *list, *last;

  // Deletes all the frames and their children
  // Unlink all frames first! Otherwise there'll be trouble because the Frame Manager
  // will loop over the frames and delete them; but if the frames have a valid parent
  // they will deregister there which will screw up the Frame Manager's frame list
  // _during the loop_ and hence crash.
  list = frameList;
  for (i=0; i<listLength; i++)
  {
    last = list; list = list->next;
    // If it's the global frame manager it shouldn't delete the children, that's
    // wxWindows' job. If it's a manager local to a frame it should delete all
    // that frame's children, however.
    if (deleteChildren)
    {
      last->frame->setParent(NULL);
      //delete last->frame;
      last->frame->Close(TRUE);
    }
    delete last;
  }
}


void rviewFrameMgr::registerFrame(rviewFrame *client)
{
  frame_list *entry;

  //cout << "frameManager::registerFrame(" << (void*)client << ")" << endl;
  if ((entry = new frame_list) == NULL)
  {
    //cerr << "frameManager: Unable to claim memory!\n" << endl;
    return;
  }

  entry->frame = client; entry->next = NULL;

  if (frameList == NULL)
  {
    frameList = entry; tailList = entry;
  }
  else
  {
    tailList->next = entry;
    tailList = entry;
  }
  listLength++;
  //cout << "Frame manager: Added frame to list. New length = " << listLength << endl;
  //cout << "(anchor = " << (void*)frameList << ", tail = " << (void*)tailList << ")" << endl;
}


void rviewFrameMgr::deregisterFrame(rviewFrame *client)
{
  int i;
  frame_list *list, *last;

  //cout << "frameManager::deregisterFrame(" << (void*)client << ")" << endl;
  list = frameList; last = NULL;
  for (i=0; i<listLength; i++)
  {
    if (list->frame == client)
    {
      list = list->next;
      if (last == NULL)
      {
	delete frameList; frameList = list; last = list;
      }
      else
      {
        delete last->next; last->next = list;
      }
      listLength--;
      if (last == NULL) tailList = NULL;
      else
      {
	while (last->next != NULL) last = last->next;
	tailList = last;
      }
      //cout << "Frame manager: Removed frame from list. New length = " << listLength << endl;
      //cout << "(anchor = " << (void*)frameList << ", tail = " << (void*)tailList << ")" << endl;
      return;
    }
    last = list; list = list->next;
  }
}



int rviewFrameMgr::numberOfFrames(void) const
{
  return listLength;
}



void rviewFrameMgr::setDeleteMode(bool delChild)
{
  deleteChildren = delChild;
}


// Issues re-label requests to all frames.
void rviewFrameMgr::labelAll(void)
{
  int i;
  frame_list *list;

  //cout << "frameManager::labelAll()" << endl;
  list = frameList;
  for (i=0; i<listLength; i++)
  {
    list->frame->label();
    list = list->next;
  }
}



/*
 *  Broadcasts the event to all frames until one claims the event by returning
 *  a value != 0. Warning: this function has to be re-entrant!
 */

void rviewFrameMgr::broadcastEvent(wxObject &obj, wxEvent &evt)
{
  int i;
  frame_list *list;

  // Note: the broadcast has to go in two steps, first determining which frame
  // knows the object, then terminating the loop and calling the object as the
  // last action. The reason is that this function is re-entrant and would
  // crash badly if the frame list changed during the loop.
  //cout << "frameManager::broadcastEvent()" << endl;
  list = frameList;
  for (i=0; i<listLength; i++)
  {
    //cout << "Broadcast to " << (void*)(list->frame) << endl;
    if (list->frame->checkobj(obj) != 0)
    {
      //cout << "Frame manager: object known by frame " << (void*)list->frame << endl;
      break;
    }
    list = list->next;
  }
  //cout << "Frame manager: broadcast " << ((list == NULL) ? "failed" : "successful") << endl;

  // Now call the frame.
  if (list != NULL) {list->frame->process(obj, evt);}
  // Uncomment this if there's any doubt it's re-entrant
  //cout << "frameManager::broadcastEvent done" << endl;
}



/*
 *  Broadcast a quit-message to all frames but the first one (the main frame). There
 *  are currently two levels, 0 means the frames can yet refuse to die by returning a
 *  value != 0, every other level doesn't give them this option. Returns 0 for failure.
 *  This must only be called for the _global_ frame manager!
 */

int rviewFrameMgr::broadcastQuit(int level)
{
  int i, status;
  frame_list *list;

  list = frameList->next; status = 1;
  for (i=1; i<listLength; i++)
  {
    //if (level > 0) cout << "delete " << (void*)list << endl;
    if (list->frame->requestQuit(level) != 0) status = 0;
    list = list->next;
  }
  if (level == 0) return status;

  //cout << "Hard quit OK" << endl;
  return 1;
}



/*
 *  Broadcast a user event to all frames.
 */

int rviewFrameMgr::broadcastUserEvent(const user_event &ue)
{
  int i, status;
  frame_list *list;

  list = frameList; status = 0;
  for (i=0; i<listLength; i++)
  {
    //cout << "broadcast to " << (void*)(list->frame) << endl;
    status += list->frame->userEvent(ue);
    list = list->next;
  }
  return status;	// number of clients that recognised the event.
}





/*
 *  rviewMultiline member functions
 */

const int rviewMultiline::multiline_ppc10 = 63;

void rviewMultiline::setupVariables(wxPanel *Panel, int X, int Y, int H, int Lines)
{
  int i;

  parent = Panel; lines = Lines;
  if ((msg = new wxMessage *[lines]) == NULL)
  {
    cerr << "rviewMultiline::setupVariables(): " << lman->lookup("errorMemory") << endl;
    return;
  }
  for (i=0; i<lines; i++) msg[i] = NULL;

  x = X; y = Y; lHeight = H;
}


rviewMultiline::rviewMultiline(wxPanel *Panel, int X, int Y, int H, int Lines)
{
  setupVariables(Panel, X, Y, H, Lines);
}


rviewMultiline::rviewMultiline(wxPanel *Panel, const char *Message, int X, int Y, int W, int H, int Lines)
{
  setupVariables(Panel, X, Y, H, Lines);

  rebuild(Message, W);
}


rviewMultiline::~rviewMultiline(void)
{
  // The wxMessage items have been created as children of the panel and will
  // be deleted by the panel later on. So just delete the array.
  delete [] msg;
}


void rviewMultiline::rebuild(const char *Message, int W)
{
  int length, i, cpl, pos;
  char *buffer, *b, *base;

  if (msg == NULL) return;

  //cout << "rviewMultiline::rebuild()" << endl;

  cpl = (10*W) / multiline_ppc10;

  if ((buffer = new char[cpl + 1]) == NULL)
  {
    cerr << "rviewMultiline::rebuild(): " << lman->lookup("errorMemory") << endl;
    return;
  }

  length = strlen(Message); base = (char*)Message;

  for (i=0, pos=y; (length > 0) && (i<lines); i++, pos+=lHeight)
  {
    if (length > cpl)
    {
      b = base + cpl;
      while ((*b > 32) && (b > base)) b--;
      if (b <= base) b = base + cpl; else b++;
    }
    else
    {
      b = base + length;
    }
    memcpy(buffer, base, (int)(b - base)); buffer[(int)(b - base)] = '\0';
    //cout << buffer << endl;
    if (msg[i] == NULL)
    {
      msg[i] = new wxMessage(parent, buffer, x, pos, W, lHeight, 0, "message");
    }
    else
    {
      msg[i]->SetSize(x, pos, W, lHeight, 0);
      msg[i]->SetLabel(buffer);
    }
    length -= (int)(b - base); base = b;
  }
  while (i<lines)
  {
    if (msg[i] != NULL) {delete msg[i]; msg[i] = NULL;}
    i++;
  }
  delete [] buffer;
}



int rviewMultiline::getMessageHeight(void) const
{
  int i;

  for (i=0; i<lines; i++) if (msg[i] == NULL) break;
  return(i*lHeight);
}



/*
 *  More convenient interface to standard widgets
 */

rviewText::rviewText(wxPanel *parent, const char *value, char *label, int x, int y, int w, int h) : wxText(parent, (wxFunction)rviewEventHandler, label, (char*)value, x, y, w, h, wxTE_PROCESS_ENTER)
{
}

rviewText::rviewText(long style, wxPanel *parent,  const char *value, char *label, int x, int y, int w, int h) : wxText(parent, (wxFunction)rviewEventHandler, label, (char*)value, x, y, w, h, style)
{
}

rviewText::rviewText(wxPanel *parent, const DynamicString &value, char *label, int x, int y, int w, int h) : wxText(parent, (wxFunction)rviewEventHandler, label, NULL, x, y, w, h, wxTE_PROCESS_ENTER)
{
  wxText::SetValue((char*)value.ptr());
}

rviewText::rviewText(wxPanel *parent, int value, char *label, int x, int y, int w, int h) : wxText(parent, (wxFunction)rviewEventHandler, label, NULL, x, y, w, h, wxTE_PROCESS_ENTER)
{
  char buffer[32];
  sprintf(buffer, "%d", value);
  wxText::SetValue(buffer);
}


rviewText::rviewText(wxPanel *parent, long value, char *label, int x, int y, int w, int h) : wxText(parent, (wxFunction)rviewEventHandler, label, NULL, x, y, w, h, wxTE_PROCESS_ENTER)
{
  char buffer[32];
  sprintf(buffer, "%ld", value);
  wxText::SetValue(buffer);
}


rviewText::rviewText(wxPanel *parent, double value, bool sciForm, char *label, int x, int y, int w, int h) : wxText(parent, (wxFunction)rviewEventHandler, label, NULL, x, y, w, h, wxTE_PROCESS_ENTER)
{
  char buffer[32];
  sprintf(buffer, (sciForm) ? "%g" : "%f", value);
  wxText::SetValue(buffer);
}

void rviewText::SetValue(char *value)
{
  wxText::SetValue(value);
}

void rviewText::SetValue(const char *value)
{
  wxText::SetValue((char*)value);
}

void rviewText::SetValue(const DynamicString &value)
{
  wxText::SetValue((char*)value.ptr());
}

void rviewText::SetValue(int value)
{
  char buffer[32];
  sprintf(buffer, "%d", value);
  wxText::SetValue(buffer);
}

void rviewText::SetValue(unsigned int value)
{
  char buffer[32];
  sprintf(buffer, "%u", value);
  wxText::SetValue(buffer);
}

void rviewText::SetValue(long value)
{
  char buffer[32];
  sprintf(buffer, "%ld", value);
  wxText::SetValue(buffer);
}

void rviewText::SetValue(double value, bool sciForm)
{
  char buffer[32];
  sprintf(buffer, (sciForm) ? "%g" : "%f", value);
  wxText::SetValue(buffer);
}

char *rviewText::GetValue(void)
{
  return wxText::GetValue();
}

void rviewText::GetValue(DynamicString &value)
{
  value = wxText::GetValue();
}

void rviewText::GetValue(int &value)
{
  value = asctoi(wxText::GetValue());
}

void rviewText::GetValue(long &value)
{
  value = asctol(wxText::GetValue());
}

void rviewText::GetValue(float &value)
{
  value = asctof(wxText::GetValue());
}

void rviewText::GetValue(double &value)
{
  value = asctof(wxText::GetValue());
}



rviewButton::rviewButton(wxPanel *parent, char *label, int x, int y, int w, int h, long style) : wxButton(parent, (wxFunction)rviewEventHandler, label, x, y, w, h, style)
{
}

rviewChoice::rviewChoice(wxPanel *parent, int n, char *choices[], char *label, int x, int y, int w, int h, long style) : wxChoice(parent, (wxFunction)rviewEventHandler, label, x, y, w, h, n, choices, style)
{
}

// hacked version to make up for wxWindows' lack of const
rviewChoice::rviewChoice(wxPanel *parent, int n, const char *choices[], char *label, int x, int y, int w, int h, long style) : wxChoice(parent, (wxFunction)rviewEventHandler, label, x, y, w, h, n, (char**)choices, style)
{
}

rviewCheckBox::rviewCheckBox(wxPanel *parent, char *label, int x, int y, int w, int h) : wxCheckBox(parent, (wxFunction)rviewEventHandler, label, x, y, w, h)
{
}

rviewRadioButton::rviewRadioButton(wxPanel *parent, char *label, bool value, int x, int y, int w, int h) : wxRadioButton(parent, (wxFunction)rviewEventHandler, label, value, x, y, w, h)
{
}

rviewScrollBar::rviewScrollBar(wxPanel *parent, int x, int y, int w, int h, long style) : wxScrollBar(parent, (wxFunction)rviewEventHandler, x, y, w, h, style)
{
}

rviewSlider::rviewSlider(wxPanel *parent, int value, int min_val, int max_val, int width, char *label, int x, int y, long style) : wxSlider(parent, (wxFunction)rviewEventHandler, label, value, min_val, max_val, x, y, style)
{
}



/*
 *  The special slider class when arbitrary mouse events are required.
 */
 
const int rviewSpecialSlider::dflt_barwidth = 30;
const int rviewSpecialSlider::dflt_barheight = 10;
const int rviewSpecialSlider::dflt_width = 200;
const int rviewSpecialSlider::dflt_height = rviewSpecialSlider::dflt_barheight + 2*rviewSpecialSlider::dflt_border;
const int rviewSpecialSlider::dflt_border = 4;

rviewSpecialSlider::rviewSpecialSlider(rviewFrame *logParent, wxPanel *parent, int val, int min, int max, int width, const char *label) :
  wxCanvas(parent, -1, -1, (width==-1) ? dflt_width : width, dflt_height, wxRETAINED),
  background(0x00,0x00,0x00),
  foreground(0x00,0xff,0x00),
  wellground(0xff,0xff,0xff),
  outline(0x00,0x00,0x00),
  labelColour(*(parent->GetLabelColour())),
  bback(background, wxTRANSPARENT),
  bfore(foreground, wxSOLID),
  bwell(wellground, wxSOLID),
  outlinePen(outline, 1, wxSOLID),
  labelFont(12, wxROMAN, wxNORMAL, wxNORMAL),
  myLabel(label)
{
  wxBrush *dcb;
  logicalParent = logParent;
  border = dflt_border;
  barwidth = dflt_barwidth; barheight = dflt_barheight;
  value = val;
  vmin = min; vmax = max;
  if (vmax <= vmin)
    vmax = vmin+1;
  dcb = ((wxPanel*)GetParent())->GetDC()->GetBackground();
  bback = wxBrush(dcb->GetColour(), dcb->GetStyle());
  SetBackground(&bback);
  SetFont(&labelFont);
  GetDC()->GetTextExtent(myLabel.ptr(), &textx, &texty);
}

rviewSpecialSlider::~rviewSpecialSlider(void)
{
}

int rviewSpecialSlider::GetMin(void) const
{
  return vmin;
}

int rviewSpecialSlider::GetMax(void) const
{
  return vmax;
}

int rviewSpecialSlider::GetValue(void) const
{
  return value;
}

void rviewSpecialSlider::SetRange(int min, int max)
{
  if (min < max)
  {
    vmin = min; vmax = max;
    if (value < vmin)
      value = vmin;
    if (value > vmax)
      value = vmax;
    Refresh(TRUE);
  }
}

void rviewSpecialSlider::SetValue(int val)
{
  if ((vmin <= val) && (val <= vmax))
  {
    float barx, bary, bheight, newbx;
    
    getBarParams(barx, bary, bheight);
    value = val;
    getBarParams(newbx, bary, bheight);
    updateWell(barx, newbx, bary, bheight);
  }
}

void rviewSpecialSlider::SetLabel(const char *label)
{
  myLabel = label;
  GetDC()->GetTextExtent(myLabel.ptr(), &textx, &texty);
  Refresh(TRUE);
}

bool rviewSpecialSlider::PositionInWell(float posx, float posy)
{
  int y0, y1;
  
  GetClientSize(&cwidth, &cheight);
  getWellVert(y0, y1);
  if (((float)y0 <= posy) && (posy <= (float)y1))
  {
    if ((posx >= textx + 2*border) && (posx <= (float(cwidth - border))))
      return TRUE;
  }
  return FALSE;
}


void rviewSpecialSlider::getWellVert(int &y0, int &y1)
{
  y0 = cheight - 2*border - barheight;
  if (y0 < 0)
    y0 = 0;
  y0 += border;
  y1 = cheight - border;
  if (y1 < y0)
    y1 = y0;
}

void rviewSpecialSlider::getBarParams(float &posx, float &posy, float &height)
{
  int y0, y1;
  
  GetClientSize(&cwidth, &cheight);

  posx = (float)((cwidth - 3*border - barwidth - textx) * (value-vmin)) / (vmax - vmin);
  if (posx < 0)
    posx = 0;
  /*cout << "cwidth " << cwidth << ", textx " << textx << ", value " << value << ", border " << border
       << ", barwidth " << barwidth << ", vmin " << vmin << ", vmax " << vmax << ", posx " << posx << endl;*/
  posx += (float)(2*border + textx);
  getWellVert(y0, y1);
  posy = (float)y0;
  height = (float)(y1 - y0);
}

int rviewSpecialSlider::calcNewValue(float posx, float posy, int &val, bool checky)
{
  int y0, y1;
  
  GetClientSize(&cwidth, &cheight);
  
  getWellVert(y0, y1);
  if (!checky || ((float)y0 <= posy) && (posy <= (float)y1))
  {
    float rem = (float)(cwidth - 3*border - barwidth - textx);
    if (rem < 1.0)
      rem = 1.0;
    val = (int)((((posx - 2*border - textx) * (vmax - vmin)) / rem) + 0.5) + vmin;
    if (val < vmin)
      val = vmin;
    if (val > vmax)
      val = vmax;
    
    return 0;
  }
  return -1;
}


void rviewSpecialSlider::getUpdateInterval(float oldx, float newx, float &clipx, float &clipw)
{
  if (oldx < newx)
  {
    clipx = oldx; clipw = newx - oldx + barwidth;
  }
  else
  {
    clipx = newx; clipw = oldx - newx + barwidth;
  }
}


void rviewSpecialSlider::updateWell(float oldx, float newx, float posy, float bheight)
{
  float clipx, clipw;
    
  getUpdateInterval(oldx, newx, clipx, clipw);
  //cout << "CLIP " << clipx << ", " << posy << ", " << clipw << ", " << bheight << endl;
  // need to enlarge the clipping region somewhat to make sure everything is redrawn
  BeginDrawing();
  SetClippingRegion(clipx, 0, clipw+2, cheight);
  //Clear();
  redrawCore(newx, posy, bheight);
  DestroyClippingRegion();
  EndDrawing();
}


void rviewSpecialSlider::redrawCore(float x, float y, float bheight)
{
  float extx, exty, nx, ny;
  char number[32];
  
  // first draw the label
  SetFont(&labelFont);
  SetTextForeground(&labelColour);
  DrawText(myLabel.ptr(), 0, y);

  SetPen(&outlinePen);
  SetBrush(&bwell);
  DrawRectangle(textx + border, y-border, (float)cwidth - textx - border, bheight + 2*border);
  SetBrush(&bfore);
  DrawRectangle(x, y, (float)barwidth, bheight);
  
  // then draw the current value on top
  sprintf(number, "%d", value);
  GetDC()->GetTextExtent(number, &extx, &exty);
  nx = x + (barwidth - extx)/2; ny = y - exty - border;
  SetPen(NULL);
  // must use a non-transparent brush. Finally found the right one!
  SetBrush(((wxPanel*)GetParent())->GetDC()->GetBackground());
  DrawRectangle(0, ny, (float)cwidth, exty);
  DrawText(number, nx, ny);
}


void rviewSpecialSlider::OnPaint(void)
{
  wxRect rect;
  float x, y, bheight;
  
  getBarParams(x, y, bheight);
    
  BeginDrawing();
  
  wxUpdateIterator upd(this);
  while (upd)
  {
    upd.GetRect(&rect);
    redrawCore(x, y, bheight);
    upd++;
  }
  EndDrawing();
}

void rviewSpecialSlider::OnEvent(wxMouseEvent &mevt)
{
  int type = mevt.GetEventType();
  float barx, bary, bheight;
  float mx, my;
  int newVal = value;
  
  getBarParams(barx, bary, bheight);
  mevt.Position(&mx, &my);
  if ((type == wxEVENT_TYPE_LEFT_DOWN) || (type == wxEVENT_TYPE_RIGHT_DOWN))
  {
    if (mx < barx)
    {
      if (calcNewValue(barx - barwidth, my, newVal, TRUE) != 0)
        newVal = value;
    }
    else if (mx > barx + barwidth)
    {
      if (calcNewValue(barx + barwidth, my, newVal, TRUE) != 0)
        newVal = value;
    }
  }
  else if (type == wxEVENT_TYPE_MOTION)
  {
    if (mevt.LeftIsDown() || mevt.RightIsDown())
    {
      if (calcNewValue(mx - barwidth/2, my, newVal, FALSE) != 0)
      {
        newVal = value;
      }
    }
  }
  if (newVal != value)
  {
    float newbx, newby, newbh;
    
    value = newVal;
    getBarParams(newbx, newby, newbh);
    updateWell(barx, newbx, bary, bheight);

    // additionally we build a regular command event
    wxCommandEvent cmd(wxEVENT_TYPE_SLIDER_COMMAND);
    //OnCommand(*GetParent(), cmd);
    logicalParent->process(*this, cmd);
  }
  // the entire point of this class is to always pass on the actual mouse event to the parent
  logicalParent->childMouseEvent(this, mevt);
}






/*
 *  rviewDialog member functions.
 */

const int rviewDialog::dialog_width = 300;
const int rviewDialog::dialog_height = 170;
const int rviewDialog::dialog_border = 8;
const int rviewDialog::dialog_buttonsx = 80;
const int rviewDialog::dialog_buttonsy = 30;
const int rviewDialog::dialog_bheight = rviewDialog::dialog_buttonsy + 16;
const int rviewDialog::dialog_lines = 8;
const int rviewDialog::dialog_lheight = 20;


// The strings passed to this function may be labels (first char is a backslash)
// or explicit text.
rviewDialog::rviewDialog(const char *title, const char *message, int buttonNo, const char *buttons[]):
  rviewFrame(NULL, "", 0, 0, dialog_width, dialog_height)
{
  int i, x, y;
  char *string;

  panel = NULL; buttonNumber = 0; buttonPressed = 0;

  buttonText = new char *[buttonNo + 2];
  but = new rviewButton *[buttonNo];

  if ((buttonText == NULL) || (but == NULL))
  {
    cerr << "rviewDialog::rviewDialog(): " << lman->lookup("errorMemory") << endl;
    if (buttonText != NULL) delete [] buttonText;
    if (but != NULL) delete [] but;
    return;
  }

  buttonNumber = buttonNo;

  buttonText[0] = (char*)title; buttonText[1] = (char*)message;
  for (i=0; i<buttonNumber; i++)
  {
    but[i] = NULL; buttonText[i+2] = (char*)buttons[i];
  }

  // Only memorize those strings that are a label identifier (first char a backslash)
  for (i=0; i<2+buttonNumber; i++)
  {
    if (buttonText[i] != NULL)
    {
      // Don't combine the two ifs with && : there is no defined evaluation order for && !
      // Always memorize the message text.
      if ((buttonText[i][0] == '\\') || (i == 1))
      {
        // We remove the backslash but need one additional char for the
        // line terminator ==> strlen -1 + 1.
        if ((string = new char[strlen(buttonText[i]) + ((i==1) ? 1 : 0)]) == NULL)
        {
	  cerr << "rviewDialog::rviewDialog(): " << lman->lookup("errorMemory") << endl;
	  while (--i >= 0)
	  {
	    if (buttonText[i] != NULL) delete [] buttonText[i];
	  }
	  delete [] buttonText; buttonText = NULL;
	  delete [] but; but = NULL;
	  buttonNumber = 0;
	  return;
        }
        strcpy(string, buttonText[i] + ((i==1) ? 0 : 1)); buttonText[i] = string;
	//cout << "buttonText[" << i << "] = " << buttonText[i] << endl;
      }
      else buttonText[i] = NULL;
    }
  }

  GetClientSize(&x, &y);

  panel = new wxPanel((wxWindow*)this, 100, 100, 10, 10);

  msg = new rviewMultiline(panel, dialog_border, dialog_border, dialog_lheight, dialog_lines);

  //cout << x << ", " << y << endl;

  // If the strings are not labels then set them now statically, otherwise they will
  // be set in the following label() call.
  if (title[0] != '\\')
  {
    SetTitle((char*)title);
  }

  // Now handle all buttons.
  for (i=0; i<buttonNumber; i++)
  {
    but[i] = new rviewButton(panel);
    if (buttons[i][0] != '\\')
    {
      but[i]->SetLabel((char*)buttons[i]);
    }
    else	// do this for the button size.
    {
      but[i]->SetLabel(lman->lookup(buttons[i]+1));
    }
  }

  OnSize(x, y);

  label();

  Show(TRUE);
}



rviewDialog::~rviewDialog(void)
{
  int i;

  // Widgets that were created as children of other wx items are deleted by those items.
  // They mustn't be destroyed here!

  if (msg != NULL) delete msg;
  //if (panel != NULL) delete panel;

  if (but != NULL)
  {
    //for (i=0; i<buttonNumber; i++) {if (but[i] != NULL) delete but[i];}
    delete [] but;
  }

  if (buttonText != NULL)
  {
    for (i=0; i<2+buttonNumber; i++) {if (buttonText[i] != NULL) delete [] buttonText[i];}
    delete [] buttonText;
  }
}


const char *rviewDialog::getFrameName(void) const
{
  return "rviewDialog";
}

rviewFrameType rviewDialog::getFrameType(void) const
{
  return rviewFrameTypeDialog;
}


void rviewDialog::OnSize(int w, int h)
{
  int x, y, empty, pos, i;

  RMDBGONCE( 3, RMDebug::module_applications, "rviewDialog", "OnSize( " << x << ", " << h << " )" ); 

  GetClientSize(&x, &y);
  if ((frameWidth == x) && (frameHeight == y)) return;
  frameWidth = x; frameHeight = y;

  x -= 2*dialog_border; y -= dialog_border;
  panel->SetSize(0, 0, x, y);

  if (buttonText[1][0] == '\\')
    msg->rebuild(lman->lookup(buttonText[1]+1), x);
  else
    msg->rebuild(buttonText[1], x);

  // Space out the buttons on the available space.
  if (buttonNumber == 0) return;

  empty = (x - buttonNumber*dialog_buttonsx) / buttonNumber; 
  if(empty <0 )
	empty=0;
	
  pos = empty/2;

  for (i=0; i<buttonNumber; i++)
  {
    but[i]->SetSize(pos, y - (dialog_bheight + dialog_buttonsy)/2, dialog_buttonsx, dialog_buttonsy);
    pos += empty + dialog_buttonsx;
  }
}



void rviewDialog::label(void)
{
  int i, x, y;

  //cout << "rviewDialog::label()" << endl;
  // If the widgets are labels then set their new values.

  panel->GetClientSize(&x, &y);
  if (buttonText[0] != NULL)
  {
    SetTitle(lman->lookup(buttonText[0]));
  }

  // The message is always stored.
  if (buttonText[1][0] == '\\')
    msg->rebuild(lman->lookup(buttonText[1]+1), x);
  else
    msg->rebuild(buttonText[1], x);

  for (i=0; i<buttonNumber; i++)
  {
    if (buttonText[2+i] != NULL)
    {
      but[i]->SetLabel(lman->lookup(buttonText[2+i]));
    }
  }
}




/*
 *  Process events which are broadcast by the frame manager.
 */

int rviewDialog::process(wxObject &obj, wxEvent &evt)
{
  int i, type;

  //cout << "rviewDialog::process()" << endl;
  for (i=0; i<buttonNumber; i++)
  {
    if (&obj == (wxObject*)but[i]) break;
  }

  if (i >= buttonNumber) return 0;

  type = evt.GetEventType();

  if (type == wxEVENT_TYPE_BUTTON_COMMAND)
  {
    buttonPressed = i+1;
  }
  else
  {
    buttonPressed = 0;
  }
  //cout << "rviewDialog::process():" << (void*)this << " Button " << buttonPressed << endl;

  return buttonPressed;
}



/*
 *  Polling interface to the dialog box. Returns the number of the button that
 *  was pressed, starting from 1 (0 means none). On reading the button number
 *  is reset to 0.
 */

int rviewDialog::GetButton(void)
{
  int val = buttonPressed;

  buttonPressed = 0;
  return val;
}





/*
 *  Error box
 *  (an intrinsically modal special case of a dialog box)
 */

char *rviewErrorboxDefaultButton[1] = {"\\textOK"};

rviewErrorbox::rviewErrorbox(const char *message): rviewDialog("\\errorFrom", message, 1, (const char**)rviewErrorboxDefaultButton)
{
  //place this in log file
  cerr << lman->lookup("errorFrom") << ' ' << message << endl;
}


rviewErrorbox::rviewErrorbox(const char *title, const char *message, int buttonNo, const char *buttons[]): rviewDialog(title, message, buttonNo, buttons)
{
  //place this in log file
  cerr << lman->lookup("errorFrom") << ' ' << message << endl;
}


rviewErrorbox::~rviewErrorbox(void) {;}


const char *rviewErrorbox::getFrameName(void) const
{
  return "rviewErrorbox";
}

rviewFrameType rviewErrorbox::getFrameType(void) const
{
  return rviewFrameTypeErrorbox;
}


int rviewErrorbox::activate(void)
{
  int pressed;

  MakeModal(TRUE);
  while ((pressed = GetButton()) == 0) ::wxYield();
  MakeModal(FALSE);
  return pressed;
}


// static member functions
char *rviewErrorbox::buildErrorMessage(const char *message, const char *classname, const char *funcname)
{
  char *buffer, *b;
  int bsize = strlen(message) + 1;

  if (classname != NULL)
  {
    bsize += strlen(classname) + 3;	// ": "

    // funcname is ignored unless class name is given
    if (funcname != NULL)
      bsize += strlen(funcname) + 3;	// "::"
  }

  buffer = new char[bsize];
  b = buffer;

  if (classname != NULL)
  {
    b += sprintf(b, "%s", classname);

    if (funcname != NULL)
      b += sprintf(b, "::%s", funcname);

    b += sprintf(b, ": ");
  }
  b += sprintf(b, "%s", message);

  return buffer;
}


rviewErrorbox *rviewErrorbox::newErrorbox(const char *message, const char *classname, const char *funcname)
{
  char *msg;
  rviewErrorbox *box;

  msg = buildErrorMessage(message, classname, funcname);
  box = new rviewErrorbox(msg);
  delete [] msg;
  
  return box;
}


rviewErrorbox *rviewErrorbox::newErrorbox(const char *title, const char *message, int buttonNo, const char *buttons[], const char *classname, const char *funcname)
{
  char *msg;
  rviewErrorbox *box;

  msg = buildErrorMessage(message, classname, funcname);
  box = new rviewErrorbox(msg);
  delete [] msg;

  return box;
}


int rviewErrorbox::reportError(const char *message, const char *classname, const char *funcname)
{
  rviewErrorbox *box;
  int but;

  box = newErrorbox(message, classname, funcname);
  but = box->activate();
  box->Close(TRUE);

  return but;
}


int rviewErrorbox::reportError(const char *title, const char *message, int buttonNo, const char *buttons[], const char *classname, const char *funcname)
{
  rviewErrorbox *box;
  int but;

  box = newErrorbox(title, message, buttonNo, buttons, classname, funcname);
  but = box->activate();
  box->Close(TRUE);

  return but;
}

  



/*
 *  rviewProgress members
 */

rviewProgress::rviewProgress(const char *message): rviewDialog("\\messageFrom", message, 1, (const char**)rviewErrorboxDefaultButton)
{
  int x, y;

  RMDBGONCE( 3, RMDebug::module_applications, "rviewProgress", "rviewProgress( " << lman->lookup("messageFrom") << message << " )" ); 

  GetSize(&x, &y);
  y = 2*dialog_border + msg->getMessageHeight() + dialog_bheight;
  SetSize(-1, -1, x, y);

  // Have to do this to make sure you actually see anything in the window
  // Crude, but nothing else seems to work...
  Refresh(TRUE); ::wxYield();
  // Wait 300ms
  ::wxStartTimer();
  while (::wxGetElapsedTime(FALSE) < 300) ::wxYield();
}




rviewProgress::~rviewProgress(void) {;}


int rviewProgress::process(wxObject &obj, wxEvent &evt)
{
  if (rviewDialog::process(obj, evt) != 0)
  {
    this->Close(TRUE);
    return 1;
  }
  return 0;
}


const char *rviewProgress::getFrameName(void) const
{
  return "rviewProgress";
}

rviewFrameType rviewProgress::getFrameType(void) const
{
  return rviewFrameTypeProgress;
}




/*
 *  rviewResult members
 */

const int rviewResult::result_x = 0;
const int rviewResult::result_y = 0;
const int rviewResult::result_width = 320;
const int rviewResult::result_height = 296;
const int rviewResult::result_border = 8;
const int rviewResult::result_lheight = 20;
const int rviewResult::result_header = (8 * rviewResult::result_lheight);
const int rviewResult::result_cwidth = 150;
const int rviewResult::result_twidth = 90;
const int rviewResult::result_theight = 30;
const int rviewResult::result_bwidth = 60;
const int rviewResult::result_bheight = 30;

rviewResult::rviewResult(void): rviewFrame(NULL, "", result_x, result_y, result_width, result_height)
{
  RMDBGONCE( 3, RMDebug::module_applications, "rviewResult", "rviewResult() " << this);

  setupVariables();
  configureGrey();
  Show(FALSE);
}

rviewResult::rviewResult(collection_desc *collection): rviewFrame(NULL, "", result_x, result_y, result_width, result_height)
{
  setupVariables();
  setCollection(collection);
}


rviewResult::~rviewResult(void)
{
  RMDBGONCE( 3, RMDebug::module_applications, "rviewResult", "rviewResult() " << this );

  int i;
  collection_desc *ptr = coll;
  user_event ue;

  // give all viewers a chance to clean up
  ue.type = usr_mdd_dying;
  for (i=0; i<coll->number; i++)
  {
    ue.data = (void*)&(coll->mddObjs[i].mdd);
    frames->broadcastUserEvent(ue);
  }

  // All the widgets are deleted automatically.
  if (selectedItems != NULL) delete [] selectedItems;
  if (typeManager != NULL) {typeManager->unlinkParent(); typeManager->Close(TRUE);}

  rviewDeleteCollection(coll);
}


const char *rviewResult::getFrameName(void) const
{
  return "rviewResult";
}

rviewFrameType rviewResult::getFrameType(void) const
{
  return rviewFrameTypeResult;
}


void rviewResult::setCollection(collection_desc *collection)
{
  int x, y, i;
  char res_string[STRINGSIZE];

  // In case this is called when the frame already displays a result (shouldn't
  // normally happen, though)
  if (coll != NULL)
  {
    rviewDeleteCollection(coll);
    delete list;
  }
  coll = collection;

  // Init flags
  for (i=0; i<coll->number; i++)
  {
    coll->mddObjs[i].flags = 0;
  }

  GetClientSize(&x, &y);

  list = new wxListBox(panel, (wxFunction)&rviewEventHandler, "", wxMULTIPLE, result_border, result_border + result_header, x, y - result_header, 0, NULL, wxALWAYS_SB | wxLB_MULTIPLE);

  ostrstream memstr(res_string, STRINGSIZE);
  for (i=0; i<coll->number; i++)
  {
    list->Append(mddDescriptorString(memstr, i));
  }

  if (selectedItems != NULL) delete [] selectedItems;
  i = (coll->number + 7) >> 3;
  if ((selectedItems = new char[i]) == NULL)
  {
    cerr << "rviewResult::setCollection(): " << lman->lookup("errorMemory") << endl;
    this->Close(TRUE);
    return;
  }
  memset(selectedItems, 0, i);

  configureGrey();

  label();

  // Force resize
  frameWidth = -1; frameHeight = -1;
  OnSize(x, y);

  Show(TRUE);
}



char *rviewResult::mddDescriptorString(ostrstream &memstr, int number)
{
  r_GMarray *mdd = coll->mddObjs[number].mdd.ptr();
  r_Data_Format fmt = mdd->get_current_format();

  memstr.width(3);
  memstr << number << ": ("; memstr.width(0);
  memstr << mdd->get_type_length() << ") "
	 << mdd->spatial_domain() << ' '
	 << fmt << '\0';
  memstr.seekp(0);

  return memstr.str();
}


void rviewResult::label(void)
{
  char buffer[STRINGSIZE];

  //cout << "labelling " << (void*)mBar << endl;

  SetTitle(lman->lookup("titleResult"));

  if (mBar != NULL)
  {
    // Configure all the text in the menu bar
    mBar->SetLabel(MENU_RSLT_ITEM_OPENALL, lman->lookup("menRsltItemOpAll"));
    mBar->SetLabel(MENU_RSLT_ITEM_THUMBALL, lman->lookup("menRsltItemThumbAll"));
    mBar->SetLabel(MENU_RSLT_ITEM_CLOSE, lman->lookup("menRsltItemClose"));
    mBar->SetHelpString(MENU_RSLT_ITEM_OPENALL, lman->lookup("helpRsltItemOpAll"));
    mBar->SetHelpString(MENU_RSLT_ITEM_THUMBALL, lman->lookup("helpRsltItemThumbAll"));
    mBar->SetHelpString(MENU_RSLT_ITEM_CLOSE, lman->lookup("helpRsltItemClose"));

    mBar->SetLabel(MENU_RSLT_SLCT_SLCTALL, lman->lookup("menRsltSlctSlctAll"));
    mBar->SetLabel(MENU_RSLT_SLCT_CLEAR, lman->lookup("menRsltSlctClear"));
    mBar->SetLabel(MENU_RSLT_SLCT_OPEN, lman->lookup("menRsltSlctOpen"));
    mBar->SetLabel(MENU_RSLT_SLCT_THUMB, lman->lookup("menRsltSlctThumb"));
    mBar->SetLabel(MENU_RSLT_SLCT_DELETE, lman->lookup("menRsltSlctDel"));
    mBar->SetLabel(MENU_RSLT_SLCT_ENDIAN, lman->lookup("menRsltSlctEndian"));
    mBar->SetLabel(MENU_RSLT_SLCT_TYPEMAN, lman->lookup("menRsltSlctTypeMan"));
    mBar->SetLabel(MENU_RSLT_SLCT_INFO, lman->lookup("menRsltSlctInfo"));
    mBar->SetHelpString(MENU_RSLT_SLCT_SLCTALL, lman->lookup("helpRsltSlctSlctAll"));
    mBar->SetHelpString(MENU_RSLT_SLCT_CLEAR, lman->lookup("helpRsltSlctClear"));
    mBar->SetHelpString(MENU_RSLT_SLCT_OPEN, lman->lookup("helpRsltSlctOpen"));
    mBar->SetHelpString(MENU_RSLT_SLCT_THUMB, lman->lookup("helpRsltSlctThumb"));
    mBar->SetHelpString(MENU_RSLT_SLCT_DELETE, lman->lookup("helpRsltSlctDel"));
    mBar->SetHelpString(MENU_RSLT_SLCT_ENDIAN, lman->lookup("helpRsltSlctEndian"));
    mBar->SetHelpString(MENU_RSLT_SLCT_TYPEMAN, lman->lookup("helpRsltSlctTypeMan"));
    mBar->SetHelpString(MENU_RSLT_SLCT_INFO, lman->lookup("helpRsltSlctInfo"));

    mBar->SetLabelTop(0, lman->lookup("menRsltItem"));
    mBar->SetLabelTop(1, lman->lookup("menRsltSlct"));
  }

  if (list != NULL)
  {
    list->SetLabel(lman->lookup("textResult"));
  }

  if (group != NULL)
  {
    group->SetLabel(lman->lookup("textCollHeader"));
    sprintf(buffer, "%s: %s", lman->lookup("textCollName"), (coll->collName == NULL) ? "" : coll->collName);
    collName->SetLabel(buffer);
    sprintf(buffer, "%s: %s", lman->lookup("textCollType"), (coll->collType == NULL) ? "?" : coll->collType);
    collType->SetLabel(buffer);
    sprintf(buffer, (coll->collInfo == NULL) ? "" : coll->collInfo);
    collInfo->SetLabel(buffer);

    if (choice != NULL)
    {
      choice->SetLabel(lman->lookup("dispModeLabel"));
    }
  }
  resampBut->SetLabel(lman->lookup("textOK"));

  //cout << "labelled OK" << endl;
}



void rviewResult::OnSize(int w, int h)
{
  if (panel != NULL)
  {
    int x, y;

    RMDBGONCE( 3, RMDebug::module_applications, "rviewResult", "OnSize( " << w << ", " << h << " )");

    GetClientSize(&x, &y);
    if ((frameWidth == x) && (frameHeight == y)) return;
    frameWidth = x; frameHeight = y;

    panel->SetClientSize(x, y);
    x -= 2*result_border; y -= 2*result_border;

    if (list != NULL)
      list->SetSize(result_border, 
		    result_lheight + result_border + result_header, 
		    x, 
		    y - result_header - result_lheight);

    if (group != NULL)
    {
      group->SetSize(result_border,
		     result_border, 
		     x,
		     result_header);
      //group->GetClientSize(&x, &y);
      x -= 2*result_border; y -=2*result_border;
      if (collName != NULL)
        collName->SetSize(2*result_border, 
			  result_lheight + result_border, 
			  x,
			  result_lheight);
      if (collType != NULL)
	collType->SetSize(2*result_border, 
			  2*result_lheight + result_border, 
			  x,
			  result_lheight);
      if (collInfo != NULL)
	collInfo->SetSize(2*result_border, 
			  3*result_lheight + result_border, 
			  x, 
			  result_lheight);
      if (choice != NULL)
        choice->SetSize(2*result_border, 
			4*result_lheight + result_border, 
			result_cwidth - cbfactor, 
			result_lheight);
    }
    scaleMode->SetSize(3*result_border/2, 
		       6*result_lheight + result_border, 
		       result_cwidth - 2*cbfactor, 
		       result_lheight);
    resampText->SetSize(3*result_border/2 + result_cwidth - cbfactor, 
			6*result_lheight + result_border, 
			result_twidth, 
			result_theight);
    resampBut->SetSize(3*result_border/2 + result_cwidth - cbfactor/2 + result_twidth,
		       6*result_lheight + result_border,
		       result_bwidth,
		       result_bheight);
  }
}



void rviewResult::openViewer(int itemNo)
{

  RMDBGONCE( 3, RMDebug::module_applications, "rviewResult", "openViewer( " << itemNo << " )" ); 

  if ((itemNo < 0) || (itemNo >= coll->number)) return;

  rviewDisplay *newDisplay=NULL;

  switch (prefs->lastDisplay)
  {
    case 0:
      {
	if ((coll->mddObjs[itemNo].flags & RVIEW_RESDISP_IMGFLAT) == 0)
        {
          newDisplay = new rviewFlatImage(coll->mddObjs + itemNo);
	}
      }
      break;
    case 1:
      {
	if ((coll->mddObjs[itemNo].flags & RVIEW_RESDISP_IMGVOLM) == 0)
	{
	  newDisplay = new rviewVolumeImage(coll->mddObjs + itemNo);
	}
      }
      break;
    case 2:
      {
        if ((coll->mddObjs[itemNo].flags & RVIEW_RESDISP_IMGOSECT) == 0)
	{
	  newDisplay = new rviewOSectionFullImage(coll->mddObjs + itemNo);
	}
      }
      break;
    case 3:
      {
	if ((coll->mddObjs[itemNo].flags & RVIEW_RESDISP_IMGHGHT) == 0)
	{
	  newDisplay = new rviewHeightImage(coll->mddObjs + itemNo);
	}
      }
      break;
    case 4:
      {
        if ((coll->mddObjs[itemNo].flags & RVIEW_RESDISP_CHART) == 0)
        {
          newDisplay = new rviewChart(coll->mddObjs + itemNo);
        }
      }
      break;
    case 5:
      {
        if ((coll->mddObjs[itemNo].flags & RVIEW_RESDISP_TABLE) == 0)
        {
          newDisplay = new rviewTable(coll->mddObjs + itemNo);
        }
      }
      break;
    case 6:
      {
	if ((coll->mddObjs[itemNo].flags & RVIEW_RESDISP_SOUND) == 0)
	{
	  newDisplay = new rviewSoundPlayer(coll->mddObjs + itemNo);
	}
      }
      break;
    case 7:
      {
        if ((coll->mddObjs[itemNo].flags & RVIEW_RESDISP_STRVIEW) == 0)
	{
	  newDisplay = new rviewStringViewer(coll->mddObjs + itemNo);
	}
      }
      break;
    default:
      cerr << "Unsupported display mode " << prefs->lastDisplay << endl;
      return;
  }

  if (newDisplay != NULL)
  {
    if (newDisplay->openViewer() != 0)
      newDisplay->Close(TRUE);
    else
    {
      coll->mddObjs[itemNo].flags |= newDisplay->getViewerType();
      registerChild(newDisplay);
    }
  }
}



/*
 *  This function must be called whenever the selections of the list box
 *  change (click / double click) or items in the listbox are modified or
 *  deleted (this seems to be some wxWindows-internal bug that always
 *  deselects listbox items if an item was changed).
 */
int rviewResult::updateSelection(void)
{
  int i, changes, sel=-1;
  char val;

  if (selectedItems == NULL) return -1;

  changes = 0;
  for (i=0; i<coll->number; i++)
  {
    val = selectedItems[i>>3] & (1<<(i&7));
    if (list->Selected(i))
    {
      if (val == 0) {sel=i; changes++;}
      selectedItems[i>>3] |= (1<<(i&7));
    }
    else
    {
      if (val != 0) {sel=i; changes++;}
      selectedItems[i>>3] &= ~(1<<(i&7));
    }
  }
  if (changes > 1)
  {
    cerr << "Warning: more than one selection changed!" << endl;
  }

  configureGrey();

  return sel;
}



void rviewResult::operationPrologue(void)
{
  ::wxBeginBusyCursor();
  ::wxStartTimer();
}


void rviewResult::operationEpilogue(const char *opname)
{
  int elapsed = ::wxGetElapsedTime();

  ::wxEndBusyCursor();

  if (opname != NULL)
  {
    char buffer[STRINGSIZE];

    sprintf(buffer, "%s \"%s\": %dms", lman->lookup("textOpTime"), opname, elapsed);
    cout << buffer << endl;
    SetStatusText(buffer);
  }
}


int rviewResult::parseResampleString(const char *resStr, double *values)
{
  int i;
  const char *b;

  b = resStr; i = 0;
  while (*b != 0)
  {
    while ((*b == ' ') || (*b == '\t')) b++;
    if (*b == ',') b++;
    if (*b != 0)
    {
      if (values != NULL) values[i] = atof(b);
      while ((*b != ' ') && (*b != '\t') && (*b != ',') && (*b != 0)) b++;
      i++;
    }
  }
  return i;
}


int rviewResult::resampleSelection(void)
{
  int i, j, res;
  double *scale;
  r_Dimension dim;
  r_Minterval oldInterv, useInterv, newInterv;
  r_Ref<r_GMarray> newMdd;
  rviewBaseType baseType;
  char buffer[STRINGSIZE];
  user_event usr;
  char *valStr;
  int dimString;
  int smode;
  const char *operation=NULL;

  ostrstream memstr(buffer, STRINGSIZE);

  valStr = resampText->GetValue();
  dimString = parseResampleString(valStr, NULL);
  scale = new double[dimString];
  parseResampleString(valStr, scale);

  for (i=0; i<dimString; i++)
  {
    if (scale[i] <= 0.0) return 0;
    if (scale[i] != 1.0) break;
  }

  smode = scaleMode->GetSelection();

  operationPrologue();

  res = 0;
  for (i=0; i<coll->number; i++)
  {
    if (list->Selected(i))
    {
      double totalScale = 1.0;

      baseType = rviewGetBasetype((r_Object*)(&(*(coll->mddObjs[i].mdd))));
      oldInterv = (coll->mddObjs[i].mdd)->spatial_domain();
      dim = oldInterv.dimension();
      newInterv = r_Minterval(dim); useInterv = r_Minterval(dim);
      for (j=0; j<(int)dim; j++)
      {
	double h;

	// Use the entire source object for scaling
	useInterv << oldInterv[j];
	h = (j < dimString) ? scale[j] : scale[dimString-1]; totalScale *= h;
        newInterv << r_Sinterval((r_Range)(oldInterv[j].low()), (r_Range)(oldInterv[j].low() + h*(oldInterv[j].high() - oldInterv[j].low() + 1) - 1));
      }
      if (smode == 0)	// resampling mode
      {
        if (totalScale > 1.0)
        {
	  operation = lman->lookup("operationUpsamp");
          j = mdd_objectScaleInter(coll->mddObjs[i].mdd, useInterv, newMdd, newInterv);
        }
        else
        {
	  operation = lman->lookup("operationDownsamp");
          j = mdd_objectScaleAverage(coll->mddObjs[i].mdd, useInterv, newMdd, newInterv);
        }
      }
      else	// simple scale mode
      {
	operation = lman->lookup("operationScale");
	j = mdd_objectScaleSimple(coll->mddObjs[i].mdd, useInterv, newMdd, newInterv);
      }
      if (j != 0)
      {
        usr.type = usr_mdd_dying; usr.data = (void*)(&((coll->mddObjs[i]).mdd));
        frames->broadcastUserEvent(usr);
        coll->mddObjs[i].flags = 0;
        (coll->mddObjs[i].mdd).destroy();
        coll->mddObjs[i].mdd = newMdd;
        res++;
	list->SetString(i, mddDescriptorString(memstr, i));
        selectedItems[i>>3] &= ~(1<<(i&7));
      }
    }
  }

  operationEpilogue(operation);
	    
  delete [] scale;

  lastSelected = updateSelection();

  return res;
}


int rviewResult::process(wxObject &obj, wxEvent &evt)
{
  int type = evt.GetEventType();

  if (&obj == (wxObject*)list)
  {
    if (type == wxEVENT_TYPE_LISTBOX_COMMAND)
    {
      //cout << "rviewResult::process Listbox command" << endl;
      lastSelected = updateSelection();
      return 1;
    }
    if (type == wxEVENT_TYPE_LISTBOX_DCLICK_COMMAND)
    {
      if ((lastSelected >= 0) && (lastSelected < coll->number))
      {
	// This check is necessary
	if (!list->Selected(lastSelected))
	{
	  list->SetSelection(lastSelected, TRUE);
	  if (selectedItems != NULL) selectedItems[lastSelected>>3] |= (1<<(lastSelected&7));
	}
        openViewer(lastSelected);
      }
      return 1;
    }
  }
  if (&obj == (wxObject*)choice)
  {
    if (type == wxEVENT_TYPE_CHOICE_COMMAND)
    {
      prefs->lastDisplay = choice->GetSelection();
	  prefs->markModified();
      return 1;
    }
  }
  if (&obj == (wxObject*)resampText)
  {
    if (type == wxEVENT_TYPE_TEXT_ENTER_COMMAND)
    {
      resampleSelection();
      return 1;
    }
  }
  if (&obj == (wxObject*)resampBut)
  {
    if (type == wxEVENT_TYPE_BUTTON_COMMAND)
    {
      resampleSelection();
      return 1;
    }
  }

  return 0;
}



int rviewResult::userEvent(const user_event &ue)
{
  if (ue.type == usr_viewer_closed)
  {
    mdd_frame *mf = (mdd_frame*)(ue.data);
    int i;

	//{FILE *fp=fopen("xxx", "a+"); fprintf(fp, "Received viewer closed %p --- %p, %d\n", mf->mdd.ptr(), coll->mddObjs[0].mdd.ptr(), mf->flags); fclose(fp);}
    for (i=0; i<coll->number; i++)
    {
      // must compare pointers, comparing r_Refs has strange effects on Win
      if (mf->mdd.ptr() == coll->mddObjs[i].mdd.ptr()) break;
    }
    if (i < coll->number)
    {
      coll->mddObjs[i].flags &= ~(mf->flags);
      return 1;
    }
  }
  else if (ue.type == usr_child_closed)
  {
    if (ue.data == (void*)typeManager) typeManager = NULL;
    return 1;
  }
  else if (ue.type == usr_typeman_convert)
  {
    convertSelectedItems();
    typeManager->Close(TRUE); typeManager = NULL;
    return 1;
  }
  else if (ue.type == usr_close_viewers)
  {
    Close(TRUE);
    return 1;
  }

  return 0;
}



void rviewResult::convertSelectedItems(void)
{
  int itemNo;
  user_event usr;
  char buffer[STRINGSIZE];
  ostrstream memstr(buffer, STRINGSIZE);

  operationPrologue();

  for (itemNo=0; itemNo < coll->number; itemNo++)
  {
    if ((list->Selected(itemNo)) && (!coll->mddObjs[itemNo].mdd.is_null()))
    {
      r_Ref<r_GMarray> newMdd;

      if (typeManager->convert(coll->mddObjs[itemNo].mdd, newMdd) == 0)
      {
	usr.type = usr_mdd_dying; usr.data = (void*)(&((coll->mddObjs[itemNo]).mdd));
	frames->broadcastUserEvent(usr);
        coll->mddObjs[itemNo].mdd.destroy();
        coll->mddObjs[itemNo].mdd = newMdd;
	list->SetString(itemNo, mddDescriptorString(memstr, itemNo));
      }
      else
      {
	newMdd.destroy();
      }
    }
  }

  operationEpilogue(lman->lookup("operationTypeProj"));

  lastSelected = updateSelection();
}



// Set up some variables and widgets in the frame.
void rviewResult::setupVariables(void)
{
  int x, y;
  char *displayModes[RVIEW_RESDISP_NUMBER];
  char *scaleModes[2];
  wxMenu *mbarMenus[2];
  char buffer[STRINGSIZE];

  coll = NULL; panel = NULL; list = NULL; collName = NULL; collType = NULL;
  group = NULL; mBar = NULL; typeManager = NULL;
  lastSelected = -1;
  selectedItems = NULL;

  CreateStatusLine(1);

  mbarMenus[0] = new wxMenu;
  mbarMenus[0]->Append(MENU_RSLT_ITEM_OPENALL, "");
  mbarMenus[0]->Append(MENU_RSLT_ITEM_THUMBALL, "");
  mbarMenus[0]->Append(MENU_RSLT_ITEM_CLOSE, "");

  mbarMenus[1] = new wxMenu;
  mbarMenus[1]->Append(MENU_RSLT_SLCT_SLCTALL, "");
  mbarMenus[1]->Append(MENU_RSLT_SLCT_CLEAR, "");
  mbarMenus[1]->Append(MENU_RSLT_SLCT_OPEN, "");
  mbarMenus[1]->Append(MENU_RSLT_SLCT_THUMB, "");
  mbarMenus[1]->Append(MENU_RSLT_SLCT_DELETE, "");
  mbarMenus[1]->Append(MENU_RSLT_SLCT_ENDIAN, "");
  mbarMenus[1]->Append(MENU_RSLT_SLCT_TYPEMAN, "");
  mbarMenus[1]->Append(MENU_RSLT_SLCT_INFO, "");

  mBar = new wxMenuBar;
  sprintf(buffer, "&%s", lman->lookup("menRsltItem"));
  mBar->Append(mbarMenus[0], buffer);
  sprintf(buffer, "&%s", lman->lookup("menRsltSlct"));
  mBar->Append(mbarMenus[1], buffer);

  GetClientSize(&x, &y);
  panel = new wxPanel((wxWindow*)this, 0, 0, x, y);
  x -= 2*result_border; y -= 2*result_border;

  // Create a group box surrounding the collection-items
  group = new wxGroupBox(panel, "", 0, 0, x, result_header, wxBORDER);
  x -= 2*result_border; y -= 2*result_border;
  // Create the message widget showing the collection name
  collName = new wxMessage(panel, "", 2*result_border, result_lheight + 2*result_border, x, result_lheight, 0, "message");
  // The same for the collection base type
  collType = new wxMessage(panel, "", 2*result_border, 2*result_lheight + 2*result_border, x, result_lheight, 0, "message");
  // The info string
  collInfo = new wxMessage(panel, "", 2*result_border, 3*result_lheight + 2*result_border, x, result_lheight, 0, "message");

  // And the choice item for the display modes.
  // In contrast to the menu stuff non-persistent objects are OK here.
  displayModes[0] = lman->lookup("dispModeImage");
  displayModes[1] = lman->lookup("dispModeVolume");
  displayModes[2] = lman->lookup("dispModeOrtho");
  displayModes[3] = lman->lookup("dispModeHeight");
  displayModes[4] = lman->lookup("dispModeChart");
  displayModes[5] = lman->lookup("dispModeTable");
  displayModes[6] = lman->lookup("dispModeSound");
  displayModes[7] = lman->lookup("dispModeString");
  choice = new rviewChoice(panel, RVIEW_RESDISP_NUMBER, displayModes, lman->lookup("dispModeLabel"));
  choice->SetSelection(prefs->lastDisplay);

  scaleModes[0] = lman->lookup("textResample");
  scaleModes[1] = lman->lookup("textScale");
  scaleMode = new rviewChoice(panel, 2, scaleModes);
  scaleMode->SetSelection(0);
  scaleMode->SetLabel("");

  sprintf(buffer, "%f", 1.0);
  resampText = new rviewText(panel, buffer);
  resampBut = new rviewButton(panel, lman->lookup("textOK"));

  choice->GetSize(&x, &y);
  cbfactor = x - result_cwidth;

  SetMenuBar(mBar);
}




void rviewResult::OnMenuCommand(int id)
{
  switch (id)
  {
    case MENU_RSLT_ITEM_OPENALL:
      {
	for (int i=0; i<coll->number; i++)
	{
	  openViewer(i);
	}
      }
      break;
    case MENU_RSLT_ITEM_THUMBALL:
      {
	int i;
	rviewThumb *thumb;

	thumb = new rviewThumb;
	for (i=0; i<coll->number; i++)
	{
	  thumb->addMDD(coll->mddObjs[i].mdd);
	}
	registerChild((rviewFrame*)thumb);
      }
      break;
    case MENU_RSLT_ITEM_CLOSE:
      {
        this->Close(TRUE);
      }
      break;
    case MENU_RSLT_SLCT_SLCTALL:
      {
	for (int i=0; i<coll->number; i++)
	{
	  if (!list->Selected(i))
	  {
	    list->SetSelection(i, TRUE);
	  }
	}
	if (selectedItems != NULL) memset(selectedItems, 0xff, (coll->number + 7) >> 3);
	configureGrey();
      }
      break;
    case MENU_RSLT_SLCT_CLEAR:
      {
	for (int i=0; i<coll->number; i++)
	{
	  if (list->Selected(i))
	  {
	    list->SetSelection(i, FALSE);
	  }
	}
	if (selectedItems != NULL) memset(selectedItems, 0, (coll->number + 7) >> 3);
	configureGrey();
      }
      break;
    case MENU_RSLT_SLCT_OPEN:
      {
	int i;

	for (i=0; i<coll->number; i++)
	{
	  if (list->Selected(i))
            openViewer(i);
	}
      }
      break;
    case MENU_RSLT_SLCT_THUMB:
      {
	int i;

	for (i=0; i<coll->number; i++)
	{
	  if (list->Selected(i)) break;
	}
	if (i < coll->number)
	{
	  rviewThumb *thumb;

	  thumb = new rviewThumb;
	  for (i=0; i<coll->number; i++)
	  {
	    if (list->Selected(i))
	      thumb->addMDD(coll->mddObjs[i].mdd);
	  }
	  registerChild((rviewFrame*)thumb);
	}
      }
      break;
    case MENU_RSLT_SLCT_DELETE:
      {
	int itemNo, j;
	user_event usr;

	do
	{
          for (itemNo=0; itemNo < coll->number; itemNo++)
            if (list->Selected(itemNo)) break;

	  if (itemNo >= coll->number) break;
	  list->Delete(itemNo);
	  // Notify all open display frames that a particular mdd object will die
	  usr.type = usr_mdd_dying; usr.data = (void*)(&((coll->mddObjs[itemNo]).mdd));
	  frames->broadcastUserEvent(usr);
	  if (!coll->mddObjs[itemNo].mdd.is_null())
	  {
	    coll->mddObjs[itemNo].mdd.destroy();
	  }
	  (coll->number)--;
	  for (j=itemNo; j<coll->number; j++)
	  {
	    coll->mddObjs[j] = coll->mddObjs[j+1];
	    // Don't forget to copy the selection too
	    selectedItems[j>>3] &= ~(1<<(j&7));
	    if ((selectedItems[(j+1)>>3] & (1<<((j+1)&7))) != 0) selectedItems[j>>3] |= (1<<(j&7));
	  }
	}
	while (1);
	lastSelected = updateSelection();
	configureGrey();
      }
      break;
    case MENU_RSLT_SLCT_ENDIAN:
      {
	int itemNo;
	user_event ue;

	operationPrologue();

	ue.type = usr_mdd_dying;
	for (itemNo = 0; itemNo < coll->number; itemNo++)
	{
	  if ((list->Selected(itemNo)) && (!coll->mddObjs[itemNo].mdd.is_null()))
	  {
	    r_Minterval useInterv;

	    ue.data = (void*)(&((coll->mddObjs[itemNo]).mdd));
	    frames->broadcastUserEvent(ue);	// close all open viewers
	    useInterv = coll->mddObjs[itemNo].mdd->spatial_domain();
	    mdd_objectChangeEndianness(coll->mddObjs[itemNo].mdd, useInterv);
	  }
	}
	operationEpilogue(lman->lookup("operationEndian"));
      }
      break;
    case MENU_RSLT_SLCT_TYPEMAN:
      if (typeManager == NULL)
      {
	int itemNo;
	const r_Type *sampleType = NULL;

	for (itemNo = 0; itemNo < coll->number; itemNo++)
	{
	  if ((list->Selected(itemNo)) && (!coll->mddObjs[itemNo].mdd.is_null()))
	  {
	    sampleType = coll->mddObjs[itemNo].mdd->get_base_type_schema();
	    break;
	  }
	}
	/*try {
	  sampleType = r_Type::get_any_type("struct { struct { float u, float v, float w }, float p, float te, float ed, float den, float vis }");
	} catch (r_Error &err) {
	  cerr << err.what() << endl;
	}*/
	if (sampleType != NULL)
	{
	  if (typeManager == NULL)
	    typeManager = new rviewTypeMan(this, sampleType);
	}
      }
      break;
    case MENU_RSLT_SLCT_INFO: break;
    default: break;
  }
}



void rviewResult::configureGrey(void)
{
  int i;

  mBar->Enable(MENU_RSLT_ITEM_OPENALL, (coll->number > 0));
  mBar->Enable(MENU_RSLT_ITEM_THUMBALL, (coll->number> 0));

  for (i=0; i<coll->number; i++)
  {
    if (list->Selected(i)) break;
  }
  bool enable = (i < coll->number);

  mBar->Enable(MENU_RSLT_SLCT_CLEAR, enable);
  mBar->Enable(MENU_RSLT_SLCT_OPEN, enable);
  mBar->Enable(MENU_RSLT_SLCT_THUMB, enable);
  mBar->Enable(MENU_RSLT_SLCT_DELETE, enable);
  mBar->Enable(MENU_RSLT_SLCT_ENDIAN, enable);
  mBar->Enable(MENU_RSLT_SLCT_TYPEMAN, enable);
  mBar->Enable(MENU_RSLT_SLCT_INFO, enable);
}





/*
 *  rView about window
 */

const int rviewAbout::about_width = 300;
const int rviewAbout::about_height = 150;
const int rviewAbout::about_border = 8;
const int rviewAbout::about_pheight = 50;
const int rviewAbout::about_bwidth = 80;
const int rviewAbout::about_bheight = 30;
const int rviewAbout::about_mheight = 16;

rviewAbout::rviewAbout(void) : rviewFrame(NULL, "", -1, -1, about_width, about_height)
{
  labels = NULL; numlines = 0;
  panel = new wxPanel((wxWindow*)this, 0, 0, about_width, about_height);
  okBut = new rviewButton(panel);

  label();

  OnSize(about_width, about_height);
}


rviewAbout::~rviewAbout(void)
{
  // the messages themselves will be sorted out by the panel destructor.
  if (labels != NULL) delete [] labels;
}


const char *rviewAbout::getFrameName(void) const
{
  return "rviewAbout";
}

rviewFrameType rviewAbout::getFrameType(void) const
{
  return rviewFrameTypeAbout;
}


void rviewAbout::deleteLabels(void)
{
  if (labels != NULL)
  {
    int i;

    for (i=0; i<numlines; i++) delete labels[i];
    delete [] labels; labels = NULL; numlines = 0;
  }
}


void rviewAbout::label(void)
{
  int i, number, x, y;

  SetTitle(lman->lookup("titleAbout"));
  okBut->SetLabel(lman->lookup("textOK"));

  deleteLabels();

  GetClientSize(&x, &y);
  y = about_border;
  number = atoi(lman->lookup("rviewAboutLineNum"));
  if (number >= 1)
  {
    char lineName[64];

    numlines = number;
    labels = new wxMessage *[numlines]; x -= 2*about_border;
    for (i=0; i<number; i++)
    {
      sprintf(lineName, "rviewAboutLine%d", i);
      labels[i] = new wxMessage(panel, lman->lookup(lineName), about_border, y, x, about_mheight, 0, "message");
      y += about_mheight;
    }
  }
  SetSize(-1, -1, x, y + about_pheight + rview_window_extra_height);
}


int rviewAbout::process(wxObject &obj, wxEvent &evt)
{
  if ((&obj == (wxObject*)okBut) && (evt.GetEventType() == wxEVENT_TYPE_BUTTON_COMMAND))
  {
    Show(FALSE); return 1;
  }
  return 0;
}


void rviewAbout::OnSize(int w, int h)
{
  int x, y;

  GetClientSize(&x, &y);

  panel->SetSize(0, 0, x, y);
  x -= 2*about_border; y = about_border;
  if (panel != NULL)
  {
    for (int i=0; i<numlines; i++)
    {
      labels[i]->SetSize(about_border, y, x, about_mheight);
      y += about_mheight;
    }
  }
  x -= about_bwidth; y += (about_pheight - about_bheight)/2;
  okBut->SetSize(x/2, y, about_bwidth, about_bheight);
}





/*
 *  rviewStringSet window
 */

const int rviewStringSet::strset_width = 300;
const int rviewStringSet::strset_height = 250;
const int rviewStringSet::strset_border = 8;
const int rviewStringSet::strset_reserve = 50;
const int rviewStringSet::strset_bwidth = 70;
const int rviewStringSet::strset_bheight = 40;
const int rviewStringSet::strset_mheight = 20;

rviewStringSet::rviewStringSet(collection_desc *desc) : rviewFrame(NULL, "", -1, -1, strset_width, strset_height)
{
  int w, h;
  char buffer[STRINGSIZE];

  panel = new wxPanel((wxWindow*)this, 0, 0, strset_width, strset_height);
  list = new wxListBox(panel, (wxFunction)rviewEventHandler, "", wxSINGLE, 0, 0, strset_width, strset_height, desc->number, desc->strObjs, wxALWAYS_SB);
  dismiss = new rviewButton(panel);

  sprintf(buffer, "%s: %s", lman->lookup("textCollName"), (desc->collName == NULL) ? "" : desc->collName);
  collName = new wxMessage(panel, buffer, 0, 0, 10, 10, 0, "message");
  sprintf(buffer, "%s: %s", lman->lookup("textCollType"), (desc->collType == NULL) ? "" : desc->collType);
  collType = new wxMessage(panel, buffer, 0, 0, 10, 10, 0, "message");
  char* tmpChar1 = "message";
  char* tmpChar2 = "";
  collInfo = new wxMessage(panel, (desc->collInfo == NULL) ? tmpChar2 : desc->collInfo, 0, 0, 10, 10, 0, tmpChar1);

  GetClientSize(&w, &h);

  label();

  OnSize(w, h);

  Show(TRUE);
}


rviewStringSet::~rviewStringSet(void)
{
}


const char *rviewStringSet::getFrameName(void) const
{
  return "rviewStringSet";
}

rviewFrameType rviewStringSet::getFrameType(void) const
{
  return rviewFrameTypeStrSet;
}


void rviewStringSet::label(void)
{
  SetTitle(lman->lookup("titleStringSet"));
  list->SetLabel(lman->lookup("strSetList"));
  dismiss->SetLabel(lman->lookup("textClose"));
}


void rviewStringSet::OnSize(int w, int h)
{
  int x, y;
  int head;

  GetClientSize(&x, &y);
  panel->SetSize(0, 0, x, y);
  head = 3*(strset_mheight + strset_border);
  x -= 2*strset_border; y -= 2*strset_border;
  collName->SetSize(strset_border, strset_border, x, strset_mheight);
  collType->SetSize(strset_border, strset_mheight + 2*strset_border, x, strset_mheight);
  collInfo->SetSize(strset_border, 2*strset_mheight + 3*strset_border, x, strset_mheight);

  list->SetSize(strset_border, strset_border + head, x, y - head - strset_reserve);
  dismiss->SetSize((x - strset_bwidth) / 2, y + 2*strset_border - (strset_reserve + strset_bheight) / 2, strset_bwidth, strset_bheight);
}


int rviewStringSet::process(wxObject &obj, wxEvent &evt)
{
  if (&obj == (wxObject*)dismiss)
  {
    this->Close(TRUE);
    return 1;
  }
  return 0;
}


int rviewStringSet::getNumItems(void)
{
  return list->Number();
}


void rviewStringSet::addItem(const char *string)
{
  list->Append((char*)string);
}


char *rviewStringSet::getItem(int number)
{
  return list->GetString(number);
}


#ifdef EARLY_TEMPLATE
#undef __EXECUTABLE__
#endif

#endif	// !defined(EARLY_TEMPLATE) || !defined(__EXECUTABLE__)



#if (!defined(EARLY_TEMPLATE) || defined(__EXECUTABLE__))

/*
 *  Templates
 */

// For placement new (DynamicStack template)
#include <new>

/*
 *  Use malloc/free, placement new and explicit calls to destructors.
 *  Use placement new when initializing on the stack because that's
 *  raw memory, use assignment when initializing parameters
 */
template<class T>
DynamicStack<T>::DynamicStack(unsigned int gran)
{
  number = 0; max = 0;
  if ((stack = (T*)malloc(gran * sizeof(T))) != NULL)
  {
    granularity = gran;
    max = granularity;
    memset(stack, 0, max * sizeof(T));
  }
}


template<class T>
DynamicStack<T>::DynamicStack(const DynamicStack<T> &src)
{
  number = 0; max = 0;
  if ((stack = (T*)malloc(src.max * sizeof(T))) != NULL)
  {
    granularity = src.granularity;
    max = src.max;
    memset(stack, 0, max*sizeof(T));
    number = src.number;

    unsigned int i;

    // use loop for class safety
    for (i=0; i<number; i++)
      new(stack + i) T(src.stack[i]);	// placement new
  }
}


template<class T>
DynamicStack<T>::~DynamicStack(void)
{
  unsigned int i;

  for (i=0; i<number; i++)
    stack[i].~T();	// direct destructor call

  if (stack != NULL)
    free(stack);
}


template<class T>
int DynamicStack<T>::push(const T &item)
{
  if (ensureFree() != 0) return -1;
  new(stack + number++) T(item);	// placement new
  return 0;
}


template<class T>
int DynamicStack<T>::pop(T &item)
{
  if (number == 0) return -1;
  item = stack[--number];	// assignment
  stack[number].~T();		// direct destructor call
  return 0;
}


template<class T>
int DynamicStack<T>::peek(T &item) const
{
  if (number == 0) return -1;
  item = stack[number-1];	// assignment
  return 0;
}


template<class T>
unsigned int DynamicStack<T>::getNumber(void) const
{
  return number;
}


template<class T>
int DynamicStack<T>::ensureFree(void)
{
  if (number >= max)
  {
    if ((stack = (T*)realloc(stack, (max + granularity) * sizeof(T))) == NULL)
    {
      max = 0; number = 0; return -1;
    }
    memset(stack + max, 0, granularity * sizeof(T));
    max += granularity;
  }
  return 0;
}

#endif