This file is indexed.

/usr/share/pyshared/PyMca/McaAdvancedFit.py is in pymca 4.5.0-4.

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

The actual contents of the file can be viewed below.

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

__revision__ = "$Revision: 1.65 $"
__author__="V.A. Sole - ESRF BLISS Group"
import sys
import PyMcaQt as qt
if hasattr(qt, "QString"):
    QString = qt.QString
else:
    QString = str

QTVERSION = qt.qVersion()
import traceback

try:
    import PyMcaMatplotlibSave
    import QPyMcaMatplotlibSave1D
    MATPLOTLIB = True
    #force understanding of utf-8 encoding
    #otherways it cannot generate svg output
    try:
        import encodings.utf_8
    except:
        #not a big problem
        pass
except:
    MATPLOTLIB = False

import ClassMcaTheory
import FitParam
import McaAdvancedTable
import QtMcaAdvancedFitReport
import ConcentrationsWidget
import ConcentrationsTool
import types
import copy
import os
import QtBlissGraph
from PyMca_Icons import IconDict
import time
import McaCalWidget
import PeakIdentifier
import ElementsInfo
Elements = ElementsInfo.Elements
#import McaROIWidget
import numpy.oldnumeric as Numeric
import PyMcaPrintPreview
import PyMcaDirs
USE_BOLD_FONT = True
DEBUG = 0
if DEBUG:
    print("############################################")
    print("#    McaAdvancedFit is in DEBUG mode %s     #" % DEBUG)
    print("############################################")

class McaAdvancedFit(qt.QWidget):
    """
    This class inherits QWidget.

    It provides all the functionality required to perform an interactive fit
    and to generate a configuration file.

    It is the simplest way to embed PyMca's fitting functionality into other
    PyQt application.

    It can be used from the interactive prompt of ipython provided ipython is
    started with the -q4thread flag.

    **Usage**

    >>> from PyMca import McaAdvancedFit
    >>> w = McaAdvancedFit.McaAdvancedFit()
    >>> w.setData(x=x, y=y) # x is your channel array and y the counts array
    >>> w.show()
    
    """
    def __init__(self, parent=None, name="PyMca - McaAdvancedFit",fl=0,
                 sections=None, top=True, margin=11, spacing=6):
                #fl=qt.Qt.WDestructiveClose):
        if QTVERSION < '4.0.0':
            qt.QWidget.__init__(self, parent, name,fl)
            self.setCaption(name)
            self.setIcon(qt.QPixmap(IconDict['gioconda16']))
        else:
            qt.QWidget.__init__(self, parent)
            self.setWindowTitle(name)
            self.setWindowIcon(qt.QIcon(qt.QPixmap(IconDict['gioconda16'])))
        self.lastInputDir = None
        self.configDialog = None
        self.matplotlibDialog = None
        self.mainLayout = qt.QVBoxLayout(self)
        self.mainLayout.setMargin(margin)
        self.mainLayout.setSpacing(0)
        if sections is None:sections=["TABLE"]
        self.headerLabel = qt.QLabel(self)
        self.mainLayout.addWidget(self.headerLabel)

        self.headerLabel.setAlignment(qt.Qt.AlignHCenter)
        font = self.font()
        font.setBold(USE_BOLD_FONT)
        self.headerLabel.setFont(font)
        self.setHeader('Fit of XXXXXXXXXX from Channel XXXXX to XXXX')
        self.top = Top(self)
        self.mainLayout.addWidget(self.top)
        self.sthread = None
        self.elementsInfo = None
        self.identifier   = None
        if False and len(sections) == 1:
            w = self
            self.mcatable  = McaAdvancedTable.McaTable(w)
            self.concentrationsWidget = None
        else:
            self.mainTab = qt.QTabWidget(self)
            self.mainLayout.addWidget(self.mainTab)
            if  QTVERSION < '3.0.0':
                self.mainTab.label = self.__mainTabPatch
                self.mainTab.tabText = self.mainTab.label
                self.mainTab.currentIndex = self.mainTab.currentPageIndex
                self.mainTab.setCurrentIndex = self.mainTab.setCurrentPage
                self.mainTabLabels = ["GRAPH", "TABLE", "CONCENTRATIONS", "DIAGNOSTICS"]
            #graph
            if QTVERSION < '4.0.0':
                self.mainTab.tabText = self.mainTab.label
                self.mainTab.currentIndex = self.mainTab.currentPageIndex
                self.mainTab.setCurrentIndex = self.mainTab.setCurrentPage
                self.tabGraph  = qt.QWidget(self.mainTab,"tabGraph")
                tabGraphLayout = qt.QVBoxLayout(self.tabGraph,margin,
                                                spacing,"tabGraphLayout")
            else:
                self.tabGraph  = qt.QWidget()
                tabGraphLayout = qt.QVBoxLayout(self.tabGraph)
                tabGraphLayout.setMargin(margin)
                tabGraphLayout.setSpacing(spacing)
            #self.graphToolbar  = qt.QHBox(self.tabGraph)
            self.graphWindow = McaGraphWindow(self.tabGraph)
            tabGraphLayout.addWidget(self.graphWindow)
            self.graph = self.graphWindow.graph
            self.graph.xlabel('Channel')
            self.graph.ylabel('Counts')
            self.graph.canvas().setMouseTracking(1)
            self.graph.setCanvasBackground(qt.Qt.white)
            if QTVERSION < '4.0.0':
                self.mainTab.insertTab(self.tabGraph,"GRAPH")
                qt.QObject.connect(self.graphWindow,
                                   qt.PYSIGNAL('McaGraphSignal'),
                                   self._mcaGraphSignalSlot)
            else:
                self.mainTab.addTab(self.tabGraph,"GRAPH")
                qt.QObject.connect(self.graphWindow,
                                   qt.SIGNAL('McaGraphSignal'),
                                   self._mcaGraphSignalSlot)
            #table
            if QTVERSION < '4.0.0':
                self.tabMca  = qt.QWidget(self.mainTab)
            else:
                self.tabMca  = qt.QWidget()
            tabMcaLayout = qt.QVBoxLayout(self.tabMca)
            tabMcaLayout.setMargin(margin)
            tabMcaLayout.setSpacing(spacing)
            w = self.tabMca
            line = Line(w, info="TABLE")
            tabMcaLayout.addWidget(line)

            if QTVERSION < '4.0.0':
                qt.QToolTip.add(line,"DoubleClick toggles floating window mode")
            else:
                line.setToolTip("DoubleClick toggles floating window mode")

            if QTVERSION < '4.0.0':
                self.mcatable  = McaAdvancedTable.McaTable(w)
                tabMcaLayout.addWidget(self.mcatable)
                self.mainTab.insertTab(w,"TABLE")
                self.connect(line,qt.PYSIGNAL("LineDoubleClickEvent"),
                                self._tabReparent)
                self.connect(self.mcatable,qt.PYSIGNAL("closed"),
                                self._mcatableClose)
            else:
                self.mcatable  = McaAdvancedTable.McaTable(w)
                tabMcaLayout.addWidget(self.mcatable)
                self.mainTab.addTab(w,"TABLE")
                self.connect(line,qt.SIGNAL("LineDoubleClickEvent"),
                                self._tabReparent)
                self.connect(self.mcatable,qt.SIGNAL("closed"),
                                self._mcatableClose)

            #concentrations
            if QTVERSION < '4.0.0':
                self.tabConcentrations  = qt.QWidget(self.mainTab,"tabConcentrations")
            else:
                self.tabConcentrations  = qt.QWidget()
            tabConcentrationsLayout = qt.QVBoxLayout(self.tabConcentrations)
            tabConcentrationsLayout.setMargin(margin)
            tabConcentrationsLayout.setSpacing(0)
            line2 = Line(self.tabConcentrations, info="CONCENTRATIONS")
            self.concentrationsWidget = ConcentrationsWidget.Concentrations(self.tabConcentrations)
            tabConcentrationsLayout.addWidget(line2)
            tabConcentrationsLayout.addWidget(self.concentrationsWidget)


            if QTVERSION < '4.0.0':
                self.mainTab.insertTab(self.tabConcentrations,"CONCENTRATIONS")
                qt.QToolTip.add(line2,"DoubleClick toggles floating window mode")
                self.connect(self.concentrationsWidget,
                            qt.PYSIGNAL("ConcentrationsSignal"),
                            self.__configureFromConcentrations)
                self.connect(line2,qt.PYSIGNAL("LineDoubleClickEvent"),
                                self._tabReparent)
                self.connect(self.concentrationsWidget,qt.PYSIGNAL("closed"),
                                self._concentrationsWidgetClose)
            else:
                self.mainTab.addTab(self.tabConcentrations,"CONCENTRATIONS")
                line2.setToolTip("DoubleClick toggles floating window mode")
                self.connect(self.concentrationsWidget,
                            qt.SIGNAL("ConcentrationsSignal"),
                            self.__configureFromConcentrations)
                self.connect(line2,qt.SIGNAL("LineDoubleClickEvent"),
                                self._tabReparent)
                self.connect(self.concentrationsWidget,qt.SIGNAL("closed"),
                                self._concentrationsWidgetClose)

            #diagnostics
            if QTVERSION < '4.0.0':
                self.tabDiagnostics  = qt.QWidget(self.mainTab)
            else:
                self.tabDiagnostics  = qt.QWidget()
            tabDiagnosticsLayout = qt.QVBoxLayout(self.tabDiagnostics)
            tabDiagnosticsLayout.setMargin(margin)
            tabDiagnosticsLayout.setSpacing(spacing)
            w = self.tabDiagnostics
            if  QTVERSION < '3.0.0':
                self.diagnosticsWidget = qt.QTextView(w)
            else:
                self.diagnosticsWidget = qt.QTextEdit(w)
                self.diagnosticsWidget.setReadOnly(1)

            tabDiagnosticsLayout.addWidget(self.diagnosticsWidget)
            if QTVERSION < '4.0.0':
                self.mainTab.insertTab(w,"DIAGNOSTICS")
                self.connect(self.mainTab, qt.SIGNAL('currentChanged(QWidget *)'),
                             self._tabChanged)
            else:
                self.mainTab.addTab(w,"DIAGNOSTICS")
                self.connect(self.mainTab, qt.SIGNAL('currentChanged(int)'),
                             self._tabChanged)


        self._logY       = False
        self._energyAxis = False
        if QTVERSION < '4.0.0' :
            self.__printmenu = qt.QPopupMenu()
            self.__printmenu.insertItem(QString("Calibrate"),     self._calibrate)
            self.__printmenu.insertItem(QString("Identify Peaks"),self.__peakIdentifier)
            self.__printmenu.insertItem(QString("Elements Info"), self.__elementsInfo)
            #self.__printmenu.insertItem(QString("Concentrations"),self.concentrations)
            #self.__printmenu.insertItem(QString("Spectrum from Matrix"),self.matrixSpectrum)
            #self.__printmenu.insertItem(QString("Print Table"),self.printps)
            #self.__printmenu.insertItem(QString("HTML Report"),self.htmlReport)
        else:
            self.__printmenu = qt.QMenu()
            self.__printmenu.addAction(QString("Calibrate"),     self._calibrate)
            self.__printmenu.addAction(QString("Identify Peaks"),self.__peakIdentifier)
            self.__printmenu.addAction(QString("Elements Info"), self.__elementsInfo)
        self.outdir      = None
        self.configDir   = None
        self.__lastreport= None
        self.browser     = None
        self.info        = {}
        self.__fitdone   = 0
        self._concentrationsDict = None
        #self.graph.hide()
        #self.guiconfig = FitParam.Fitparam()
        """
        self.specfitGUI.guiconfig.MCACheckBox.setEnabled(0)
        palette = self.specfitGUI.guiconfig.MCACheckBox.palette()
        palette.setDisabled(palette.active())
        """
        ##############
        hbox=qt.QWidget(self)
        self.bottom = hbox
        hboxLayout = qt.QHBoxLayout(hbox)
        hboxLayout.setMargin(0)
        hboxLayout.setSpacing(4)
        if not top:
            self.configureButton = qt.QPushButton(hbox)
            self.configureButton.setText("Configure")
            self.toolsButton = qt.QPushButton(hbox)
            self.toolsButton.setText("Tools")
            hboxLayout.addWidget(self.configureButton)
            hboxLayout.addWidget(self.toolsButton)
        hboxLayout.addWidget(HorizontalSpacer(hbox))
        self.fitButton = qt.QPushButton(hbox)
        hboxLayout.addWidget(self.fitButton)
        #font = self.fitButton.font()
        #font.setBold(True)
        #self.fitButton.setFont(font)
        self.fitButton.setText("Fit Again!")
        self.printButton = qt.QPushButton(hbox)
        hboxLayout.addWidget(self.printButton)
        self.printButton.setText("Print")
        self.htmlReportButton = qt.QPushButton(hbox)
        hboxLayout.addWidget(self.htmlReportButton)
        self.htmlReportButton.setText("HTML Report")
        self.matrixSpectrumButton = qt.QPushButton(hbox)
        hboxLayout.addWidget(self.matrixSpectrumButton)
        self.matrixSpectrumButton.setText("Matrix Spectrum")
        self.peaksSpectrumButton = qt.QPushButton(hbox)
        hboxLayout.addWidget(self.peaksSpectrumButton)
        self.peaksSpectrumButton.setText("Peaks Spectrum")
        if QTVERSION < '4.0.0':
            self.matrixSpectrumButton.setToggleButton(1)
            self.peaksSpectrumButton.setToggleButton(1)
            self.matrixSpectrumButton.isChecked = self.matrixSpectrumButton.isOn
            self.peaksSpectrumButton.isChecked = self.peaksSpectrumButton.isOn
        else:
            self.matrixSpectrumButton.setCheckable(1)
            self.peaksSpectrumButton.setCheckable(1)
        hboxLayout.addWidget(HorizontalSpacer(hbox))
        self.dismissButton = qt.QPushButton(hbox)
        hboxLayout.addWidget(self.dismissButton)
        self.dismissButton.setText("Dismiss")
        hboxLayout.addWidget(HorizontalSpacer(hbox))

        self.mainLayout.addWidget(hbox)
        if QTVERSION < '4.0.0':
            qt.QToolTip.add(self.printButton,'Print Active Tab')
            qt.QToolTip.add(self.htmlReportButton,'Generate Browser Compatible Output\nin Chosen Directory')
            qt.QToolTip.add(self.matrixSpectrumButton,'Toggle Matrix Spectrum Calculation On/Off')
            qt.QToolTip.add(self.peaksSpectrumButton,'Toggle Individual Peaks Spectrum Calculation On/Off')
        else:
            self.printButton.setToolTip('Print Active Tab')
            self.htmlReportButton.setToolTip('Generate Browser Compatible Output\nin Chosen Directory')
            self.matrixSpectrumButton.setToolTip('Toggle Matrix Spectrum Calculation On/Off')
            self.peaksSpectrumButton.setToolTip('Toggle Individual Peaks Spectrum Calculation On/Off')

        self.mcafit   = ClassMcaTheory.McaTheory()

        self.connect(self.fitButton,                qt.SIGNAL("clicked()"),self.fit)
        self.connect(self.printButton,              qt.SIGNAL("clicked()"),self.printActiveTab)
        self.connect(self.htmlReportButton,         qt.SIGNAL("clicked()"),self.htmlReport)
        self.connect(self.matrixSpectrumButton,     qt.SIGNAL("clicked()"),self.__toggleMatrixSpectrum)
        self.connect(self.peaksSpectrumButton,      qt.SIGNAL("clicked()"),self.__togglePeaksSpectrum)
        self.connect(self.dismissButton,            qt.SIGNAL("clicked()"),self.dismiss)
        self.connect(self.top.configureButton,qt.SIGNAL("clicked()") ,   self.__configure)
        self.connect(self.top.printButton,qt.SIGNAL("clicked()") ,self.__printps)
        if top:
            if QTVERSION < '4.0.0':
                self.connect(self.top,qt.PYSIGNAL("TopSignal"), self.__updatefromtop)
            else:
                self.connect(self.top,qt.SIGNAL("TopSignal"), self.__updatefromtop)
        else:
            self.top.hide()
            self.connect(self.configureButton,qt.SIGNAL("clicked()") ,   self.__configure)
            self.connect(self.toolsButton,qt.SIGNAL("clicked()") ,self.__printps)
        self._updateTop()

    def __mainTabPatch(self, index):
        return self.mainTabLabels[index]

    def _fitdone(self):
        if self.__fitdone:
            return True
        else:
            return False

    def _submitThread(self, function, parameters, message="Please wait",
                    expandparametersdict=None):
        if expandparametersdict is None: expandparametersdict= False
        sthread = SimpleThread()
        sthread._expandParametersDict=expandparametersdict
        sthread._function = function
        sthread._kw       = parameters
        #try:
        sthread.start()
        #except:
        #    raise "ThreadError",sys.exc_info()
        if QTVERSION < '3.0.0':
            msg = qt.QDialog(self, "Please Wait", False,qt.Qt.WStyle_NoBorder)
        elif QTVERSION < '4.0.0':
            msg = qt.QDialog(self, "Please Wait",
                             1,
                             qt.Qt.WStyle_NoBorder)
        else:
            msg = qt.QDialog(self, qt.Qt.FramelessWindowHint)
            msg.setModal(0)
            msg.setWindowTitle("Please Wait")
        layout = qt.QHBoxLayout(msg)
        l1 = qt.QLabel(msg)
        layout.addWidget(l1)
        l1.setFixedWidth(l1.fontMetrics().width('##'))
        l2 = qt.QLabel(msg)
        layout.addWidget(l2)
        l2.setText("%s" % message)
        l3 = qt.QLabel(msg)
        layout.addWidget(l3)
        l3.setFixedWidth(l3.fontMetrics().width('##'))
        msg.show()
        qt.qApp.processEvents()
        t0 = time.time()
        i = 0
        ticks = ['-','\\', "|", "/","-","\\",'|','/']
        if QTVERSION < '4.0.0':
            while (sthread.running()):
                i = (i+1) % 8
                l1.setText(ticks[i])
                l3.setText(" "+ticks[i])
                qt.qApp.processEvents()
                time.sleep(1)
            msg.close(True)
        else:
            while (sthread.isRunning()):
                i = (i+1) % 8
                l1.setText(ticks[i])
                l3.setText(" "+ticks[i])
                qt.qApp.processEvents()
                time.sleep(1)
            msg.close()
        result = sthread._result
        del sthread
        if QTVERSION < '4.0.0':
            self.raiseW()
        else:
            self.raise_()
        return result

    def refreshWidgets(self):
        """
        This method just forces the graphical widgets to get updated.
        It should be called if somehow you have modified the fit and/
        or concentrations parameters by other means than the graphical
        interface.
        """
        self.__configure(justupdate=True)

    def configure(self, ddict=None):
        """
        This methods configures the fitting parameters and updates the
        graphical interface.

        It returns the current configuration.
        """
        if ddict is None:
            return self.mcafit.configure(ddict)

        #configure and get the new configuration
        newConfig = self.mcafit.configure(ddict)

        #refresh the interface
        self.refreshWidgets()

        #return the current configuration
        return newConfig

    def __configure(self, justupdate=False):
        config = {}
        config.update(self.mcafit.config)
        #config['fit']['use_limit'] = 1
        if not justupdate:
            if self.configDialog is None:
                if self.__fitdone:
                    dialog = FitParam.FitParamDialog(modal=1,
                                                     fl=0,
                                                     initdir=self.configDir,
                                                     fitresult=self.dict['result'])
                else:
                    dialog = FitParam.FitParamDialog(modal=1,
                                                     fl=0,
                                                     initdir=self.configDir,
                                                     fitresult=None)
                if QTVERSION < '4.0.0':
                    self.connect(dialog.fitparam.peakTable,
                                 qt.PYSIGNAL("FitPeakSelect"),
                                 self.__elementclicked)
                else:
                    self.connect(dialog.fitparam.peakTable,
                                 qt.SIGNAL("FitPeakSelect"),
                                 self.__elementclicked)
                self.configDialog = dialog
            else:
                dialog = self.configDialog
                if self.__fitdone: dialog.setFitResult(self.dict['result'])
                else:dialog.setFitResult(None)
            dialog.setParameters(config)
            dialog.setData(self.mcafit.xdata * 1.0,
                           self.mcafit.ydata * 1.0)

            
            #dialog.fitparam.regionCheck.setDisabled(True)
            #dialog.fitparam.minSpin.setDisabled(True)
            #dialog.fitparam.maxSpin.setDisabled(True)
            if QTVERSION < '4.0.0':
                ret = dialog.exec_loop()
            else:
                ret = dialog.exec_()
            if dialog.initDir is not None: self.configDir = 1 * dialog.initDir
            else: self.configDir = None
            if ret != qt.QDialog.Accepted:
                dialog.close()
                #del dialog
                return
            try:
                #this may crash in qt 2.3.0
                npar = dialog.getParameters()
            except:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                if QTVERSION < '4.0.0':
                    msg.setText("%s" % sys.exc_info()[1])
                    msg.exec_loop()
                else:
                    msg.setText("Error occured getting parameters:")
                    msg.setInformativeText(str(sys.exc_info()[1]))
                    msg.setDetailedText(traceback.format_exc())
                    msg.exec_()
                return
            config.update(npar)
            dialog.close()
            #del dialog

        self.graph.removeMarkers()
        self.graph.replot()
        self.__fitdone = False
        self._concentrationsDict = None
        if self.concentrationsWidget is not None:
            self.concentrationsWidget.concentrationsTable.setRowCount(0)
        if self.mcatable is not None:
            self.mcatable.setRowCount(0)

        #make sure newly or redefined materials are added to the
        #materials in the fit configuration
        for material in Elements.Material.keys():
            self.mcafit.config['materials'][material] =copy.deepcopy(Elements.Material[material])

        if DEBUG:
            self.mcafit.configure(config)
        elif (QTVERSION < '3.0.0'):
            try:
                self.mcafit.configure(config)
            except:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("%s" % sys.exc_info()[1])
                msg.exec_loop()
        else:
            try:
                threadResult=self._submitThread(self.mcafit.configure, config,
                                 "Configuring, please wait")
                if type(threadResult) == type((1,)):
                    if len(threadResult):
                        if threadResult[0] == "Exception":
                            raise Exception(threadResult[1], threadResult[2])
            except:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                if QTVERSION < '4.0.0':
                    msg.setText("%s" % sys.exc_info()[1])
                    msg.exec_loop()
                else:
                    msg.setWindowTitle("Configuration error")
                    msg.setText("Error configuring fit:")
                    msg.setInformativeText(str(sys.exc_info()[1]))
                    msg.setDetailedText(traceback.format_exc())
                    msg.exec_()
                return

        #update graph
        delcurves = []
        for key in self.graph.curves.keys():
            if key not in ["Data"]:
                delcurves.append(key)
        for key in delcurves:
            self.graph.delcurve(key)

        if not justupdate:
            self.plot()

        self._updateTop()
        if self.concentrationsWidget is not None:
            try:
                qt.qApp.processEvents()
                self.concentrationsWidget.setParameters(config['concentrations'], signal=False)
            except:
                if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "CONCENTRATIONS":
                    self.mainTab.setCurrentIndex(0)

    def __configureFromConcentrations(self,ddict):
        config = self.concentrationsWidget.getParameters()
        self.mcafit.config['concentrations'].update(config)
        if ddict['event'] == 'updated':
            if 'concentrations' in ddict:
                self._concentrationsDict = ddict['concentrations']

    def __elementclicked(self,ddict):
        ddict['event'] = 'McaAdvancedFitElementClicked'
        self.__showElementMarker(ddict)
        self.__anasignal(ddict)

    def __showElementMarker(self, dict):
        self.graph.removeMarkers()
        ele = dict['current']
        items = []
        if not (ele in dict):
            self.graph.replot()
            return
        for rays in dict[ele]:
            for transition in Elements.Element[ele][rays +" xrays"]:
                items.append([transition,
                              Elements.Element[ele][transition]['energy'],
                              Elements.Element[ele][transition]['rate']])

        config = self.mcafit.configure()
        xdata  = self.mcafit.xdata * 1.0
        xmin = xdata[0]
        xmax = xdata[-1]
        ymin,ymax = self.graph.getY1AxisLimits()
        calib = [config['detector'] ['zero'], config['detector'] ['gain']]
        for transition,energy,rate in items:
            marker = ""
            x = (energy - calib[0])/calib[1]
            if (x < xmin) or (x > xmax):continue
            if not self._energyAxis:
                if abs(calib[1]) > 0.0000001:
                    marker=self.graph.insertX1Marker(x,
                                                     ymax*rate,
                                                     label=transition)
            else:
                marker=self.graph.insertX1Marker(energy,
                                                 ymax*rate,
                                                 label=transition)
            if marker is not "":
                self.graph.setmarkercolor(marker,'orange')
        self.graph.replot()

    def _updateTop(self):
        config = {}
        if 0:
            config.update(self.mcafit.config['fit'])
        else:
            config['stripflag']    = self.mcafit.config['fit'].get('stripflag',0)
            config['fitfunction'] = self.mcafit.config['fit'].get('fitfunction',0)
            config['hypermetflag'] = self.mcafit.config['fit'].get('hypermetflag',1)
            config['sumflag']      = self.mcafit.config['fit'].get('sumflag',0)
            config['escapeflag']   = self.mcafit.config['fit'].get('escapeflag',0)
            config['continuum']    = self.mcafit.config['fit'].get('continuum',0)
        self.top.setParameters(config)

    def __updatefromtop(self,ndict):
        config = self.mcafit.configure()
        for key in ndict.keys():
            if DEBUG:
                keylist = ['stripflag','hypermetflag','sumflag','escapeflag',
                           'fitfunction', 'continuum']
                if key not in keylist:
                    print("UNKNOWN key ",key)
            config['fit'][key] = ndict[key]
        self.__fitdone = False
        #erase table
        if self.mcatable is not None:
            self.mcatable.setRowCount(0)
        #erase concentrations
        if self.concentrationsWidget is not None:
            self.concentrationsWidget.concentrationsTable.setRowCount(0)
        #update graph
        delcurves = []
        for key in self.graph.curves.keys():
            if key not in ["Data"]:
                delcurves.append(key)
        for key in delcurves:
            self.graph.delcurve(key)
        self.plot()

        if DEBUG or (QTVERSION < '3.0.0'):
            self.mcafit.configure(config)
        else:
            threadResult=self._submitThread(self.mcafit.configure, config,
                             "Configuring, please wait")
            if type(threadResult) == type((1,)):
                if len(threadResult):
                    if threadResult[0] == "Exception":
                        raise Exception(threadResult[1], threadResult[2])

    def _tabChanged(self, value):
        if DEBUG:
            print("_tabChanged(self, value) called")
        if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "CONCENTRATIONS":
            self.printButton.setEnabled(False)
            w = self.concentrationsWidget
            if w.parent() is None:
                if w.isHidden():
                    w.show()
                if QTVERSION < '4.0.0':
                    w.raiseW()
                else:
                    w.raise_()
                self.printButton.setEnabled(True)
                #do not calculate again. It should be already updated
                return
            if DEBUG:
                self.concentrations()
                self.printButton.setEnabled(True)
            else:
                try:
                    self.concentrations()
                    self.printButton.setEnabled(True)
                except:
                    #print "try to set"
                    self.printButton.setEnabled(False)
                    msg = qt.QMessageBox(self)
                    msg.setIcon(qt.QMessageBox.Critical)
                    msg.setText("Concentrations error: %s" % sys.exc_info()[1])
                    if QTVERSION < '4.0.0':
                        msg.exec_loop()
                    else:
                        msg.exec_()
                    self.mainTab.setCurrentIndex(0)
        elif str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "TABLE":
            self.printButton.setEnabled(True)
            w = self.mcatable
            if w.parent() is None:
                if w.isHidden():
                    w.show()
                if QTVERSION < '4.0.0':
                    w.raiseW()
                else:
                    w.raise_()
        elif str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "DIAGNOSTICS":
            self.printButton.setEnabled(False)
            self.diagnostics()
        else:
            self.printButton.setEnabled(True)

    def _concentrationsWidgetClose(self, dict):
        dict['info'] = "CONCENTRATIONS"
        self._tabReparent(dict)

    def _mcatableClose(self, dict):
        dict['info'] = "TABLE"
        self._tabReparent(dict)

    def _tabReparent(self, dict):
        if dict['info'] == "CONCENTRATIONS":
            w = self.concentrationsWidget
            parent = self.tabConcentrations
        elif dict['info'] == "TABLE":
            w = self.mcatable
            parent = self.tabMca
        if w.parent() is not None:
            if QTVERSION < '4.0.0':
                w.reparent(None,self.cursor().pos(),1)
            else:
                parent.layout().removeWidget(w)
                w.setParent(None)
                w.show()
        else:
            if QTVERSION < '4.0.0':
                w.reparent(parent,qt.QPoint(),1)
            else:
                w.setParent(parent)
                parent.layout().addWidget(w)

    def _calibrate(self):
        config = self.mcafit.configure()
        x = self.mcafit.xdata0[:]
        y = self.mcafit.ydata0[:]
        legend = "Calibration for " +str(self.headerLabel.text())
        ndict={}
        ndict[legend] = {'A':config['detector']['zero'],
               'B':config['detector']['gain'],
               'C': 0.0}
        caldialog = McaCalWidget.McaCalWidget(legend=legend,
                                                     x=x,
                                                     y=y,
                                                     modal=1,
                                                     caldict=ndict,
                                                     fl=0)
        caldialog.calpar.orderbox.setEnabled(0)
        caldialog.calpar.CText.setEnabled(0)
        caldialog.calpar.savebox.setEnabled(0)
        if QTVERSION < '4.0.0':
            ret = caldialog.exec_loop()
        else:
            ret = caldialog.exec_()
        if ret == qt.QDialog.Accepted:
            dict = caldialog.getdict()
            config['detector']['zero'] = dict[legend]['A']
            config['detector']['gain'] = dict[legend]['B']
            #self.mcafit.configure(config)
            self.mcafit.config['detector']['zero'] = 1. * dict[legend]['A']
            self.mcafit.config['detector']['gain'] = 1. * dict[legend]['B']
            self.__fitdone = 0
            self.plot()
        del caldialog

    def __elementsInfo(self):
        if self.elementsInfo is None:
            self.elementsInfo = ElementsInfo.ElementsInfo(None, "Elements Info")
        if self.elementsInfo.isHidden():
           self.elementsInfo.show()
        if QTVERSION < '4.0.0':
            self.elementsInfo.raiseW()
        else:
            self.elementsInfo.raise_()

    def __peakIdentifier(self, energy = None):
        if energy is None:energy = 5.9
        if self.identifier is None:
            self.identifier=PeakIdentifier.PeakIdentifier(energy=energy,
                                                          threshold=0.040,
                                                          useviewer=1)
            self.identifier.myslot()
        self.identifier.setEnergy(energy)
        if self.identifier.isHidden():
            self.identifier.show()
        if QTVERSION < '4.0.0':
            self.identifier.raiseW()
        else:
            self.identifier.raise_()

    def printActiveTab(self):
        if   str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "GRAPH":
            self.graph.printps()
        elif str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "TABLE":
            self.printps(True)
        elif str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "CONCENTRATIONS":
            self.printConcentrations(True)
        elif str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "DIAGNOSTICS":
            pass
        else:
            pass

    def diagnostics(self):
        if not self.__fitdone:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            text = "Sorry. You need to perform a fit first.\n"
            msg.setText(text)
            if QTVERSION < '4.0.0':
                msg.exec_loop()
            else:
                msg.exec_()
            if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "DIAGNOSTICS":
                self.mainTab.setCurrentIndex(0)
            return
        fitresult = self.dict
        x = fitresult['result']['xdata']
        energy = fitresult['result']['energy']
        y = fitresult['result']['ydata']
        yfit = fitresult['result']['yfit']
        param = fitresult['result']['fittedpar']
        i    = fitresult['result']['parameters'].index('Noise')
        noise= param[i] * param[i]
        i    = fitresult['result']['parameters'].index('Fano')
        fano = param[i] * 2.3548*2.3548*0.00385
        meanfwhm = Numeric.sqrt(noise + 0.5 * (energy[0] + energy[-1]) * fano)
        i = fitresult['result']['parameters'].index('Gain')
        gain = fitresult['result']['fittedpar'][i]
        meanfwhm = int(meanfwhm/gain) + 1
        missed =  self.mcafit.detectMissingPeaks(y, yfit, meanfwhm)
        hcolor = 'white'
        finalcolor = 'white'
        text=""
        if len(missed):
            text+="<br><b><font color=blue size=4>Possibly Missing or Underestimated Peaks</font></b>"
            text+="<nobr><table><tr>"
            text+='<td align="right" bgcolor="%s"><b>' % hcolor
            text+='Channel'
            text+="</b></td>"
            text+='<td align="right" bgcolor="%s"><b>' % hcolor
            text+='Energy'
            text+="</b></td>"
            text+="</tr>"
            text+="<tr>"
            for peak in missed:
                text+="<tr>"
                text+='<td align="right" bgcolor="%s">' % finalcolor
                text+="<b><font size=3>%d </font></b>"  % x[int(peak)]
                text+="</td>"
                text+='<td align="right" bgcolor="%s">' % finalcolor
                text+="<b><font size=3>%.3f </font></b>"  % energy[int(peak)]
                text+="</td>"
            text+="</tr>"
            text+="</table>"
        missed =  self.mcafit.detectMissingPeaks(yfit, y, meanfwhm)
        if len(missed):
            text+="<br><b><font color=blue size=4>Possibly Overestimated Peaks</font></b>"
            text+="<nobr><table><tr>"
            text+='<td align="right" bgcolor="%s"><b>' % hcolor
            text+='Channel'
            text+="</b></td>"
            text+='<td align="right" bgcolor="%s"><b>' % hcolor
            text+='Energy'
            text+="</b></td>"
            text+="</tr>"
            text+="<tr>"
            for peak in missed:
                text+="<tr>"
                text+='<td align="right" bgcolor="%s">' % finalcolor
                text+="<b><font size=3>%d </font></b>"  % x[int(peak)]
                text+="</td>"
                text+='<td align="right" bgcolor="%s">' % finalcolor
                text+="<b><font size=3>%.3f </font></b>"  % energy[int(peak)]
                text+="</td>"
            text+="</tr>"
            text+="</table>"
        if QTVERSION < '4.0.0':
            self.diagnosticsWidget.setText(text)
        else:
            self.diagnosticsWidget.clear()
            self.diagnosticsWidget.insertHtml(text)

    def concentrations(self):
        self._concentrationsDict = None
        if not self.__fitdone:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            text = "Sorry, You need to perform a fit first.\n"
            msg.setText(text)
            if QTVERSION < '4.0.0':
                msg.exec_loop()
            else:
                msg.exec_()
            if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == "CONCENTRATIONS":
                self.mainTab.setCurrentIndex(0)
            return
        fitresult = self.dict
        if False:
            #from the fit
            config = fitresult['result']['config']
        else:
            #from current
            config = self.mcafit.configure()
        #tool = ConcentrationsWidget.Concentrations(fl=qt.Qt.WDestructiveClose)
        if self.concentrationsWidget is None:
           self.concentrationsWidget = ConcentrationsWidget.Concentrations()
           if QTVERSION < '4.0.0':
               self.connect(self.concentrationsWidget,qt.PYSIGNAL("ConcentrationsSignal"),
                                    self.__configureFromConcentrations)
           else:
               self.connect(self.concentrationsWidget,qt.SIGNAL("ConcentrationsSignal"),
                                    self.__configureFromConcentrations)
        tool = self.concentrationsWidget
        toolconfig = tool.getParameters()
        dict = {}
        dict.update(config['concentrations'])
        tool.setParameters(dict, signal=False)
        if DEBUG:
            dict = tool.processFitResult(config=dict,fitresult=fitresult,
                    elementsfrommatrix=False,
                    fluorates = self.mcafit._fluoRates)
        else:
            try:
                dict = tool.processFitResult(config=dict,fitresult=fitresult,
                    elementsfrommatrix=False,
                    fluorates = self.mcafit._fluoRates)
            except:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Error processing fit result: %s" % (sys.exc_info()[1]))
                if QTVERSION < '4.0.0':
                    msg.exec_loop()
                else:
                    msg.exec_()
                if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == 'CONCENTRATIONS':
                    self.mainTab.setCurrentIndex(0)
                return
        self._concentrationsDict = dict
        tool.show()
        tool.setFocus()
        if QTVERSION < '4.0.0':
            tool.raiseW()
        else:
            tool.raise_()

    def __toggleMatrixSpectrum(self):
        if self.matrixSpectrumButton.isChecked():
            self.matrixSpectrum()
            self.plot()
        else:
            if "Matrix" in self.graph.curves.keys():
                self.graph.delcurve("Matrix")
                self.plot()

    def __togglePeaksSpectrum(self):
        if self.peaksSpectrumButton.isChecked():
            self.peaksSpectrum()
            self.plot()
        else:
            self.__clearPeaksSpectrum()
            self.plot()

    def __clearPeaksSpectrum(self):
        delcurves = []
        for key in self.graph.curves.keys():
            if key not in ["Data", "Fit", "Continuum", "Pile-up", "Matrix"]:
                delcurves.append(key)
        for key in delcurves:
            self.graph.delcurve(key)

    def matrixSpectrum(self):
        if not self.__fitdone:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            text = "Sorry, for the time being you need to perform a fit first\n"
            text+= "in order to calculate the spectrum derived from the matrix.\n"
            text+= "Background and detector parameters are taken from last fit"
            msg.setText(text)
            if QTVERSION < '4.0.0':
                msg.exec_loop()
            else:
                msg.exec_()
            return
        #fitresult = self.dict['result']
        fitresult = self.dict
        config = self.mcafit.configure()
        tool   = ConcentrationsTool.ConcentrationsTool()
        toolconfig = tool.configure()
        dict = {}
        dict.update(config['concentrations'])
        tool.configure(dict)
        if DEBUG:
            dict = tool.processFitResult(fitresult=fitresult,
                                         elementsfrommatrix=True)
        elif (QTVERSION < '3.0.0'):
            try:
                dict = tool.processFitResult(fitresult=fitresult,
                                         elementsfrommatrix=True)
            except:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Error: %s" % (sys.exc_info()[1]))
                msg.exec_loop()
                return
        else:
            try:
                threadResult = self._submitThread(tool.processFitResult,
                                   {'fitresult':fitresult,'elementsfrommatrix':True},
                                   "Calculating Matrix Spectrum",
                                   True)
                if type(threadResult) == type((1,)):
                    if len(threadResult):
                        if threadResult[0] == "Exception":
                            raise Exception(threadResult[1], threadResult[2])
                dict = threadResult
            except:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Error: %s" % (sys.exc_info()[1]))
                if QTVERSION < '4.0.0':
                    msg.exec_loop()
                else:
                    msg.exec_()
                return
        groupsList = fitresult['result']['groups']

        if type(groupsList) != type([]):
            groupsList = [groupsList]
        areas = []
        for group in groupsList:
            item = group.split()
            element = item[0]
            if len(element) >2:
                areas.append(0.0)
            else:
                transitions = item[1] + " xrays"
                areas.append(dict['area'][group])

        nglobal    = len(fitresult['result']['parameters']) - len(groupsList)
        parameters = []
        for i in range(len(fitresult['result']['parameters'])):
            if i < nglobal:
                parameters.append(fitresult['result']['fittedpar'][i])
            else:
                parameters.append(areas[i-nglobal])

        xmatrix = fitresult['result']['xdata']
        ymatrix = self.mcafit.mcatheory(parameters,xmatrix)
        ymatrix.shape =  [len(ymatrix),1]
        dict=copy.deepcopy(self.dict)
        dict['event'] = "McaAdvancedFitMatrixFinished"
        if self.mcafit.STRIP:
            dict['result']['ymatrix']  = ymatrix + self.mcafit.zz
        else:
            dict['result']['ymatrix']  = ymatrix
        dict['result']['ymatrix'].shape  = (len(dict['result']['ymatrix']),)
        dict['result']['continuum'].shape  = (len(dict['result']['ymatrix']),)
        if self.matrixSpectrumButton.isChecked():self.dict['result']['ymatrix']= dict['result']['ymatrix'] * 1.0
        """
        if self.graph is not None:
            if self._logY:
                logfilter = 1
            else:
                logfilter = 0
            if self._energyAxis:
                xdata = dict['result']['energy'][:]
            else:
                xdata = dict['result']['xdata'][:]
            self.graph.newCurve("Matrix",xdata,dict['result']['ymatrix'],logfilter=logfilter)
        """
        try:
            self.__anasignal(dict)
        except:
            print("Error generating matrix output. ")
            print("Try to perform your fit again.  ")
            print(sys.exc_info())
            print("If error persists, please report this error.")
            print("ymatrix shape = ", dict['result']['ymatrix'].shape)
            print("xmatrix shape = ", xmatrix.shape)
            print("continuum shape = ", dict['result']['continuum'].shape)
            print("zz      shape = ", self.mcafit.zz.shape)

    def peaksSpectrum(self):
        if not self.__fitdone:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            text = "You need to perform a fit first\n"
            msg.setText(text)
            if QTVERSION < '4.0.0':
                msg.exec_loop()
            else:
                msg.exec_()
            return
        #fitresult = self.dict['result']
        fitresult = self.dict
        config = self.mcafit.configure()
        groupsList = fitresult['result']['groups']
        if type(groupsList) != type([]):
            groupsList = [groupsList]

        nglobal    = len(fitresult['result']['parameters']) - len(groupsList)
        dict=copy.deepcopy(self.dict)
        dict['event'] = "McaAdvancedFitPeaksFinished"
        newparameters = fitresult['result']['fittedpar'] * 1
        for i in range(nglobal,len(fitresult['result']['parameters'])):
            newparameters[i] = 0.0
        for i in range(nglobal,len(fitresult['result']['parameters'])):
            group = fitresult['result']['parameters'][i]
            parameters    = newparameters * 1
            parameters[i] = fitresult['result']['fittedpar'][i]
            xmatrix = fitresult['result']['xdata']
            ymatrix = self.mcafit.mcatheory(parameters,xmatrix)
            ymatrix.shape =  [len(ymatrix),1]
            label = 'y'+group
            if self.mcafit.STRIP:
                dict['result'][label]  = ymatrix + self.mcafit.zz
            else:
                dict['result'][label]  = ymatrix
            dict['result'][label].shape  = (len(dict['result'][label]),)
            if self.peaksSpectrumButton.isChecked():self.dict['result'][label]= dict['result'][label] * 1.0
        try:
            self.__anasignal(dict)
        except:
            print("Error generating peaks output. ")
            print("Try to perform your fit again.  ")
            print(sys.exc_info())
            print("If error persists, please report this error.")
            print("ymatrix shape = ", dict['result']['ymatrix'].shape)
            print("xmatrix shape = ", xmatrix.shape)
            print("continuum shape = ", dict['result']['continuum'].shape)
            print("zz      shape = ", self.mcafit.zz.shape)

    def __printps(self):
        if QTVERSION < '4.0.0':
            self.__printmenu.exec_loop(self.cursor().pos())
        else:
            self.__printmenu.exec_(self.cursor().pos())

    def htmlReport(self,index=None):
        if not self.__fitdone:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText("You should perform a fit \nfirst,\n shouldn't you?")
            if QTVERSION < '4.0.0':
                msg.exec_loop()
            else:
                msg.exec_()
            return
        oldoutdir = self.outdir
        if self.outdir is None:
            cwd = PyMcaDirs.outputDir
            if QTVERSION < '4.0.0':
                outfile = qt.QFileDialog(self,"Output Directory Selection",1)
                outfile.setMode(outfile.DirectoryOnly)
                outfile.setDir(cwd)
                ret = outfile.exec_loop()
            else:
                outfile = qt.QFileDialog(self)
                outfile.setWindowTitle("Output Directory Selection")
                outfile.setModal(1)
                outfile.setFileMode(outfile.DirectoryOnly)
                outfile.setDirectory(cwd)
                ret = outfile.exec_()
            if ret:
                if QTVERSION < '4.0.0':
                    self.outdir=str(outfile.selectedFile())
                else:
                    self.outdir=str(outfile.selectedFiles()[0])
                outfile.close()
                del outfile
            else:
                outfile.close()
                del outfile
                return
            if self.outdir[-1]=="/":self.outdir=self.outdir[0:-1]
        try:
            report = self.__htmlReport()
        except IOError:
            self.outdir = None
            if oldoutdir is not None:
                if os.path.exists(oldoutdir):
                    self.outdir = oldoutdir
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText("Input Output Error: %s" % (sys.exc_info()[1]))
            if QTVERSION < '4.0.0':
                msg.exec_loop()
            else:
                msg.exec_()


    def __htmlReport(self,outfile=None):
        report = QtMcaAdvancedFitReport.QtMcaAdvancedFitReport(None,
                    outfile,self.outdir,self.info['sourcename'],
                    self.info['legend'],self.dict,
                    concentrations=self._concentrationsDict,
                    plotdict={'logy':self._logY})
        if 0:
            #this forces to open and read the file
            self.__lastreport = report.writeReport()
        else:
            text = report.getText()
            self.__lastreport = report.writeReport(text=text)
        if self.browser is None:
            self.browser= qt.QWidget()
            if QTVERSION < '4.0.0':
                self.browser.setCaption(QString(self.__lastreport))
            else:
                self.browser.setWindowTitle(QString(self.__lastreport))
            self.browser.layout = qt.QVBoxLayout(self.browser)
            self.browser.layout.setMargin(0)
            self.browser.layout.setSpacing(0)
            if QTVERSION < '4.0.0':
                self.__printmenu.insertSeparator()
                self.__printmenu.insertItem(QString("Last Report"),self.showLastReport)
            else:
                self.__printmenu.addSeparator()
                self.__printmenu.addAction(QString("Last Report"),self.showLastReport)

            if QTVERSION < '4.0.0':
                self.browsertext= qt.QTextView(self.browser)
            else:
                self.browsertext = qt.QTextBrowser(self.browser)
                self.browsertext.setReadOnly(1)
                screenWidth = qt.QDesktopWidget().width()
                if screenWidth > 0:
                    self.browsertext.setMinimumWidth(min(self.width(), int(0.5 * screenWidth)))
                else:
                    self.browsertext.setMinimumWidth(self.width())
                screenHeight = qt.QDesktopWidget().height()
                if screenHeight > 0:
                    self.browsertext.setMinimumHeight(min(self.height(), int(0.5 * screenHeight)))
                else:
                    self.browsertext.setMinimumHeight(self.height())

            self.browser.layout.addWidget(self.browsertext)
        else:
            if QTVERSION < '4.0.0':
                self.browser.setCaption(QString(self.__lastreport))
            else:
                self.browser.setWindowTitle(QString(self.__lastreport))

        if QTVERSION < '4.0.0':
            self.browsertext.mimeSourceFactory().addFilePath(QString(os.path.dirname(self.__lastreport)))
            self.browsertext.setText(text)
        else:
            dirname  = os.path.dirname(self.__lastreport)
            basename = os.path.basename(self.__lastreport)
            #self.browsertext.setMimeSourceFactory(qt.QMimeFactory.defaultFactory())
            #self.browsertext.mimeSourceFactory().addFilePath(QString(dirname))
            self.browsertext.setSearchPaths([QString(dirname)])
            #self.browsertext.setSource(qt.QUrl(QString(basename)))
            self.browsertext.clear()
            if QTVERSION < '4.2.0':
                self.browsertext.insertHtml(text)
            else:
                self.browsertext.setText(text)
        self.browsertext.show()
        self.showLastReport()

    def showLastReport(self):
        if self.browser is not None:
            self.browser.show()
            if QTVERSION < '4.0.0':
                self.browser.raiseW()
            else:
                self.browser.raise_()

    def printConcentrations(self, doit=0):
        text = "<CENTER>"+self.concentrationsWidget.concentrationsTable.getHtmlText()+"</CENTER>"
        if (__name__ == "__main__") or (doit):
            self.__print(text)
            #print h+text
        else:
            ddict={}
            ddict['event'] = "McaAdvancedFitPrint"
            ddict['text' ] = h+text
            if QTVERSION < '4.0.0':
                self.emit(qt.PYSIGNAL('McaAdvancedFitSignal'), (ddict,))
            else:
                self.emit(qt.SIGNAL('McaAdvancedFitSignal'), (ddict))

    def printps(self,doit=0):
        h = self.__htmlheader()
        text = "<CENTER>"+self.mcatable.gettext()+"</CENTER>"
        #text = self.mcatable.gettext()
        if (__name__ == "__main__") or (doit):
            self.__print(h+text)
            #print h+text
        else:
            ddict={}
            ddict['event'] = "McaAdvancedFitPrint"
            ddict['text' ] = h+text
            if QTVERSION < '4.0.0':
                self.emit(qt.PYSIGNAL('McaAdvancedFitSignal'), (ddict,))
            else:
                self.emit(qt.SIGNAL('McaAdvancedFitSignal'), (ddict))

    def __htmlheader(self):
        header = "%s" % str(self.headerLabel.text())
        if header[0] == "<":
            header = header[3:-3]
        if self.mcafit.config['fit']['sumflag']:
            sumflag = "Y"
        else:
            sumflag = "N"

        if self.mcafit.config['fit']['escapeflag']:
            escapeflag =  "Y"
        else:
            escapeflag = "N"

        if self.mcafit.config['fit']['stripflag']:
            stripflag = "Y"
        else:
            stripflag = "N"
        #bkg = self.mcafit.config['fit']['continuum']
        #theory = "Hypermet"
        bkg    = "%s" % str(self.top.BkgComBox.currentText())
        theory = "%s" % str(self.top.FunComBox.currentText())
        hypermetflag=self.mcafit.config['fit']['hypermetflag']
        g_term    = hypermetflag  & 1
        st_term   = (hypermetflag >>1) & 1
        lt_term   = (hypermetflag >>2) & 1
        step_term = (hypermetflag >>3) & 1
        if st_term:
            st_term = "Y"
        else:
            st_term = "N"
        if st_term:
            lt_term = "Y"
        else:
            lt_term = "N"
        if step_term:
            step_term = "Y"
        else:
            step_term = "N"


        h=""
        h+="    <CENTER>"
        h+="<B>%s</B>" % header
        h+="    </CENTER>"
        h+="    <SPACER TYPE=BLOCK HEIGHT=10>"
        #h+="<BR></BR>"
        h+="    <CENTER>"
        h+="<TABLE>"
        h+="<TR>"
        h+="    <TD ALIGN=LEFT><B>Function</B></TD>"
        h+="    <TD><B>:</B></TD>"
        h+="    <TD NOWRAP ALIGN=LEFT>%s</TD>" % theory
        h+="    <TD><SPACER TYPE=BLOCK WIDTH=15></TD>"

        h+="    <TD ALIGN=LEFT><B>ShortTail</B></TD>"
        h+="    <TD><B>:</B></TD>"
        h+="    <TD>%s</TD>" % st_term
        h+="    <TD><SPACER TYPE=BLOCK WIDTH=5></B></TD>"

        h+="    <TD ALIGN=LEFT><B>LongTail</B></TD>"
        h+="    <TD><B>:</B></TD>"
        h+="    <TD>%s</TD>" % lt_term
        h+="    <TD><SPACER TYPE=BLOCK WIDTH=5></B></TD>"

        h+="    <TD ALIGN=LEFT><B>StepTail</B></TD>"
        h+="    <TD><B>:</B></TD>"
        h+="    <TD>%s</TD>" % step_term
        h+="</TR>"

        h+="<TR>"
        #h+="    <TD ALIGN=LEFT><B>Background</B></TH>"
        h+="    <TD ALIGN=LEFT><B>Backg.</B></TH>"
        h+="    <TD><B>:</B></TD>"
        h+="    <TD NOWRAP ALIGN=LEFT>%s</TD>" % bkg
        h+="    <TD><SPACER TYPE=BLOCK WIDTH=15></B></TD>"

        h+="    <TD ALIGN=LEFT><B>Escape</B></TD>"
        h+="    <TD><B>:</B></TD>"
        h+="    <TD>%s</TD>" % escapeflag
        h+="    <TD><SPACER TYPE=BLOCK WIDTH=5></B></TD>"

        h+="    <TD ALIGN=LEFT><B>Pile-up</B></TD>"
        h+="    <TD><B>:</B></TD>"
        h+="    <TD ALIGN=LEFT>%s</TD>" % sumflag
        h+="    <TD><SPACER TYPE=BLOCK WIDTH=5></B></TD>"

        h+="    <TD ALIGN=LEFT><B>Strip</B></TD>"
        h+="    <TD><B>:</B></TD>"
        h+="    <TD>%s</TD>" % stripflag

        h+="</TR>"
        h+="</TABLE>"
        h+="</CENTER>"
        return h


    if QTVERSION < '4.0.0':
        def __print(self,text):
            printer = qt.QPrinter()
            if printer.setup(self):
                painter = qt.QPainter()
                if not(painter.begin(printer)):
                    return 0
                metrics = qt.QPaintDeviceMetrics(printer)
                dpiy    = metrics.logicalDpiY()
                margin  = int((2/2.54) * dpiy) #2cm margin
                body = qt.QRect(0.5*margin, margin, metrics.width()- 1 * margin, metrics.height() - 2 * margin)
                #html output -> print text
                richtext = qt.QSimpleRichText(text, qt.QFont(),
                                                    QString(""),
                                                    #0,
                                                    qt.QStyleSheet.defaultSheet(),
                                                    qt.QMimeSourceFactory.defaultFactory(),
                                                    body.height())
                view = qt.QRect(body)
                richtext.setWidth(painter,view.width())
                page = 1
                while(1):
                    if QTVERSION < '3.0.0':
                        richtext.draw(painter,body.left(),body.top(),
                                    qt.QRegion(0.5*margin, margin, metrics.width()- 1 * margin, metrics.height() - 2 * margin),
                                    qt.QColorGroup())
                        #richtext.draw(painter,body.left(),body.top(),
                        #            qt.QRegion(view),
                        #            qt.QColorGroup())
                    else:
                        richtext.draw(painter,body.left(),body.top(),
                                    view,qt.QColorGroup())
                    view.moveBy(0, body.height())
                    painter.translate(0, -body.height())
                    painter.drawText(view.right()  - painter.fontMetrics().width(QString.number(page)),
                                     view.bottom() - painter.fontMetrics().ascent() + 5,QString.number(page))
                    if view.top() >= richtext.height():
                        break
                    printer.newPage()
                    page += 1

                #painter.flush()
                painter.end()
    else:
        def __print(self,text):
            printer = qt.QPrinter()
            printDialog = qt.QPrintDialog(printer, self)
            if printDialog.exec_():
                if 0:
                    #this was crashing in Qt 4.2.2
                    #with the PyQt snapshot of 20061203
                    editor = qt.QTextEdit()
                    cursor = editor.textCursor()
                    cursor.movePosition(qt.QTextCursor.Start)
                    editor.insertHtml(text)
                    document = editor.document()
                else:
                    document = qt.QTextDocument()
                    document.setHtml(text)
                document.print_(printer)

    def setdata(self, *var, **kw):
        if DEBUG:
            print("McaAdvancedFit.setdata deprecated, use setData instead.")
        return self.setData( *var, **kw)

    def setData(self,*var,**kw):
        """
        The simplest way to use it is to pass at least the y keyword containing
        the channel counts. The other items are not mandatory.
        
        :keywords:
            x
                channels
            y
                counts in each channel
            sigmay
                uncertainties to be applied if different than sqrt(y)
            xmin
                minimum channel of the fit
            xmax
                maximum channel of the fit
            calibration
                list of the form [a, b, c] containing the mca calibration 
        """
        
        self.__fitdone = 0
        self.info ={}
        key = 'legend'
        if key in kw:
            self.info[key] = kw[key]
        else:
            self.info[key] = 'Unknown Origin'
        key = 'xlabel'
        if key in kw:
            self.info[key] = kw[key]
        else:
            self.info[key] = 'X'
        key = 'xmin'
        if key in kw:
            self.info[key] = "%.3f" % kw[key]
        else:
            self.info[key] = "????"
        key = 'xmax'
        if key in kw:
            self.info[key] = "%.3f" % kw[key]
        else:
            self.info[key] = "????"
        key = 'sourcename'
        if key in kw:
            self.info[key] = "%s" % kw[key]
        else:
            self.info[key] = "Unknown Source"
        self.__var = var
        self.__kw  = kw
        self.mcafit.setdata(*var,**kw)
        if self.configDialog is not None:
            self.configDialog.setData(self.mcafit.xdata * 1.0,
                           self.mcafit.ydata * 1.0)

        if 'calibration' in kw:
            if kw['calibration'] is not None:
                if kw['calibration'] != [0.0,1.0,0.0]:
                    self.mcafit.config['detector']['zero']=kw['calibration'][0] * 1
                    self.mcafit.config['detector']['gain']=kw['calibration'][1] * 1

        self.setHeader(text="Fit of %s from %s %s to %s" % (self.info['legend'],
                                                            self.info['xlabel'],
                                                            self.info['xmin'],
                                                            self.info['xmax']))
        self._updateTop()
        self.plot()

    def setheader(self, *var, **kw):
        if DEBUG:
            print("McaAdvancedFit.setheader deprecated, use setHeader instead.")
        return self.setHeader( *var, **kw)

    def setHeader(self,*var,**kw):
        if len(var):
            text = var[0]
        elif 'text' in kw:
            text = kw['text']
        elif 'header' in kw:
            text = kw['header']
        else:
            text = ""
        self.headerLabel.setText("%s" % text)

    def fit(self):
        """
        Function called to start the fit process.
        
        Interactive use
                
        It returns a dictionnary containing the fit results or None in case of 
        unsuccessfull fit.
        
        Embedded use
        
        In case of successfull fit emits a signal of the form:
            
        self.emit(qt.SIGNAL('McaAdvancedFitSignal'), (ddict))
        
        where ddict['event'] = 'McaAdvancedFitFinished'
        """    
        self.__fitdone = 0
        self.mcatable.setRowCount(0)
        if self.concentrationsWidget is not None:
            self.concentrationsWidget.concentrationsTable.setRowCount(0)
        fitconfig = {}
        fitconfig.update(self.mcafit.configure())
        if fitconfig['peaks'] == {}:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Information)
            msg.setText("No peaks defined.\nPlease configure peaks")
            if QTVERSION < '4.0.0':
                msg.exec_loop()
            else:
                msg.exec_()
            return
        if DEBUG or (QTVERSION < '3.0.0'):
            if DEBUG:
                print("calling estimate")
            self.mcafit.estimate()
            if DEBUG:
                print("calling startfit")
            fitresult,result = self.mcafit.startfit(digest=1)
            if DEBUG:
                print("filling table")
            self.mcatable.fillfrommca(result)
            if DEBUG:
                print("finished")
        else:
            try:
                self.mcafit.estimate()
                threadResult = self._submitThread(self.mcafit.startfit,
                                            {'digest':1},
                                            "Calculating Fit",
                                            True)
                if type(threadResult) == type((1,)):
                    if len(threadResult):
                        if threadResult[0] == "Exception":
                            raise Exception(threadResult[1], threadResult[2])
                fitresult = threadResult[0]
                result    = threadResult[1]
            except:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                if QTVERSION < '4.0.0':
                    msg.setText("Error on fit: %s" % (sys.exc_info()[1]))
                    msg.exec_loop()
                else:
                    msg.setWindowTitle("Fit error")
                    msg.setText("Error on fit:")
                    msg.setInformativeText(str(sys.exc_info()[1]))
                    msg.setDetailedText(traceback.format_exc())
                    msg.exec_()
                    msg.exec_()
                return
            try:
                #self.mcatable.fillfrommca(self.mcafit.result)
                self.mcatable.fillfrommca(result)
            except:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Error filling Table: %s" % (sys.exc_info()[1]))
                if QTVERSION < '4.0.0':
                    msg.exec_loop()
                else:
                    msg.exec_()
                return
        dict={}
        dict['event']     = "McaAdvancedFitFinished"
        dict['fitresult'] = fitresult
        dict['result']    = result
        #I should make a copy but ...
        self.dict = {}
        self.dict['info'] = {}
        self.dict['info'] = self.info.copy()
        self.dict['result'] = dict['result']
        self.__fitdone      = 1
        # add the matrix spectrum
        if self.matrixSpectrumButton.isChecked():
            self.matrixSpectrum()
        else:
            if "Matrix" in self.graph.curves.keys():
                self.graph.delcurve("Matrix")
        # add the peaks spectrum
        if self.peaksSpectrumButton.isChecked():
            self.peaksSpectrum()
        else:
            self.__clearPeaksSpectrum()
        self.plot()

        if self.concentrationsWidget is not None:
            if (str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == 'CONCENTRATIONS') or \
                (self.concentrationsWidget.parent() is None):
                if not self.concentrationsWidget.isHidden():
                    if DEBUG:
                        self.concentrations()
                    else:
                        try:
                            self.concentrations()
                        except:
                            msg = qt.QMessageBox(self)
                            msg.setIcon(qt.QMessageBox.Critical)
                            msg.setText("Concentrations Error: %s" % (sys.exc_info()[1]))
                            if QTVERSION < '4.0.0':
                                msg.exec_loop()
                            else:
                                msg.exec_()
                            return
        if str(self.mainTab.tabText(self.mainTab.currentIndex())).upper() == 'DIAGNOSTICS':
            try:
                self.diagnostics()
            except:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                msg.setText("Diagnostics Error: %s" % (sys.exc_info()[1]))
                if QTVERSION < '4.0.0':
                    msg.exec_loop()
                else:
                    msg.exec_()
                return

        return self.__anasignal(dict)

    def __anasignal(self, ddict):
        if type(ddict) != type({}):
            return
        if 'event' in ddict:
            ddict['info'] = {}
            ddict['info'].update(self.info)
            if QTVERSION < '4.0.0':
                self.emit(qt.PYSIGNAL('McaAdvancedFitSignal'), (ddict,))
            else:
                self.emit(qt.SIGNAL('McaAdvancedFitSignal'), (ddict))

            #Simplify interactive usage of the module
            return ddict

    def dismiss(self):
        self.close()

    def closeEvent(self, event):
        if self.identifier is not None:
            self.identifier.close()
        qt.QWidget.closeEvent(self, event)

    def _mcaGraphSignalSlot(self, ddict):
        if ddict['event'] == "FitClicked":
            self.fit()
        elif ddict['event'] == "LogClicked":
            self.toggleLogY(ddict)
        elif ddict['event'] == "EnergyClicked":
            self.toggleEnergyAxis()
        elif ddict['event'] == "SaveClicked":
            self._saveGraph()
        elif ddict['event'] == 'MouseClick':
            if self._energyAxis:
                self.__peakIdentifier(ddict['x'])
        else:
            pass
        return

    def toggleEnergyAxis(self, dict=None):
        if self._energyAxis:
            self._energyAxis = False
            self.graph.xlabel('Channel')
        else:
            self._energyAxis = True
            self.graph.xlabel('Energy')
        self.plot()

    def toggleLogY(self, dict=None):
        if self._logY:
            self.graph.ToggleLogY()
            self._logY = False
            self.plot()
        else:
            self._logY = True
            self.plot()
            self.graph.ToggleLogY()

    def plot(self, dict=None):
        if self._logY:
            logfilter = 1
        else:
            logfilter = 0
        config = self.mcafit.configure()
        if dict is None:
            if not self.__fitdone:
                #color counter
                self.graph.color   = 0
                #symbol counter
                self.graph.symbol  = 0
                #line type
                self.graph.linetype= 0
                for key in list(self.graph.curves.keys()):
                    if key not in ["Data"]:
                        self.graph.delcurve(key)
                    else:
                        self.graph.color   = 1

                #just the data
                xdata  = self.mcafit.xdata * 1.0
                if self._energyAxis:
                    xdata = config['detector'] ['zero'] + config['detector'] ['gain'] * xdata
                if self.mcafit.STRIP:
                    ydata  = self.mcafit.ydata + self.mcafit.zz
                else:
                    ydata  = self.mcafit.ydata * 1.0
                xdata.shape= [len(xdata),]
                ydata.shape= [len(ydata),]
                self.graph.newCurve("Data",xdata,
                                           ydata,logfilter=logfilter)
                self.graph.replot()
                return
            else:
                dict = self.dict
        if self._energyAxis:
            xdata = dict['result']['energy'][:]
        else:
            xdata = dict['result']['xdata'][:]
        self.graph.newCurve("Data",xdata,
                                   dict['result']['ydata'],logfilter=logfilter)
        self.graph.newCurve("Fit", xdata,
                                   dict['result']['yfit'],logfilter=logfilter)
        self.graph.newCurve("Continuum",xdata,
                                   dict['result']['continuum'],logfilter=logfilter)

        if config['fit']['sumflag']:
            self.graph.newCurve("Pile-up", xdata,
                                       dict['result']['pileup']+dict['result']['continuum'],
                                       logfilter=logfilter)
        elif "Pile-up" in self.graph.curves.keys():
            self.graph.delcurve("Pile-up")

        if self.matrixSpectrumButton.isChecked():
            if 'ymatrix' in dict['result']:
                self.graph.newCurve("Matrix",xdata, dict['result']['ymatrix'],
                                    logfilter=logfilter)
            else:
                if "Matrix" in self.graph.curves.keys():
                    self.graph.delcurve("Matrix")
        else:
            if "Matrix" in self.graph.curves.keys():
                self.graph.delcurve("Matrix")

        if self.peaksSpectrumButton.isChecked():
            keep = ['Data','Fit','Continuum','Matrix','Pile-up']
            for group in dict['result']['groups']:
                keep += ['y'+group]
            for key in list(self.graph.curves.keys()):
                if key not in keep:
                    self.graph.delcurve(key)
            for group in dict['result']['groups']:
                label = 'y'+group
                if label in dict['result']:
                    self.graph.newCurve(label,xdata, dict['result'][label],
                                    logfilter=logfilter)
                else:
                    if group in self.graph.curves.keys():
                        self.graph.delcurve(label)
        else:
            self.__clearPeaksSpectrum()

        self.graph.replot()

    def _saveGraph(self, dict=None):
        curves = self.graph.curves.keys()
        if not len(curves):return
        if not self.__fitdone:
            if False:
                #just the data
                xdata  = self.mcafit.xdata
                config = self.mcafit.configure()
                energy = config['detector'] ['zero'] + config['detector'] ['gain'] * xdata
                if self.mcafit.STRIP:
                    ydata  = self.mcafit.ydata + self.mcafit.zz
                else:
                    ydata  = self.mcafit.ydata
                savelist = ['xdata', 'energy','ydata']
            else:
                msg = qt.QMessageBox(self)
                msg.setIcon(qt.QMessageBox.Critical)
                text = "Sorry, You need to perform a fit first.\n"
                msg.setText(text)
                if QTVERSION < '4.0.0':
                    msg.exec_loop()
                else:
                    msg.exec_()
                return
        if dict is None:
            #everything
            fitresult = self.dict
        else:
            fitresult = dict
        xdata     = fitresult['result']['xdata']
        energy    = fitresult['result']['energy']
        ydata     = fitresult['result']['ydata']
        yfit      = fitresult['result']['yfit']
        continuum = fitresult['result']['continuum']
        pileup    = fitresult['result']['pileup']
        savelist  = ['xdata', 'energy','ydata','yfit','continuum','pileup']
        parNames  = fitresult['result']['parameters']
        parFit    = fitresult['result']['fittedpar']
        parSigma  = fitresult['result']['sigmapar']
        #still to add the matrix spectrum

        #get outputfile
        outfile = qt.QFileDialog(self)
        outfile.setModal(1)
        if self.lastInputDir is None:
            self.lastInputDir = PyMcaDirs.outputDir
        if QTVERSION < '4.0.0':
            outfile.setCaption("Output File Selection")
            filterlist = 'Specfile MCA  *.mca\nSpecfile Scan *.dat\nRaw ASCII  *.txt'
            if MATPLOTLIB:
                filterlist += '\nGraphics EPS *.eps\nGraphics PNG *.png'
                if not self.peaksSpectrumButton.isChecked():
                    filterlist += '\nB/WGraphics EPS *.eps\nB/WGraphics PNG *.png'
            outfile.setFilters(filterlist)
            outfile.setMode(outfile.AnyFile)
            outfile.setDir(self.lastInputDir)
            ret = outfile.exec_loop()
        else:
            outfile.setWindowTitle("Output File Selection")
            if hasattr(qt, "QStringList"):
                strlist = qt.QStringList()
            else:
                strlist = []
            format_list = ['Specfile MCA  *.mca',
                           'Specfile Scan *.dat',
                           'Raw ASCII  *.txt',
                           '";"-separated CSV *.csv',
                           '","-separated CSV *.csv',
                           '"tab"-separated CSV *.csv']
            if MATPLOTLIB:
                format_list.append('Graphics PNG *.png')
                format_list.append('Graphics EPS *.eps')
                format_list.append('Graphics SVG *.svg')
                if not self.peaksSpectrumButton.isChecked():
                    format_list.append('B/WGraphics PNG *.png')
                    format_list.append('B/WGraphics EPS *.eps')
                    format_list.append('B/WGraphics SVG *.svg')
            for f in format_list:
                strlist.append(f)
            outfile.setFilters(strlist)

            outfile.setFileMode(outfile.AnyFile)
            outfile.setAcceptMode(qt.QFileDialog.AcceptSave)
            outfile.setDirectory(self.lastInputDir)
            ret = outfile.exec_()

        if ret:
            filterused = str(outfile.selectedFilter()).split()
            filedescription = filterused[0]
            filetype  = filterused[1]
            extension = filterused[2]
            if QTVERSION < '4.0.0':
                outstr=str(outfile.selectedFile())
            else:
                outstr=str(outfile.selectedFiles()[0])
            try:
                outputDir  = os.path.dirname(outstr)
                self.lastInputDir   = outputDir
                PyMcaDirs.outputDir = outputDir
            except:
                outputDir  = "."
            #self.outdir = outputDir
            try:
                outputFile = os.path.basename(outstr)
            except:
                outputFile  = outstr
            outfile.close()
            del outfile
        else:
            outfile.close()
            del outfile
            return
        #always overwrite for the time being
        if len(outputFile) < len(extension[1:]):
            outputFile += extension[1:]
        elif outputFile[-4:] != extension[1:]:
            outputFile += extension[1:]
        specFile = os.path.join(outputDir, outputFile)
        try:
            os.remove(specFile)
        except:
            pass
        systemline = os.linesep
        os.linesep = '\n'
        try:
            if MATPLOTLIB:
                if filetype in ['EPS', 'PNG', 'SVG']:
                    size = (7, 3.5) #in inches
                    logy = self._logY
                    if filedescription == "B/WGraphics":
                        bw = True
                    else:
                        bw = False
                    if self.peaksSpectrumButton.isChecked():  legends = True
                    elif 'ymatrix' in fitresult['result'].keys(): legends = False
                    else: legends = False
                    if self.matplotlibDialog is None:
                        self.matplotlibDialog = QPyMcaMatplotlibSave1D.\
                                                QPyMcaMatplotlibSaveDialog(size=size,
                                                                    logy=logy,
                                                                    legends=legends,
                                                                    bw = bw)
                    mtplt = self.matplotlibDialog.plot
                    mtplt.setParameters({'logy':logy,
                                         'legends':legends,
                                         'bw':bw})
                    """
                        mtplt = PyMcaMatplotlibSave.PyMcaMatplotlibSave(size=size,
                                                                    logy=logy,
                                                                    legends=legends,
                                                                    bw = bw)
                        self.matplotlibDialog = None
                    """
                    if self._energyAxis:
                        x = fitresult['result']['energy']
                    else:
                        x = fitresult['result']['xdata']
                    xmin, xmax = self.graph.getx1axislimits()
                    ymin, ymax = self.graph.gety1axislimits()
                    mtplt.setLimits(xmin, xmax, ymin, ymax)
                    index = Numeric.nonzero((xmin <= x) & (x <= xmax))
                    x = Numeric.take(x, index)
                    if bw:
                        mtplt.addDataToPlot( x,
                                Numeric.take(fitresult['result']['ydata'],index),
                                legend='data',
                                color='k',linestyle=':', linewidth=1.5, markersize=3)
                    else:
                        mtplt.addDataToPlot( x,
                                Numeric.take(fitresult['result']['ydata'],index),
                                legend='data',
                                linewidth=1)

                    mtplt.addDataToPlot( x,
                                Numeric.take(fitresult['result']['yfit'],index),
                                legend='fit',
                                linewidth=1.5)
                    if not self.peaksSpectrumButton.isChecked():
                        mtplt.addDataToPlot( x,
                                    Numeric.take(fitresult['result']['continuum'],index),
                                    legend='bck', linewidth=1.5)
                    if self.top.sumbox.isChecked():
                        mtplt.addDataToPlot( x,
                                Numeric.take(fitresult['result']['pileup']+\
                                             fitresult['result']['continuum'],index),
                                             legend="pile up",
                                             linewidth=1.5)
                    if 'ymatrix' in fitresult['result'].keys():
                        mtplt.addDataToPlot( x,
                                Numeric.take(fitresult['result']['ymatrix'],index),
                                legend='matrix',
                                linewidth=1.5)
                    if self.peaksSpectrumButton.isChecked():
                        for group in fitresult['result']['groups']:
                            label = 'y'+group
                            if label in fitresult['result'].keys():
                                mtplt.addDataToPlot( x,
                                    Numeric.take(fitresult['result'][label],index),
                                                legend=group,
                                                linewidth=1.5)
                    if self._energyAxis:
                        mtplt.setXLabel('Energy (keV)')
                    else:
                        mtplt.setXLabel('Channel')
                    mtplt.setYLabel('Counts')
                    mtplt.plotLegends()
                    if self.matplotlibDialog is not None:
                        ret = self.matplotlibDialog.exec_()
                        if ret == qt.QDialog.Accepted:
                            mtplt.saveFile(specFile)
                    else:
                        mtplt.saveFile(specFile)
                    return
        except:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText("Matplotlib or Input Output Error: %s" % (sys.exc_info()[1]))
            if QTVERSION < '4.0.0':
                msg.exec_loop()
            else:
                msg.exec_()
            return
        try:
            file=open(specFile,'wb')
        except IOError:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText("Input Output Error: %s" % (sys.exc_info()[1]))
            if QTVERSION < '4.0.0':
                msg.exec_loop()
            else:
                msg.exec_()
            return
        try:
            if filetype == 'ASCII':
                keys = fitresult['result'].keys()
                for i in range(len(fitresult['result']['ydata'])):
                    file.write("%.7g  %.7g   %.7g  %.7g  %.7g  %.7g" % (fitresult['result']['xdata'][i],
                                       fitresult['result']['energy'][i],
                                       fitresult['result']['ydata'][i],
                                       fitresult['result']['yfit'][i],
                                       fitresult['result']['continuum'][i],
                                       fitresult['result']['pileup'][i]))
                    if 'ymatrix' in fitresult['result'].keys():
                        file.write("  %.7g" %  fitresult['result']['ymatrix'][i])
                    for group in fitresult['result']['groups']:
                        label = 'y'+group
                        if label in keys:
                            file.write("  %.7g" %  fitresult['result'][label][i])
                    file.write("\n")
                file.close()
                return
            if filetype == 'CSV':
                if "," in filterused[0]:
                    csv = ","
                elif ";" in filterused[0]:
                    csv = ";"
                else:
                    csv = "\t"
                keys = fitresult['result'].keys()

                headerLine = '"channel"%s"Energy"%s"counts"%s"fit"%s"continuum"%s"pileup"' % (csv, csv, csv, csv, csv)
                if 'ymatrix' in keys:
                    headerLine += '%s"ymatrix"' % csv

                for group in fitresult['result']['groups']:
                    label = 'y'+group
                    if label in keys:
                        headerLine += csv+ ('"%s"' % group)
                file.write(headerLine)
                file.write('\n')
                for i in range(len(fitresult['result']['ydata'])):
                    file.write("%.7g%s%.7g%s%.7g%s%.7g%s%.7g%s%.7g" % (fitresult['result']['xdata'][i],
                                       csv,
                                       fitresult['result']['energy'][i],
                                       csv,
                                       fitresult['result']['ydata'][i],
                                       csv,
                                       fitresult['result']['yfit'][i],
                                       csv,
                                       fitresult['result']['continuum'][i],
                                       csv,
                                       fitresult['result']['pileup'][i]))
                    if 'ymatrix' in fitresult['result'].keys():
                        file.write("%s%.7g" %  (csv,fitresult['result']['ymatrix'][i]))
                    for group in fitresult['result']['groups']:
                        label = 'y'+group
                        if label in keys:
                            file.write("%s%.7g" %  (csv,fitresult['result'][label][i]))
                    file.write("\n")
                file.close()
                return
            #header is almost common to specfile and mca
            file.write("#F %s\n" % specFile)
            file.write("#D %s\n"%(time.ctime(time.time())))
            file.write("\n")
            legend = str(self.headerLabel.text()).strip('<b>')
            legend.strip('<\b>')
            file.write("#S 1 %s\n" % legend)
            file.write("#D %s\n"%(time.ctime(time.time())))
            i = 0
            for parameter in fitresult['result']['parameters']:
                file.write("#U%d %s %.7g +/- %.3g\n" % (i, parameter,
                                                     fitresult['result']['fittedpar'][i],
                                                     fitresult['result']['sigmapar'][i]))
                i+=1
            if filetype == 'Scan':
                keys = fitresult['result'].keys()
                labelline= "#L channel  Energy  counts  fit  continuum  pileup"
                if 'ymatrix' in keys:
                    nlabels = 7
                    labelline += "ymatrix"
                else:
                    nlabels = 6

                for group in fitresult['result']['groups']:
                    label = 'y'+group
                    if label in keys:
                        nlabels += 1
                        labelline += '  '+group
                file.write("#N %d\n" % nlabels)
                file.write(labelline)
                file.write("\n")
                for i in range(len(fitresult['result']['ydata'])):
                    file.write("%.7g  %.7g  %.7g  %.7g  %.7g  %.7g" % (fitresult['result']['xdata'][i],
                                       fitresult['result']['energy'][i],
                                       fitresult['result']['ydata'][i],
                                       fitresult['result']['yfit'][i],
                                       fitresult['result']['continuum'][i],
                                       fitresult['result']['pileup'][i]))
                    if 'ymatrix' in keys:
                        file.write("  %.7g" % fitresult['result']['ymatrix'][i])
                    for group in fitresult['result']['groups']:
                        label = 'y'+group
                        if label in keys:
                            file.write("  %.7g" %  fitresult['result'][label][i])
                    file.write("\n")
            else:
                file.write("#@MCA %16C\n")
                file.write("#@CHANN %d %d %d 1\n" %  (len(fitresult['result']['ydata']),
                                                        fitresult['result']['xdata'][0],
                                                        fitresult['result']['xdata'][-1]))
                zeroindex = fitresult['result']['parameters'].index('Zero')
                gainindex = fitresult['result']['parameters'].index('Gain')
                file.write("#@CALIB %.7g %.7g 0.0\n" % (fitresult['result']['fittedpar'][zeroindex],
                                                        fitresult['result']['fittedpar'][gainindex]))
                file.write(self.array2SpecMca(fitresult['result']['ydata']))
                file.write(self.array2SpecMca(fitresult['result']['yfit']))
                file.write(self.array2SpecMca(fitresult['result']['continuum']))
                file.write(self.array2SpecMca(fitresult['result']['pileup']))
                keys = fitresult['result'].keys()
                if 'ymatrix' in keys:
                    file.write(self.array2SpecMca(fitresult['result']['ymatrix']))
                for group in fitresult['result']['groups']:
                    label = 'y'+group
                    if label in keys:
                        file.write(self.array2SpecMca(fitresult['result'][label]))
            file.write("\n")
            file.close()
        except:
            os.linesep = systemline
            raise
        return

    def array2SpecMca(self, data):
        """ Write a python array into a Spec array.
            Return the string containing the Spec array
        """
        tmpstr = "@A "
        length = len(data)
        for idx in range(0, length, 16):
            if idx+15 < length:
                for i in range(0,16):
                    tmpstr += "%.4f " % data[idx+i]
                if idx+16 != length:
                    tmpstr += "\\"
            else:
                for i in range(idx, length):
                    tmpstr += "%.4f " % data[i]
            tmpstr += "\n"
        return tmpstr


class Top(qt.QWidget):
    def __init__(self,parent = None,name = None,fl = 0):
        qt.QWidget.__init__(self,parent)
        self.mainLayout= qt.QHBoxLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        self.build()

    def build(self):
        self.__w=qt.QWidget(self)
        w = self.__w
        self.mainLayout.addWidget(w)
        wlayout = qt.QGridLayout(w)
        wlayout.setSpacing(5)
        #function
        FunLabel = qt.QLabel(w)
        FunLabel.setText(str("Function"))
        if QTVERSION < '4.0.0':
            self.FunComBox = qt.QComboBox(0,w,"FunComBox")
            self.FunComBox.insertStrList(["Mca Hypermet"])
            self.FunComBox.insertStrList(["Mca Pseudo-Voigt"])
        else:
            self.FunComBox = qt.QComboBox(w)
            self.FunComBox.insertItem(0, "Mca Hypermet")
            self.FunComBox.insertItem(1, "Mca Pseudo-Voigt")
        wlayout.addWidget(FunLabel,0,0)
        wlayout.addWidget(self.FunComBox,0,1)
        #background
        BkgLabel = qt.QLabel(w)
        BkgLabel.setText(str("Background"))
        if QTVERSION < '4.0.0':
            self.BkgComBox = qt.QComboBox(0,w,"BkgComBox")
            self.BkgComBox.insertStrList(['No Background',
                                          'Constant',
                                          'Linear',
                                          'Parabolic',
                                          'Linear Polynomial',
                                          'Exp. Polynomial'])
        else:
            self.BkgComBox = qt.QComboBox(w)
            options = ['No Background',
                       'Constant',
                       'Linear',
                       'Parabolic',
                       'Linear Polynomial',
                       'Exp. Polynomial']
            for item in options:
                self.BkgComBox.insertItem(options.index(item), item)

        self.connect(self.FunComBox,
                     qt.SIGNAL("activated(int)"),self.mysignal)

        self.connect(self.BkgComBox,
                     qt.SIGNAL("activated(int)"),self.mysignal)
        #                        qt.SIGNAL("activated(const QString &)"),self.bkgevent)
        wlayout.addWidget(BkgLabel,1,0)
        wlayout.addWidget(self.BkgComBox,1,1)
        dummy = qt.QWidget(self)
        dummy.setMinimumSize(20,0)
        self.mainLayout.addWidget(dummy)
        self.mainLayout.addWidget(HorizontalSpacer(self))

        #the checkboxes
        if 0:
             w1 = qt.QVBox(self)
             self.WeightCheckBox = qt.QCheckBox(w1)
             self.WeightCheckBox.setText(str("Weight"))
             self.McaModeCheckBox = qt.QCheckBox(w1)
             self.McaModeCheckBox.setText(str("Mca Mode"))

        # Flags
        f       = qt.QWidget(self)
        self.mainLayout.addWidget(f)
        f.layout= qt.QGridLayout(f)
        f.layout.setSpacing(5)
        flagsoffset = -1
        coffset     = 0
        #hyplabel = qt.QLabel(f)
        #hyplabel.setText(str("<b>%s</b>" % 'FLAGS'))
        self.stbox = qt.QCheckBox(f)
        self.stbox.setText('Short Tail')
        self.ltbox = qt.QCheckBox(f)
        self.ltbox.setText('Long Tail')
        self.stepbox = qt.QCheckBox(f)
        self.stepbox.setText('Step Tail')
        self.escapebox = qt.QCheckBox(f)
        self.escapebox.setText('Escape')
        self.sumbox = qt.QCheckBox(f)
        self.sumbox.setText('Pile-up')
        self.stripbox = qt.QCheckBox(f)
        self.stripbox.setText('Strip Back.')
        #checkbox connections
        self.connect(self.stbox,qt.SIGNAL("clicked()"),     self.mysignal)
        self.connect(self.ltbox,qt.SIGNAL("clicked()"),     self.mysignal)
        self.connect(self.stepbox,qt.SIGNAL("clicked()"),   self.mysignal)
        self.connect(self.escapebox,qt.SIGNAL("clicked()"), self.mysignal)
        self.connect(self.sumbox,qt.SIGNAL("clicked()"),    self.mysignal)
        self.connect(self.stripbox,qt.SIGNAL("clicked()"),  self.mysignal)
        #f.layout.addWidget(hyplabel,flagsoffset,coffset +1)
        f.layout.addWidget(self.stbox,flagsoffset+1,coffset +0)
        f.layout.addWidget(self.ltbox,flagsoffset+1,coffset +1)
        f.layout.addWidget(self.stepbox,flagsoffset+1,coffset +2)
        f.layout.addWidget(self.escapebox,flagsoffset+2,coffset +0)
        f.layout.addWidget(self.sumbox,flagsoffset+2,coffset +1)
        f.layout.addWidget(self.stripbox,flagsoffset+2,coffset +2)
        self.mainLayout.addWidget(HorizontalSpacer(self))

        #buttons
        g = qt.QWidget(self)
        self.mainLayout.addWidget(g)
        glayout = qt.QGridLayout(g)
        glayout.setSpacing(5)
        self.configureButton = qt.QPushButton(g)
        self.configureButton.setText(str("Configure"))
        self.printButton = qt.QPushButton(g)
        self.printButton.setText(str("Tools"))
        glayout.addWidget(self.configureButton,0,0)
        glayout.addWidget(self.printButton,1,0)

    def setParameters(self,ddict=None):
        if ddict == None: ddict = {}
        hypermetflag = ddict.get('hypermetflag', 1)
        if not ('fitfunction' in ddict):
            if hypermetflag:
                ddict['fitfunction'] = 0
            else:
                ddict['fitfunction'] = 1

        if QTVERSION < '4.0.0':
            self.FunComBox.setCurrentItem(ddict['fitfunction'])
        else:
            self.FunComBox.setCurrentIndex(ddict['fitfunction'])

        if 'hypermetflag' in ddict:
            hypermetflag = ddict['hypermetflag']
            if ddict['fitfunction'] == 0:
                g_term    =  hypermetflag & 1
                st_term   = (hypermetflag >>1) & 1
                lt_term   = (hypermetflag >>2) & 1
                step_term = (hypermetflag >>3) & 1
                self.stbox.setEnabled(1)
                self.ltbox.setEnabled(1)
                self.stepbox.setEnabled(1)
                if st_term:
                    self.stbox.setChecked(1)
                else:
                    self.stbox.setChecked(0)
                if lt_term:
                    self.ltbox.setChecked(1)
                else:
                    self.ltbox.setChecked(0)
                if step_term:
                    self.stepbox.setChecked(1)
                else:
                    self.stepbox.setChecked(0)
            else:
                self.stbox.setEnabled(0)
                self.ltbox.setEnabled(0)
                self.stepbox.setEnabled(0)

        key = 'sumflag'
        if key in ddict:
            if ddict[key] == 1:
                self.sumbox.setChecked(1)
            else:
                self.sumbox.setChecked(0)

        key = 'stripflag'
        if key in ddict:
            if ddict[key] == 1:
                self.stripbox.setChecked(1)
            else:
                self.stripbox.setChecked(0)

        key = 'escapeflag'
        if key in ddict:
            if ddict[key] == 1:
                self.escapebox.setChecked(1)
            else:
                self.escapebox.setChecked(0)

        key = 'continuum'
        if key in ddict:
            if QTVERSION < '4.0.0':
                self.BkgComBox.setCurrentItem(ddict[key])
            else:
                self.BkgComBox.setCurrentIndex(ddict[key])

    def getParameters(self):
        ddict={}
        if QTVERSION < '4.0.0':
            index = self.FunComBox.currentItem()
        else:
            index = self.FunComBox.currentIndex()

        ddict['fitfunction'] = index
        ddict['hypermetflag'] = 1
        if index == 0:
            self.stbox.setEnabled(1)
            self.ltbox.setEnabled(1)
            self.stepbox.setEnabled(1)
        else:
            ddict['hypermetflag'] = 0
            self.stbox.setEnabled(0)
            self.ltbox.setEnabled(0)
            self.stepbox.setEnabled(0)

        if self.stbox.isChecked():
            ddict['hypermetflag'] += 2
        if self.ltbox.isChecked():
            ddict['hypermetflag'] += 4

        if self.stepbox.isChecked():
            ddict['hypermetflag'] += 8

        if self.sumbox.isChecked():
            ddict['sumflag'] = 1
        else:
            ddict['sumflag'] = 0

        if self.stripbox.isChecked():
            ddict['stripflag'] = 1
        else:
            ddict['stripflag'] = 0

        if self.escapebox.isChecked():
            ddict['escapeflag'] = 1
        else:
            ddict['escapeflag'] = 0
        if QTVERSION < '4.0.0':
            ddict['continuum'] = self.BkgComBox.currentItem()
        else:
            ddict['continuum'] = self.BkgComBox.currentIndex()
        return ddict

    def mysignal(self,*var):
        ddict = self.getParameters()
        if QTVERSION < '4.0.0':
            self.emit(qt.PYSIGNAL('TopSignal'),(ddict,))
        else:
            self.emit(qt.SIGNAL('TopSignal'),(ddict))

class HorizontalSpacer(qt.QWidget):
    def __init__(self, *args):
        qt.QWidget.__init__(self, *args)

        self.setSizePolicy(qt.QSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed))

class Line(qt.QFrame):
    def __init__(self, parent=None, name="Line", fl=0, info=None):
        qt.QFrame.__init__(self, parent)
        self.info = info
        self.setFrameShape(qt.QFrame.HLine)
        self.setFrameShadow(qt.QFrame.Sunken)
        self.setFrameShape(qt.QFrame.HLine)


    def mouseDoubleClickEvent(self, event):
        if DEBUG:
            print("Double Click Event")
        ddict={}
        ddict['event']="DoubleClick"
        ddict['data'] = event
        ddict['info'] = self.info
        if QTVERSION < '4.0.0':
            self.emit(qt.PYSIGNAL("LineDoubleClickEvent"), (ddict,))
        else:
            self.emit(qt.SIGNAL("LineDoubleClickEvent"), ddict)

class SimpleThread(qt.QThread):
    def __init__(self, function = None, kw = None):
        if kw is None:kw={}
        qt.QThread.__init__(self)
        self._function = function
        self._kw       = kw
        self._result   = None
        self._expandParametersDict = False

    def run(self):
        try:
            if self._expandParametersDict:
                self._result = self._function(**self._kw)
            else:
                self._result = self._function(self._kw)
        except:
            self._result = ("Exception",) + sys.exc_info()


class McaGraphWindow(qt.QWidget):
    def __init__(self, parent=None, name="Toolbar",fl=0):
        qt.QWidget.__init__(self,parent)
        layout = qt.QVBoxLayout(self)
        layout.setMargin(0)
        layout.setSpacing(0)
        self.toolbar = qt.QWidget(self)
        self.toolbar.layout = qt.QHBoxLayout(self.toolbar)
        self.toolbar.layout.setMargin(0)
        self.toolbar.layout.setSpacing(0)
        self.graph   = QtBlissGraph.QtBlissGraph(self)
        self.graph.setPanningMode(True)
        layout.addWidget(self.toolbar)
        layout.addWidget(self.graph)
        self.initToolBar()
        if QTVERSION < '4.0.0':
            self.connect(self.graph,
                         qt.PYSIGNAL('QtBlissGraphSignal'),
                         self.__graphSignal)
        else:
            self.connect(self.graph,
                         qt.SIGNAL('QtBlissGraphSignal'),
                         self.__graphSignal)

        self.printPreview = PyMcaPrintPreview.PyMcaPrintPreview(modal = 0)
        if DEBUG:
            print("printPreview id = ", id(self.printPreview))

    def __roiSlot(self,dict=None):
        if dict is None:
            self.roimarkers = [-1, -1]
            self.roilist    = ['Integral']
            self.roidict    = {}
            self.roidict['Integral'] = {'type':'Default',
                                        'from':0,'to':-1}
            self.currentroi = None
            self.roiwidget.fillfromroidict(roilist=self.roilist,
                                       roidict=self.roidict)
        elif dict['event'] == 'AddROI':
            xmin,xmax = self.graph.getx1axislimits()
            fromdata = xmin+ 0.25 * (xmax - xmin)
            todata   = xmin+ 0.75 * (xmax - xmin)
            if self.roimarkers[0] < 0:
                self.roimarkers[0] = self.graph.insertx1marker(fromdata,1.1,
                                        label = 'ROI min')
            if self.roimarkers[1] < 0:
                self.roimarkers[1] = self.graph.insertx1marker(todata,1.1,
                                        label = 'ROI max')
            self.graph.setmarkercolor(self.roimarkers[0],'blue')
            self.graph.setmarkercolor(self.roimarkers[1],'blue')
            self.graph.replot()
            #if self.roilist is None:
            self.roilist,self.roidict = self.roiwidget.getroilistanddict()
            nrois = len(self.roilist)
            for i in range(nrois):
                i += 1
                newroi = "newroi %d" % i
                if newroi not in self.roilist:
                    break
            self.roilist.append(newroi)
            self.roidict[newroi] = {}
            self.roidict[newroi]['type']    = str(self.graph.xlabel())
            self.roidict[newroi]['from']    = fromdata
            self.roidict[newroi]['to']      = todata
            self.roiwidget.fillfromroidict(roilist=self.roilist,
                                           roidict=self.roidict,
                                           currentroi=newroi)
            self.currentroi = newroi

        elif dict['event'] == 'DelROI':
            self.roilist,self.roidict = self.roiwidget.getroilistanddict()
            self.currentroi = self.roidict.keys()[0]
            self.roiwidget.fillfromroidict(roilist=self.roilist,
                                           roidict=self.roidict,
                                           currentroi=self.currentroi)

        elif dict['event'] == 'ResetROI':
            self.roilist,self.roidict = self.roiwidget.getroilistanddict()
            self.currentroi = self.roidict.keys()[0]
            self.roiwidget.fillfromroidict(roilist=self.roilist,
                                           roidict=self.roidict,
                                           currentroi=self.currentroi)
            self.graph.clearmarkers()
        elif dict['event'] == 'ActiveROI':
            print("ActiveROI event")
            pass
        ndict = {}
        ndict['event']  = "SetActiveCurveEvent"
        self.__graphSignal(ndict)

    def initIcons(self):
        if QTVERSION > '4.0.0':qt.QIconSet = qt.QIcon
        self.normalIcon = qt.QIconSet(qt.QPixmap(IconDict["normal"]))
        self.zoomIcon   = qt.QIconSet(qt.QPixmap(IconDict["zoom"]))
        self.roiIcon    = qt.QIconSet(qt.QPixmap(IconDict["roi"]))
        self.peakIcon   = qt.QIconSet(qt.QPixmap(IconDict["peak"]))

        self.zoomResetIcon  = qt.QIconSet(qt.QPixmap(IconDict["zoomreset"]))
        self.roiResetIcon   = qt.QIconSet(qt.QPixmap(IconDict["roireset"]))
        self.peakResetIcon  = qt.QIconSet(qt.QPixmap(IconDict["peakreset"]))
        self.refreshIcon    = qt.QIconSet(qt.QPixmap(IconDict["reload"]))

        self.logxIcon   = qt.QIconSet(qt.QPixmap(IconDict["logx"]))
        self.logyIcon   = qt.QIconSet(qt.QPixmap(IconDict["logy"]))
        self.energyIcon = qt.QIconSet(qt.QPixmap(IconDict["energy"]))
        self.xAutoIcon  = qt.QIconSet(qt.QPixmap(IconDict["xauto"]))
        self.yAutoIcon  = qt.QIconSet(qt.QPixmap(IconDict["yauto"]))
        self.fitIcon    = qt.QIconSet(qt.QPixmap(IconDict["fit"]))
        self.deriveIcon = qt.QIconSet(qt.QPixmap(IconDict["derive"]))
        self.saveIcon   = qt.QIconSet(qt.QPixmap(IconDict["filesave"]))
        self.printIcon  = qt.QIconSet(qt.QPixmap(IconDict["fileprint"]))
        self.searchIcon = qt.QIconSet(qt.QPixmap(IconDict["peaksearch"]))


    def initToolBar(self):
        toolbar = self.toolbar
        self.initIcons()
        # AutoScale
        self._addToolButton(self.zoomResetIcon,
                            self.graph.ResetZoom,
                            'Auto-Scale the Graph')

        #y Autoscale
        self._addToolButton(self.yAutoIcon,
                            self._yAutoScaleToggle,
                            'Toggle Autoscale Y Axis (On/Off)',
                            toggle=1,
                            state=1)

        #x Autoscale
        self._addToolButton(self.xAutoIcon,
                            self._xAutoScaleToggle,
                            'Toggle Autoscale X Axis (On/Off)',
                            toggle=True,
                            state=1)
        # Logarithmic
        self._addToolButton(self.logyIcon,
                            self._logIconSignal,
                            'Toggle Logarithmic Y Axis (On/Off)',
                            toggle=True)

        # Energy
        self._addToolButton(self.energyIcon,
                            self._energyIconSignal,
                            'Toggle Energy Axis (On/Off)',
                            toggle=True)
        # Fit
        self._addToolButton(self.fitIcon,
                            self._fitIconSignal,
                            'Fit Again!')

        # ROI
        self.roiwidget = None
        """
        self._initRoi()
        self.roiwidget.hide()
        tb      = qt.QToolButton(toolbar)
        tb.setIconSet(self.roiIcon)
        self.connect(tb,qt.SIGNAL('clicked()'),self._roiIconSignal)
        qt.QToolTip.add(tb,'Show ROI Widget')
        """

        #save
        self._addToolButton(self.saveIcon,
                            self._saveIconSignal,
                            'Save Curves')

        # Search
        """
        tb      = qt.QToolButton(toolbar)
        tb.setIconSet(self.searchIcon)
        self.connect(tb,qt.SIGNAL('clicked()'),self.peaksearch)
        qt.QToolTip.add(tb,'Clear Peak Table and Search Peaks')
        # Marker
        self.markerButton      = qt.QToolButton(toolbar)
        self.markerButton.setIconSet(self.normalIcon)
        self.markerButton.setToggleButton(1)
        self.connect(self.markerButton,qt.SIGNAL('clicked()'),self.__peakmarkermode)
        qt.QToolTip.add(self.markerButton,'Allow Right-Click Peak Selection from Graph')
        """
        self.toolbar.layout.addWidget(HorizontalSpacer(toolbar))
        label=qt.QLabel(toolbar)
        #label.setText('<b>Channel:</b>')
        label.setText('<b>X:</b>')
        self.xpos = qt.QLineEdit(toolbar)
        self.xpos.setText('------')
        self.xpos.setReadOnly(1)
        self.xpos.setFixedWidth(self.xpos.fontMetrics().width('#########'))
        self.toolbar.layout.addWidget(label)
        self.toolbar.layout.addWidget(self.xpos)

        label=qt.QLabel(toolbar)
        label.setText('<b>Y:</b>')
        self.ypos = qt.QLineEdit(toolbar)
        self.ypos.setText('------')
        self.ypos.setReadOnly(1)
        self.ypos.setFixedWidth(self.ypos.fontMetrics().width('############'))
        self.toolbar.layout.addWidget(label)
        self.toolbar.layout.addWidget(self.ypos)

        """
        label=qt.QLabel(toolbar)
        label.setText('<b>Energy:</b>')
        self.epos = qt.QLineEdit(toolbar)
        self.epos.setText('------')
        self.epos.setReadOnly(1)
        self.epos.setFixedWidth(self.epos.fontMetrics().width('########'))
        """
        self.toolbar.layout.addWidget(HorizontalSpacer(toolbar))
        # ---print
        if 0:
            self._addToolButton(self.printIcon,
                            self.graph.printps,
                            'Prints the Graph')
        else:
            tb = self._addToolButton(self.printIcon,
                    self.printGraph,
                    'Print the graph')
            toolbar.layout.addWidget(tb)

    def printGraph(self):
        pixmap = qt.QPixmap.grabWidget(self.graph)
        self.printPreview.addPixmap(pixmap)
        if self.printPreview.isHidden():
            self.printPreview.show()
        if QTVERSION < '4.0.0':
            self.printPreview.raiseW()
        else:
            self.printPreview.raise_()

    def _addToolButton(self, icon, action, tip, toggle=None, state=None):
            toolbar = self.toolbar
            tb      = qt.QToolButton(toolbar)
            if QTVERSION < '4.0.0':
                tb.setIconSet(icon)
                qt.QToolTip.add(tb,tip)
                if toggle is not None:
                    if toggle:
                        tb.setToggleButton(1)
                        if state is not None:
                            if state:
                                tb.setState(qt.QButton.On)

            else:
                tb.setIcon(icon)
                tb.setToolTip(tip)
                if toggle is not None:
                    if toggle:
                        tb.setCheckable(1)
                        if state is not None:
                            if state:
                                tb.setChecked(state)
                        else:
                            tb.setChecked(False)
            self.toolbar.layout.addWidget(tb)
            self.connect(tb,qt.SIGNAL('clicked()'), action)
            return tb

    def _yAutoScaleToggle(self):
        if self.graph.yAutoScale:
            self.graph.yAutoScale = False
        else:
            self.graph.yAutoScale = True

    def _xAutoScaleToggle(self):
        if self.graph.xAutoScale:
            self.graph.xAutoScale = False
        else:
            self.graph.xAutoScale = True

    def _energyIconSignal(self):
        legend = self.graph.getactivecurve(justlegend=1)
        dict={}
        dict['event']  = 'EnergyClicked'
        dict['active'] = legend
        if QTVERSION < '4.0.0':
            self.emit(qt.PYSIGNAL('McaGraphSignal'),(dict,))
        else:
            self.emit(qt.SIGNAL('McaGraphSignal'), (dict))

    def _logIconSignal(self):
        legend = self.graph.getactivecurve(justlegend=1)
        dict={}
        dict['event']  = 'LogClicked'
        dict['active'] = legend
        if QTVERSION < '4.0.0':
            self.emit(qt.PYSIGNAL('McaGraphSignal'),(dict,))
        else:
            self.emit(qt.SIGNAL('McaGraphSignal'), (dict))

    def _fitIconSignal(self):
        legend = self.graph.getactivecurve(justlegend=1)
        dict={}
        dict['event']  = 'FitClicked'
        dict['active'] = legend
        if QTVERSION < '4.0.0':
            self.emit(qt.PYSIGNAL('McaGraphSignal'),(dict,))
        else:
            self.emit(qt.SIGNAL('McaGraphSignal'), (dict))

    def _initRoi(self):
        self.roiwidget = McaROIWidget.McaROIWidget(None)
        if QTVERSION < '4.0.0':
            self.connect(self.roiwidget,qt.PYSIGNAL("McaROIWidgetSignal"),
                     self.__roiSlot)
        else:
            self.connect(self.roiwidget,qt.SIGNAL("McaROIWidgetSignal"),
                     self.__roiSlot)
        self.__roiSlot()

    def _roiIconSignal(self):
        if self.roiwidget is None:self._initRoi()
        if self.roiwidget.isHidden():self.roiwidget.show()
        if QTVERSION < '4.0.0':
            self.roiwidget.raiseW()
        else:
            self.roiwidget.raise_()
        legend = self.graph.getactivecurve(justlegend=1)
        ddict={}
        ddict['event']  = 'RoiClicked'
        ddict['active'] = legend
        if QTVERSION < '4.0.0':
            self.emit(qt.PYSIGNAL('McaGraphSignal'), (ddict,))
        else:
            self.emit(qt.SIGNAL('McaGraphSignal'), (ddict))

    def _saveIconSignal(self):
        legend = self.graph.getactivecurve(justlegend=1)
        ddict={}
        ddict['event']  = 'SaveClicked'
        ddict['active'] = legend
        if QTVERSION < '4.0.0':
            self.emit(qt.PYSIGNAL('McaGraphSignal'), (ddict,))
        else:
            self.emit(qt.SIGNAL('McaGraphSignal'), (ddict))

    def __graphSignal(self, dict):
        if dict['event'] == 'MouseAt':
            self.xpos.setText('%.4g' % dict['x'])
            self.ypos.setText('%.5g' % dict['y'])
        elif dict['event'] == 'MouseClick':
            if QTVERSION < '4.0.0':
                self.emit(qt.PYSIGNAL('McaGraphSignal'),(dict,))
            else:
                self.emit(qt.SIGNAL('McaGraphSignal'), (dict))
        elif dict['event'] == "SetActiveCurveEvent":
            legend = dict.get('legend', None)
            if (legend is not None) and (self.roiwidget is not None):
                legend,x,y = self.graph.getactivecurve()
                #if self.roidict is None:
                self.roilist,self.roidict = self.roiwidget.getroilistanddict()
                if not len(x):
                    #only zeros ...
                    for i in range(len(self.roilist)):
                        key = self.roilist[i]
                        self.roidict[key]['rawcounts'] = 0.0
                        self.roidict[key]['netcounts'] = 0.0
                        #self.roidict[key]['from'  ] = 0.0
                        #self.roidict[key]['to'    ] = 0.0
                else:
                    for i in range(len(self.roilist)):
                        key = self.roilist[i]
                        if key == self.roilist[0]:
                            #take care of LLD
                            #if len(x) > 3:
                            #    fromdata = x[3]
                            #else:
                            fromdata = x[0]
                            todata   = x[-1]
                        else:
                            fromdata = self.roidict[key]['from']
                            todata   = self.roidict[key]['to']
                        i1 = Numeric.nonzero(x>=fromdata)
                        xw = Numeric.take(x,i1)
                        yw = Numeric.take(y,i1)
                        i1 = Numeric.nonzero(xw<=todata)
                        xw = Numeric.take(xw,i1)
                        yw = Numeric.take(yw,i1)
                        counts = Numeric.sum(yw)
                        self.roidict[key]['rawcounts'] = counts
                        if len(yw):
                            self.roidict[key]['netcounts'] = counts - \
                                                      len(yw) *  0.5 * (yw[0] + yw[-1])
                        else:
                            self.roidict[key]['netcounts'] = 0
                        self.roidict[key]['from'  ] = fromdata
                        self.roidict[key]['to'    ] = todata
                xlabel = self.graph.xlabel()
                #self.roiwidget.setheader(text="%s ROIs of %s" % (xlabel,legend))
                self.roiwidget.setHeader(text="ROIs of %s" % (legend))
                self.roiwidget.fillfromroidict(roilist=self.roilist,
                                                roidict=self.roidict)




def test(file='03novs060sum.mca'):
    import specfilewrapper as specfile
    app = qt.QApplication([])
    app.connect(app, qt.SIGNAL("lastWindowClosed()"), app.quit)
    sf=specfile.Specfile(file)
    scan=sf[0]
    mcadata=scan.mca(1)
    y0= Numeric.array(mcadata)
    x = Numeric.arange(len(y0))*1.0
    demo = McaAdvancedFit()
    xmin = demo.mcafit.config['fit']['xmin']
    xmax = demo.mcafit.config['fit']['xmax']
    demo.setData(x,y0,xmin=xmin,xmax=xmax,sourcename=file)
    if QTVERSION < '4.0.0':
        app.setMainWidget(demo)
        demo.show()
        app.exec_loop()
    else:
        #This illustrates how to change the configuration
        #oldConfig = demo.configure()
        #oldConfig['fit']['xmin'] = 123
        #demo.configure(oldConfig)
        demo.show()
        app.exec_()


def main():
    app = qt.QApplication([])
    form = McaAdvancedFit(top=False)
    form.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    import sys
    if len(sys.argv) >1:
        ffile = sys.argv[1]
    else:
        ffile = '03novs060sum.mca'
    if os.path.exists(ffile):
        test(ffile)
    else:
        main()