File: papi.c

package info (click to toggle)
papi 5.7.0+dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 9,856 kB
  • sloc: ansic: 93,265; fortran: 3,338; xml: 2,460; makefile: 815; sh: 290
file content (6733 lines) | stat: -rw-r--r-- 220,202 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
/****************************/
/* THIS IS OPEN SOURCE CODE */
/****************************/

/** 
* @file:    papi.c
*
* @author:  Philip Mucci
*          mucci@cs.utk.edu
* @author    dan terpstra
*          terpstra@cs.utk.edu
* @author    Min Zhou
*          min@cs.utk.edu
* @author  Kevin London
*	   london@cs.utk.edu
* @author  Per Ekman
*          pek@pdc.kth.se
* Mods:    Gary Mohr
*          gary.mohr@bull.com
*
* @brief Most of the low-level API is here.
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h> 

#include "papi.h"
#include "papi_internal.h"
#include "papi_vector.h"
#include "papi_memory.h"
#include "papi_preset.h"

#include "cpus.h"
#include "extras.h"
#include "sw_multiplex.h"
#include "papi_hl.h"

/*******************************/
/* BEGIN EXTERNAL DECLARATIONS */
/*******************************/


extern hwi_presets_t user_defined_events[PAPI_MAX_USER_EVENTS];
extern int user_defined_events_count;


#ifdef DEBUG
#define papi_return(a) do { \
	int b = a; \
	if (b != PAPI_OK) {\
		_papi_hwi_errno = b;\
	} \
	APIDBG("EXIT: return: %d\n", b);\
	return((_papi_hwi_debug_handler ? _papi_hwi_debug_handler(b) : b)); \
} while (0)
#else
#define papi_return(a) do { \
	int b = a; \
	if (b != PAPI_OK) {\
		_papi_hwi_errno = b;\
	} \
	APIDBG("EXIT: return: %d\n", b);\
	return(b);\
} while(0)
#endif


/*
#ifdef DEBUG
#define papi_return(a) return((_papi_hwi_debug_handler ? _papi_hwi_debug_handler(a) : a))
#else
#define papi_return(a) return(a)
#endif
*/

#ifdef DEBUG
int _papi_hwi_debug;
#endif


static int init_retval = DEADBEEF;

inline_static int
valid_component( int cidx )
{
	if ( _papi_hwi_invalid_cmp( cidx ) )
		return ( PAPI_ENOCMP );
	return ( cidx );
}

inline_static int
valid_ESI_component( EventSetInfo_t * ESI )
{
	return ( valid_component( ESI->CmpIdx ) );
}

/** @class	PAPI_thread_init
 *  @brief Initialize thread support in the PAPI library.
 *
 *	@param *id_fn 
 *		Pointer to a function that returns current thread ID. 
 *
 *	PAPI_thread_init initializes thread support in the PAPI library. 
 *	Applications that make no use of threads do not need to call this routine. 
 *	This function MUST return a UNIQUE thread ID for every new thread/LWP created. 
 *	The OpenMP call omp_get_thread_num() violates this rule, as the underlying 
 *	LWPs may have been killed off by the run-time system or by a call to omp_set_num_threads() . 
 *	In that case, it may still possible to use omp_get_thread_num() in 
 *	conjunction with PAPI_unregister_thread() when the OpenMP thread has finished. 
 *	However it is much better to use the underlying thread subsystem's call, 
 *	which is pthread_self() on Linux platforms. 
 *
 *	@code
if ( PAPI_thread_init(pthread_self) != PAPI_OK )
	exit(1);
 *	@endcode
 *
 *	@see PAPI_register_thread PAPI_unregister_thread PAPI_get_thr_specific PAPI_set_thr_specific PAPI_thread_id PAPI_list_threads
 */
int
PAPI_thread_init( unsigned long int ( *id_fn ) ( void ) )
{
	/* Thread support not implemented on Alpha/OSF because the OSF pfm
	 * counter device driver does not support per-thread counters.
	 * When this is updated, we can remove this if statement
	 */
	if ( init_level == PAPI_NOT_INITED )
		papi_return( PAPI_ENOINIT );

	if ( ( init_level & PAPI_THREAD_LEVEL_INITED ) )
		papi_return( PAPI_OK );

	init_level |= PAPI_THREAD_LEVEL_INITED;
	papi_return( _papi_hwi_set_thread_id_fn( id_fn ) );
}

/** @class PAPI_thread_id
 *  @brief Get the thread identifier of the current thread.
 *
 *	@retval PAPI_EMISC 
 *		is returned if there are no threads registered.
 *	@retval -1 
 *		is returned if the thread id function returns an error. 
 *
 *	This function returns a valid thread identifier. 
 *	It calls the function registered with PAPI through a call to 
 *	PAPI_thread_init().
 *
 *	@code
unsigned long tid;

if ((tid = PAPI_thread_id()) == (unsigned long int)-1 )
	exit(1);

printf("Initial thread id is: %lu\n", tid );
 *	@endcode
 *	@see PAPI_thread_init
 */
unsigned long
PAPI_thread_id( void )
{
	if ( _papi_hwi_thread_id_fn != NULL )
		return ( ( *_papi_hwi_thread_id_fn ) (  ) );
	else
#ifdef DEBUG
	if ( _papi_hwi_debug_handler )
		return ( unsigned long ) _papi_hwi_debug_handler( PAPI_EMISC );
#endif
	return ( unsigned long ) PAPI_EMISC;
}

/* Thread Functions */

/* 
 * Notify PAPI that a thread has 'appeared'
 * We lookup the thread, if it does not exist we create it
 */

/** @class PAPI_register_thread
 *  @brief Notify PAPI that a thread has 'appeared'.
 *
 *  @par C Interface:
 *  \#include <papi.h> @n
 *  int PAPI_register_thread (void);
 *
 *  PAPI_register_thread() should be called when the user wants to force 
 *  PAPI to initialize a thread that PAPI has not seen before. 
 *
 *  Usually this is not necessary as PAPI implicitly detects the thread when 
 *  an eventset is created or other thread local PAPI functions are called. 
 *  However, it can be useful for debugging and performance enhancements 
 *  in the run-time systems of performance tools. 
 *
 *  @retval PAPI_ENOMEM 
 *	Space could not be allocated to store the new thread information.
 *  @retval PAPI_ESYS 
 *	A system or C library call failed inside PAPI, see the errno variable.
 *  @retval PAPI_ECMP 
 *	Hardware counters for this thread could not be initialized. 
 *
 *   @see PAPI_unregister_thread 
 *   @see PAPI_thread_id 
 *   @see PAPI_thread_init
 */
int
PAPI_register_thread( void )
{
	ThreadInfo_t *thread;

	if ( init_level == PAPI_NOT_INITED )
		papi_return( PAPI_ENOINIT );
	papi_return( _papi_hwi_lookup_or_create_thread( &thread, 0 ) );
}

/* 
 * Notify PAPI that a thread has 'disappeared'
 * We lookup the thread, if it does not exist we return an error
 */
/** @class PAPI_unregister_thread
 *  @brief Notify PAPI that a thread has 'disappeared'.
 *
 *	@retval PAPI_ENOMEM 
 *		Space could not be allocated to store the new thread information.
 *	@retval PAPI_ESYS 
 *		A system or C library call failed inside PAPI, see the errno variable.
 *	@retval PAPI_ECMP 
 *		Hardware counters for this thread could not be initialized. 
 *
 *	PAPI_unregister_thread should be called when the user wants to shutdown 
 *	a particular thread and free the associated thread ID. 
 *	THIS IS IMPORTANT IF YOUR THREAD LIBRARY REUSES THE SAME THREAD ID FOR A NEW KERNEL LWP. 
 *	OpenMP does this. OpenMP parallel regions, if separated by a call to 
 *	omp_set_num_threads() will often kill off the underlying kernel LWPs and 
 *	then start new ones for the next region. 
 *	However, omp_get_thread_id() does not reflect this, as the thread IDs 
 *	for the new LWPs will be the same as the old LWPs. 
 *	PAPI needs to know that the underlying LWP has changed so it can set up 
 *	the counters for that new thread. 
 *	This is accomplished by calling this function. 
 */
int
PAPI_unregister_thread( void )
{
	ThreadInfo_t *thread = _papi_hwi_lookup_thread( 0 );

	if ( thread )
		papi_return( _papi_hwi_shutdown_thread( thread, 0 ) );

	papi_return( PAPI_EMISC );
}

/** @class PAPI_list_threads
 *  @brief List the registered thread ids.
 *
 *  PAPI_list_threads() returns to the caller a list of all thread IDs 
 *  known to PAPI.
 *
 *  This call assumes an initialized PAPI library. 
 *
 * @par C Interface
 * \#include <papi.h> @n
 * int PAPI_list_threads(PAPI_thread_id_t *tids, int * number );
 *
 * @param[in,out] *tids
 *		-- A pointer to a preallocated array. 
 *		This may be NULL to only return a count of threads. 
 *		No more than *number codes will be stored in the array.
 * @param[in,out] *number
 *		-- An input and output parameter.  
 *              Input specifies the number of allocated elements in *tids 
 *              (if non-NULL) and output specifies the number of threads. 
 *
 * @retval PAPI_OK The call returned successfully.
 * @retval PAPI_EINVAL *number has an improper value
 *
 * @see PAPI_get_thr_specific 
 * @see PAPI_set_thr_specific 
 * @see PAPI_register_thread 
 * @see PAPI_unregister_thread 
 * @see PAPI_thread_init PAPI_thread_id
 *
 */
int
PAPI_list_threads( PAPI_thread_id_t *tids, int *number )
{
	PAPI_all_thr_spec_t tmp;
	int retval;

	/* If tids == NULL, then just count the threads, don't gather a list. */
	/* If tids != NULL, then we need the length of the tids array in num. */

	if ( ( number == NULL ) || ( tids && ( *number <= 0 ) ) )
		papi_return( PAPI_EINVAL );

	memset( &tmp, 0x0, sizeof ( tmp ) );

	/* data == NULL, since we don't want the thread specific pointers. */
	/* tids may be NULL, if the user doesn't want the thread IDs. */

	tmp.num = *number;
	tmp.id = tids;
	tmp.data = NULL;

	retval = _papi_hwi_gather_all_thrspec_data( 0, &tmp );
	if ( retval == PAPI_OK )
		*number = tmp.num;

	papi_return( retval );
}

/** @class PAPI_get_thr_specific
 *  @brief Retrieve a pointer to a thread specific data structure.
 *
 *	@par Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_get_thr_specific( int tag, void **ptr );
 *
 *	@param tag
 *		An identifier, the value of which is either PAPI_USR1_TLS or 
 *		PAPI_USR2_TLS. This identifier indicates which of several data 
 *		structures associated with this thread is to be accessed.
 *	@param ptr
 *		A pointer to the memory containing the data structure. 
 *
 *	@retval PAPI_OK
 *	@retval PAPI_EINVAL 
 *		The @em tag argument is out of range. 
 *
 *	In C, PAPI_get_thr_specific PAPI_get_thr_specific will retrieve the pointer from the array with index @em tag. 
 *	There are 2 user available locations and @em tag can be either 
 *	PAPI_USR1_TLS or PAPI_USR2_TLS. 
 *	The array mentioned above is managed by PAPI and allocated to each 
 *	thread which has called PAPI_thread_init. 
 *	There is no Fortran equivalent function. 
 *
 *	@par Example:
 *	@code
 int ret;
 HighLevelInfo *state = NULL;
 ret = PAPI_thread_init(pthread_self);
 if (ret != PAPI_OK) handle_error(ret);
 
 // Do we have the thread specific data setup yet?

ret = PAPI_get_thr_specific(PAPI_USR1_TLS, (void *) &state);
if (ret != PAPI_OK || state == NULL) {
	state = (HighLevelInfo *) malloc(sizeof(HighLevelInfo));
	if (state == NULL) return (PAPI_ESYS);
	memset(state, 0, sizeof(HighLevelInfo));
	state->EventSet = PAPI_NULL;
	ret = PAPI_create_eventset(&state->EventSet);
	if (ret != PAPI_OK) return (PAPI_ESYS);
	ret = PAPI_set_thr_specific(PAPI_USR1_TLS, state);
	if (ret != PAPI_OK) return (ret);
}
*	@endcode
*	@see PAPI_register_thread PAPI_thread_init PAPI_thread_id PAPI_set_thr_specific
*/
int
PAPI_get_thr_specific( int tag, void **ptr )
{
	ThreadInfo_t *thread;
	int doall = 0, retval = PAPI_OK;

	if ( init_level == PAPI_NOT_INITED )
		papi_return( PAPI_ENOINIT );
	if ( tag & PAPI_TLS_ALL_THREADS ) {
		tag = tag ^ PAPI_TLS_ALL_THREADS;
		doall = 1;
	}
	if ( ( tag < 0 ) || ( tag > PAPI_TLS_NUM ) )
		papi_return( PAPI_EINVAL );

	if ( doall )
		papi_return( _papi_hwi_gather_all_thrspec_data
					 ( tag, ( PAPI_all_thr_spec_t * ) ptr ) );

	retval = _papi_hwi_lookup_or_create_thread( &thread, 0 );
	if ( retval == PAPI_OK )
		*ptr = thread->thread_storage[tag];
	else
		papi_return( retval );

	return ( PAPI_OK );
}

/** @class PAPI_set_thr_specific
 *  @brief Store a pointer to a thread specific data structure.
 *
 *	@par Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_set_thr_specific( int tag, void *ptr );
 *
 *	@param tag
 *		An identifier, the value of which is either PAPI_USR1_TLS or 
 *		PAPI_USR2_TLS. This identifier indicates which of several data 
 *		structures associated with this thread is to be accessed.
 *	@param ptr
 *		A pointer to the memory containing the data structure. 
 *
 *	@retval PAPI_OK
 *	@retval PAPI_EINVAL 
 *		The @em tag argument is out of range. 
 *
 *	In C, PAPI_set_thr_specific will save @em ptr into an array indexed by @em tag. 
 *	There are 2 user available locations and @em tag can be either 
 *	PAPI_USR1_TLS or PAPI_USR2_TLS. 
 *	The array mentioned above is managed by PAPI and allocated to each 
 *	thread which has called PAPI_thread_init. 
 *	There is no Fortran equivalent function. 
 *
 *	@par Example:
 *	@code
int ret;
HighLevelInfo *state = NULL;
ret = PAPI_thread_init(pthread_self);
if (ret != PAPI_OK) handle_error(ret);
 
// Do we have the thread specific data setup yet?

ret = PAPI_get_thr_specific(PAPI_USR1_TLS, (void *) &state);
if (ret != PAPI_OK || state == NULL) {
	state = (HighLevelInfo *) malloc(sizeof(HighLevelInfo));
	if (state == NULL) return (PAPI_ESYS);
	memset(state, 0, sizeof(HighLevelInfo));
	state->EventSet = PAPI_NULL;
	ret = PAPI_create_eventset(&state->EventSet);
	if (ret != PAPI_OK) return (PAPI_ESYS);
	ret = PAPI_set_thr_specific(PAPI_USR1_TLS, state);
	if (ret != PAPI_OK) return (ret);
}
 *	@endcode
 *	@see PAPI_register_thread PAPI_thread_init PAPI_thread_id PAPI_get_thr_specific
 */
int
PAPI_set_thr_specific( int tag, void *ptr )
{
	ThreadInfo_t *thread;
	int retval = PAPI_OK;

	if ( init_level == PAPI_NOT_INITED )
		papi_return( PAPI_ENOINIT );
	if ( ( tag < 0 ) || ( tag > PAPI_NUM_TLS ) )
		papi_return( PAPI_EINVAL );

	retval = _papi_hwi_lookup_or_create_thread( &thread, 0 );
	if ( retval == PAPI_OK ) {
	   _papi_hwi_lock( THREADS_LOCK );
	   thread->thread_storage[tag] = ptr;
	   _papi_hwi_unlock( THREADS_LOCK );
	}
	else
		return ( retval );

	return ( PAPI_OK );
}


/** 	@class PAPI_library_init
 *	@brief initialize the PAPI library. 
 *	@param version 
 *		upon initialization, PAPI checks the argument against the internal 
 *		value of PAPI_VER_CURRENT when the library was compiled. 
 *		This guards against portability problems when updating the PAPI shared 
 *		libraries on your system. 
 *
 *	@retval PAPI_EINVAL 
 *		papi.h is different from the version used to compile the PAPI library.
 *	@retval PAPI_ENOMEM 
 *		Insufficient memory to complete the operation.
 *	@retval PAPI_ECMP 
 *		This component does not support the underlying hardware.
 *	@retval PAPI_ESYS 
 *		A system or C library call failed inside PAPI, see the errno variable. 
 *
 *	PAPI_library_init() initializes the PAPI library. 
 *	PAPI_is_initialized() check for initialization.
 *	It must be called before any low level PAPI functions can be used. 
 *	If your application is making use of threads PAPI_thread_init must also be 
 *	called prior to making any calls to the library other than PAPI_library_init() . 
 *	@par Examples:
 *	@code
 *		int retval;
 *		retval = PAPI_library_init(PAPI_VER_CURRENT);
 *		if (retval != PAPI_VER_CURRENT && retval > 0) {
 *			fprintf(stderr,"PAPI library version mismatch!\en");
 *			exit(1); }
 *		if (retval < 0)
 *			handle_error(retval);
 *		retval = PAPI_is_initialized();
 *		if (retval != PAPI_LOW_LEVEL_INITED)
 *			handle_error(retval)	
 *	@endcode
 *	@bug If you don't call this before using any of the low level PAPI calls, your application could core dump.
 *	@see PAPI_thread_init PAPI
 */
int
PAPI_library_init( int version )
{
    APIDBG( "Entry: version: %#x\n", version);

	int tmp = 0;

	/* This is a poor attempt at a lock. 
	   For 3.1 this should be replaced with a 
	   true UNIX semaphore. We cannot use PAPI
	   locks here because they are not initialized yet */
	static int _in_papi_library_init_cnt = 0;
#ifdef DEBUG
	char *var;
#endif
	_papi_hwi_init_errors();

	if ( version != PAPI_VER_CURRENT )
		papi_return( PAPI_EINVAL );

	++_in_papi_library_init_cnt;
	while ( _in_papi_library_init_cnt > 1 ) {
		PAPIERROR( "Multiple callers of PAPI_library_init" );
		sleep( 1 );
	}

	/* This checks to see if we have forked or called init more than once.
	   If we have forked, then we continue to init. If we have not forked, 
	   we check to see the status of initialization. */

	APIDBG( "Initializing library: current PID %d, old PID %d\n", 
                getpid(  ), _papi_hwi_system_info.pid );

	if ( _papi_hwi_system_info.pid == getpid(  ) ) {
		/* If the magic environment variable PAPI_ALLOW_STOLEN is set,
		   we call shutdown if PAPI has been initialized. This allows
		   tools that use LD_PRELOAD to run on applications that use PAPI.
		   In this circumstance, PAPI_ALLOW_STOLEN will be set to 'stolen'
		   so the tool can check for this case. */

		if ( getenv( "PAPI_ALLOW_STOLEN" ) ) {
			char buf[PAPI_HUGE_STR_LEN];
			if ( init_level != PAPI_NOT_INITED )
				PAPI_shutdown(  );
			sprintf( buf, "%s=%s", "PAPI_ALLOW_STOLEN", "stolen" );
			putenv( buf );
		}

		/* If the library has been successfully initialized *OR*
		   the library attempted initialization but failed. */

		else if ( ( init_level != PAPI_NOT_INITED ) ||
				  ( init_retval != DEADBEEF ) ) {
			_in_papi_library_init_cnt--;
			if ( init_retval < PAPI_OK )
				papi_return( init_retval );
			else
				return ( init_retval );
		}

		APIDBG( "system_info was initialized, but init did not succeed\n" );
	}
#ifdef DEBUG
	var = ( char * ) getenv( "PAPI_DEBUG" );
	_papi_hwi_debug = 0;

	if ( var != NULL ) {
		if ( strlen( var ) != 0 ) {
			if ( strstr( var, "SUBSTRATE" ) )
				_papi_hwi_debug |= DEBUG_SUBSTRATE;
			if ( strstr( var, "API" ) )
				_papi_hwi_debug |= DEBUG_API;
			if ( strstr( var, "INTERNAL" ) )
				_papi_hwi_debug |= DEBUG_INTERNAL;
			if ( strstr( var, "THREADS" ) )
				_papi_hwi_debug |= DEBUG_THREADS;
			if ( strstr( var, "MULTIPLEX" ) )
				_papi_hwi_debug |= DEBUG_MULTIPLEX;
			if ( strstr( var, "OVERFLOW" ) )
				_papi_hwi_debug |= DEBUG_OVERFLOW;
			if ( strstr( var, "PROFILE" ) )
				_papi_hwi_debug |= DEBUG_PROFILE;
			if ( strstr( var, "MEMORY" ) )
				_papi_hwi_debug |= DEBUG_MEMORY;
			if ( strstr( var, "LEAK" ) )
				_papi_hwi_debug |= DEBUG_LEAK;
			if ( strstr( var, "ALL" ) )
				_papi_hwi_debug |= DEBUG_ALL;
		}

		if ( _papi_hwi_debug == 0 )
			_papi_hwi_debug |= DEBUG_API;
	}
#endif


	/* Initialize internal globals */
	if ( _papi_hwi_init_global_internal(  ) != PAPI_OK ) {
		_in_papi_library_init_cnt--;
		papi_return( PAPI_EINVAL );
	}

	/* Initialize OS */
	tmp = _papi_hwi_init_os();
	if ( tmp ) {
	   init_retval = tmp;
	   _papi_hwi_shutdown_global_internal(  );
	   _in_papi_library_init_cnt--;
	   papi_return( init_retval );
	}

	/* Initialize component globals */

	tmp = _papi_hwi_init_global(  );
	if ( tmp ) {
		init_retval = tmp;
		_papi_hwi_shutdown_global_internal(  );
		_in_papi_library_init_cnt--;
		papi_return( init_retval );
	}
	
	/* Initialize thread globals, including the main threads  */

	tmp = _papi_hwi_init_global_threads(  );
	if ( tmp ) {
		int i;
		init_retval = tmp;
		_papi_hwi_shutdown_global_internal(  );
		for ( i = 0; i < papi_num_components; i++ ) {
		    if (!_papi_hwd[i]->cmp_info.disabled) {
                       _papi_hwd[i]->shutdown_component(  );
		    }
		}
		_in_papi_library_init_cnt--;
		papi_return( init_retval );
	}

	init_level = PAPI_LOW_LEVEL_INITED;
	_in_papi_library_init_cnt--;

	return ( init_retval = PAPI_VER_CURRENT );
}

/** @class PAPI_query_event
 *  @brief Query if PAPI event exists.
 *
 * @par C Interface:
 * \#include <papi.h> @n
 * int PAPI_query_event(int EventCode);
 *
 * PAPI_query_event() asks the PAPI library if the PAPI Preset event can be 
 * counted on this architecture. 
 * If the event CAN be counted, the function returns PAPI_OK. 
 * If the event CANNOT be counted, the function returns an error code. 
 * This function also can be used to check the syntax of native and user events. 
 *
 * @param EventCode
 *    -- a defined event such as PAPI_TOT_INS. 
 *
 *  @retval PAPI_EINVAL 
 *	    One or more of the arguments is invalid.
 *  @retval PAPI_ENOEVNT 
 *	    The PAPI preset is not available on the underlying hardware. 
 *
 * @par Examples
 * @code
 * int retval;
 * // Initialize the library
 * retval = PAPI_library_init(PAPI_VER_CURRENT);
 * if (retval != PAPI_VER_CURRENT) {
 *   fprintf(stderr,\"PAPI library init error!\\n\");
 *   exit(1); 
 * }
 * if (PAPI_query_event(PAPI_TOT_INS) != PAPI_OK) {
 *   fprintf(stderr,\"No instruction counter? How lame.\\n\");
 *   exit(1);
 * }
 * @endcode
 *
 * @see PAPI_remove_event 
 * @see PAPI_remove_events 
 * @see PAPI_presets 
 * @see PAPI_native
 */
int
PAPI_query_event( int EventCode )
{
    APIDBG( "Entry: EventCode: %#x\n", EventCode);
	if ( IS_PRESET(EventCode) ) {
		EventCode &= PAPI_PRESET_AND_MASK;
		if ( EventCode < 0 || EventCode >= PAPI_MAX_PRESET_EVENTS )
			papi_return( PAPI_ENOTPRESET );

		if ( _papi_hwi_presets[EventCode].count )
		        papi_return (PAPI_OK);
		else
			return PAPI_ENOEVNT;
	}

	if ( IS_NATIVE(EventCode) ) {
		papi_return( _papi_hwi_query_native_event
					 ( ( unsigned int ) EventCode ) );
	}

	if ( IS_USER_DEFINED(EventCode) ) {
	  EventCode &= PAPI_UE_AND_MASK;
	  if ( EventCode < 0 || EventCode >= PAPI_MAX_USER_EVENTS)
		  papi_return ( PAPI_ENOEVNT );

		if ( user_defined_events[EventCode].count )
			papi_return (PAPI_OK);
		else
			papi_return (PAPI_ENOEVNT);
	}

	papi_return( PAPI_ENOEVNT );
}

/** @class PAPI_query_named_event
 *  @brief Query if a named PAPI event exists.
 *
 * @par C Interface:
 * \#include <papi.h> @n
 * int PAPI_query_named_event(const char *EventName);
 *
 * PAPI_query_named_event() asks the PAPI library if the PAPI named event can be 
 * counted on this architecture. 
 * If the event CAN be counted, the function returns PAPI_OK. 
 * If the event CANNOT be counted, the function returns an error code. 
 * This function also can be used to check the syntax of native and user events. 
 *
 * @param EventName
 *    -- a defined event such as PAPI_TOT_INS. 
 *
 *  @retval PAPI_EINVAL 
 *	    One or more of the arguments is invalid.
 *  @retval PAPI_ENOEVNT 
 *	    The PAPI preset is not available on the underlying hardware. 
 *
 * @par Examples
 * @code
 * int retval;
 * // Initialize the library
 * retval = PAPI_library_init(PAPI_VER_CURRENT);
 * if (retval != PAPI_VER_CURRENT) {
 *   fprintf(stderr,\"PAPI library init error!\\n\");
 *   exit(1); 
 * }
 * if (PAPI_query_named_event("PAPI_TOT_INS") != PAPI_OK) {
 *   fprintf(stderr,\"No instruction counter? How lame.\\n\");
 *   exit(1);
 * }
 * @endcode
 *
 * @see PAPI_query_event 
 */
int
PAPI_query_named_event( const char *EventName )
{
	int ret, code;

	ret = PAPI_event_name_to_code( EventName, &code );
	if ( ret == PAPI_OK ) ret = PAPI_query_event( code );
	papi_return( ret);
}


/**	@class PAPI_get_component_info 
 *	@brief get information about a specific software component 
 *
 *	@param cidx
 *		Component index
 *
 *	This function returns a pointer to a structure containing detailed 
 *	information about a specific software component in the PAPI library. 
 *	This includes versioning information, preset and native event 
 *	information, and more. 
 *	For full details, see @ref PAPI_component_info_t. 
 *
 *	@par Examples:
 *	@code
 		const PAPI_component_info_t *cmpinfo = NULL;
 		if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
 		exit(1);
 		if ((cmpinfo = PAPI_get_component_info(0)) == NULL)
 		exit(1);
 		printf("This component supports %d Preset Events and %d Native events.\n",
		cmpinfo->num_preset_events, cmpinfo->num_native_events);
 *	@endcode
 *
 *	@see PAPI_get_executable_info
 *	@see PAPI_get_hardware_info
 *	@see PAPI_get_dmem_info
 *	@see PAPI_get_opt
 *	@see PAPI_component_info_t
 */
const PAPI_component_info_t *
PAPI_get_component_info( int cidx )
{
	APIDBG( "Entry: Component Index %d\n", cidx);
	if ( _papi_hwi_invalid_cmp( cidx ) )
		return ( NULL );
	else
		return ( &( _papi_hwd[cidx]->cmp_info ) );
}

/* PAPI_get_event_info:
   tests input EventCode and returns a filled in PAPI_event_info_t 
   structure containing descriptive strings and values for the 
   specified event. Handles both preset and native events by 
   calling either _papi_hwi_get_event_info or 
   _papi_hwi_get_native_event_info.
*/
/** @class PAPI_get_event_info
 *	@brief Get the event's name and description info.
 *
 *	@param EventCode
 *		event code (preset or native)
 *	@param info 
 *		structure with the event information @ref PAPI_event_info_t
 *
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOTPRESET 
 *		The PAPI preset mask was set, but the hardware event specified is 
 *		not a valid PAPI preset.
 *	@retval PAPI_ENOEVNT 
 *		The PAPI preset is not available on the underlying hardware. 
 *
 *	This function fills the event information into a structure. 
 *	In Fortran, some fields of the structure are returned explicitly. 
 *	This function works with existing PAPI preset and native event codes. 
 *
 *	@see PAPI_event_name_to_code 
 */
int
PAPI_get_event_info( int EventCode, PAPI_event_info_t *info )
{
	APIDBG( "Entry: EventCode: 0x%x, info: %p\n", EventCode, info);
        int i;

	if ( info == NULL )
	   papi_return( PAPI_EINVAL );

	if ( IS_PRESET(EventCode) ) {
           i = EventCode & PAPI_PRESET_AND_MASK;
	   if ( i >= PAPI_MAX_PRESET_EVENTS )
	      papi_return( PAPI_ENOTPRESET );
	   papi_return( _papi_hwi_get_preset_event_info( EventCode, info ) );
	}

	if ( IS_NATIVE(EventCode) ) {
	   papi_return( _papi_hwi_get_native_event_info
			  ( ( unsigned int ) EventCode, info ) );
	}

	if ( IS_USER_DEFINED(EventCode) ) {
	   papi_return( _papi_hwi_get_user_event_info( EventCode, info ));
	}
	papi_return( PAPI_ENOTPRESET );
}


/** @class PAPI_event_code_to_name
 *	@brief Convert a numeric hardware event code to a name.
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_event_code_to_name( int  EventCode, char * EventName );
 *
 *	PAPI_event_code_to_name is used to translate a 32-bit integer PAPI event 
 *	code into an ASCII PAPI event name. 
 *	Either Preset event codes or Native event codes can be passed to this routine. 
 *	Native event codes and names differ from platform to platform.
 *
 *	@param EventCode 
 *		The numeric code for the event. 
 *	@param *EventName
 *		A string containing the event name as listed in PAPI_presets or discussed in PAPI_native.
 *
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOTPRESET 
 *		The hardware event specified is not a valid PAPI preset.
 *	@retval PAPI_ENOEVNT 
 *		The hardware event is not available on the underlying hardware. 
 *
 *	@par Examples:
 *	@code
 *	int EventCode, EventSet = PAPI_NULL;
 *  int Event, number;
 *	char EventCodeStr[PAPI_MAX_STR_LEN];
 *	// Create the EventSet
 *	if ( PAPI_create_eventset( &EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Add Total Instructions Executed to our EventSet
 *	if ( PAPI_add_event( EventSet, PAPI_TOT_INS ) != PAPI_OK )
 *	handle_error( 1 );
 *	number = 1;
 *	if ( PAPI_list_events( EventSet, &Event, &number ) != PAPI_OK )
 *	handle_error(1);
 *	// Convert integer code to name string
 *	if ( PAPI_event_code_to_name( Event, EventCodeStr ) != PAPI_OK )
 *	handle_error( 1 );
 *	printf( "Event Name: %s\n", EventCodeStr );
 *	@endcode
 *
 *	@see PAPI_event_name_to_code
 *	@see PAPI_remove_event
 *	@see PAPI_get_event_info
 *	@see PAPI_enum_event
 *	@see PAPI_add_event
 *	@see PAPI_presets
 *	@see PAPI_native
 */
int
PAPI_event_code_to_name( int EventCode, char *out )
{
	APIDBG( "Entry: EventCode: %#x, out: %p\n", EventCode, out);
	if ( out == NULL )
		papi_return( PAPI_EINVAL );

	if ( IS_PRESET(EventCode) ) {
		EventCode &= PAPI_PRESET_AND_MASK;
		if ( EventCode < 0 || EventCode >= PAPI_MAX_PRESET_EVENTS )
			papi_return( PAPI_ENOTPRESET );

		if (_papi_hwi_presets[EventCode].symbol == NULL )
			papi_return( PAPI_ENOTPRESET );

		strncpy( out, _papi_hwi_presets[EventCode].symbol, PAPI_MAX_STR_LEN-1 );
		out[PAPI_MAX_STR_LEN-1] = '\0';
		papi_return( PAPI_OK );
	}

	if ( IS_NATIVE(EventCode) ) {
		return ( _papi_hwi_native_code_to_name
				 ( ( unsigned int ) EventCode, out, PAPI_MAX_STR_LEN ) );
	}

	if ( IS_USER_DEFINED(EventCode) ) {
		EventCode &= PAPI_UE_AND_MASK;

		if ( EventCode < 0 || EventCode >= user_defined_events_count )
			papi_return( PAPI_ENOEVNT );

		if (user_defined_events[EventCode].symbol == NULL )
			papi_return( PAPI_ENOEVNT );

		strncpy( out, user_defined_events[EventCode].symbol, PAPI_MAX_STR_LEN-1);
		out[PAPI_MAX_STR_LEN-1] = '\0';
		papi_return( PAPI_OK );
	}

	papi_return( PAPI_ENOEVNT );
}

/** @class PAPI_event_name_to_code
 *	@brief Convert a name to a numeric hardware event code. 
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_event_name_to_code( const char * EventName, int * EventCode );
 *
 *	PAPI_event_name_to_code is used to translate an ASCII PAPI event name 
 *	into an integer PAPI event code. 
 *
 *	@param *EventCode 
 *		The numeric code for the event. 
 *	@param *EventName
 *		A string containing the event name as listed in PAPI_presets or discussed in PAPI_native.
 *
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOTPRESET 
 *		The hardware event specified is not a valid PAPI preset.
 *	@retval PAPI_ENOINIT 
 *		The PAPI library has not been initialized.
 *	@retval PAPI_ENOEVNT 
 *		The hardware event is not available on the underlying hardware. 
 *
 *	@par Examples:
 *	@code
 *	int EventCode, EventSet = PAPI_NULL;
 *	// Convert to integer
 *	if ( PAPI_event_name_to_code( "PAPI_TOT_INS", &EventCode ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Create the EventSet
 *	if ( PAPI_create_eventset( &EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Add Total Instructions Executed to our EventSet
 *	if ( PAPI_add_event( EventSet, EventCode ) != PAPI_OK )
 *	handle_error( 1 );
 *	@endcode
 *
 *	@see PAPI_event_code_to_name
 *	@see PAPI_remove_event
 *	@see PAPI_get_event_info
 *	@see PAPI_enum_event
 *	@see PAPI_add_event
 *	@see PAPI_add_named_event
 *	@see PAPI_presets
 *	@see PAPI_native
 */
int
PAPI_event_name_to_code( const char *in, int *out )
{
   APIDBG("Entry: in: %p, name: %s, out: %p\n", in, in, out);
	int i;

	if ( ( in == NULL ) || ( out == NULL ) )
		papi_return( PAPI_EINVAL );

	if ( init_level == PAPI_NOT_INITED )
		papi_return( PAPI_ENOINIT );

	/* All presets start with "PAPI_" so no need to */
	/* do an exhaustive search if that's not there  */
	if (strncmp(in, "PAPI_", 5) == 0) {
	   for(i = 0; i < PAPI_MAX_PRESET_EVENTS; i++ ) {
	      if ( ( _papi_hwi_presets[i].symbol )
		   && ( strcasecmp( _papi_hwi_presets[i].symbol, in ) == 0) ) {
		 *out = ( int ) ( i | PAPI_PRESET_MASK );
		 papi_return( PAPI_OK );
	      }
	   }
	}

	// check to see if it is a user defined event
	for ( i=0; i < user_defined_events_count ; i++ ) {
		APIDBG("&user_defined_events[%d]: %p, user_defined_events[%d].symbol: %s, user_defined_events[%d].count: %d\n",
				i, &user_defined_events[i], i, user_defined_events[i].symbol, i, user_defined_events[i].count);
		if (user_defined_events[i].symbol == NULL)
			break;
		if (user_defined_events[i].count == 0)
			break;
		if ( strcasecmp( user_defined_events[i].symbol, in ) == 0 ) {
			*out = (int) ( i | PAPI_UE_MASK );
			papi_return( PAPI_OK );
		}
	}

	// go look for native events defined by one of the components
	papi_return( _papi_hwi_native_name_to_code( in, out ) );
}

/* Updates EventCode to next valid value, or returns error; 
  modifier can specify {all / available} for presets, or other values for native tables 
  and may be platform specific (Major groups / all mask bits; P / M / E chip, etc) */

/** @class PAPI_enum_event
 *	@brief Enumerate PAPI preset or native events.
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_enum_event( int * EventCode, int  modifer );
 *
 *	Given a preset or native event code, PAPI_enum_event replaces the event 
 *	code with the next available event in either the preset or native table. 
 *	The modifier argument affects which events are returned. 
 *	For all platforms and event types, a value of PAPI_ENUM_ALL (zero) 
 *	directs the function to return all possible events. @n
 *
 *	For preset events, a TRUE (non-zero) value currently directs the function 
 *	to return event codes only for PAPI preset events available on this platform. 
 *	This may change in the future. 
 *	For native events, the effect of the modifier argument is different on each platform. 
 *	See the discussion below for platform-specific definitions.
 *
 *	@param *EventCode
 *		A defined preset or native event such as PAPI_TOT_INS.
 *	@param modifier 
 *		Modifies the search logic. See below for full list.
 *		For native events, each platform behaves differently. 
 *		See platform-specific documentation for details.
 *
 *	@retval PAPI_ENOEVNT 
 *		The next requested PAPI preset or native event is not available on 
 *		the underlying hardware.
 *
 *	@par Examples:
 *	@code
 *	// Scan for all supported native events on this platform
 *	printf( "Name\t\t\t       Code\t   Description\n" );
 *	do {
 *		retval = PAPI_get_event_info( i, &info );
 *		if ( retval == PAPI_OK ) {
 *		printf( "%-30s %#-10x\n%s\n", info.symbol, info.event_code, info.long_descr );
 *		}
 *	} while ( PAPI_enum_event( &i, PAPI_ENUM_ALL ) == PAPI_OK );
 *	@endcode
 *
 *      @par Generic Modifiers
 *	The following values are implemented for preset events
 *	<ul>
 *         <li> PAPI_ENUM_EVENTS -- Enumerate all (default)
 *         <li> PAPI_ENUM_FIRST -- Enumerate first event (preset or native)
 *                preset/native chosen based on type of EventCode
 *	</ul>
 *
 *      @par Native Modifiers
 *	The following values are implemented for native events
 *	<ul>
 *         <li>PAPI_NTV_ENUM_UMASKS -- Given an event, iterate through
 *                     possible umasks one at a time
 *         <li>PAPI_NTV_ENUM_UMASK_COMBOS -- Given an event, iterate
 *                     through all possible combinations of umasks.
 *                     This is not implemented on libpfm4.
 *	</ul>
 *
 *	@par Preset Modifiers
 *	The following values are implemented for preset events
 *	<ul>
 *         <li> PAPI_PRESET_ENUM_AVAIL -- enumerate only available presets
 *         <li> PAPI_PRESET_ENUM_MSC   -- Miscellaneous preset events
 *         <li> PAPI_PRESET_ENUM_INS   -- Instruction related preset events
 *         <li> PAPI_PRESET_ENUM_IDL   -- Stalled or Idle preset events
 *         <li> PAPI_PRESET_ENUM_BR    -- Branch related preset events
 *         <li> PAPI_PRESET_ENUM_CND   -- Conditional preset events
 *         <li> PAPI_PRESET_ENUM_MEM   -- Memory related preset events
 *         <li> PAPI_PRESET_ENUM_CACH  -- Cache related preset events
 *         <li> PAPI_PRESET_ENUM_L1    -- L1 cache related preset events
 *         <li> PAPI_PRESET_ENUM_L2    -- L2 cache related preset events
 *         <li> PAPI_PRESET_ENUM_L3    -- L3 cache related preset events
 *         <li> PAPI_PRESET_ENUM_TLB   -- Translation Lookaside Buffer events
 *         <li> PAPI_PRESET_ENUM_FP    -- Floating Point related preset events
 *	</ul>
 *
 *	@par ITANIUM Modifiers
 *	The following values are implemented for modifier on Itanium: 
 *	<ul>
 *	   <li> PAPI_NTV_ENUM_IARR - Enumerate IAR (instruction address ranging) events 
 *	   <li> PAPI_NTV_ENUM_DARR - Enumerate DAR (data address ranging) events 
 *	   <li> PAPI_NTV_ENUM_OPCM - Enumerate OPC (opcode matching) events 
 *	   <li> PAPI_NTV_ENUM_IEAR - Enumerate IEAR (instr event address register) events 
 *	   <li> PAPI_NTV_ENUM_DEAR - Enumerate DEAR (data event address register) events
 *	</ul>
 *
 *	@par POWER Modifiers
 *	The following values are implemented for POWER
 *	<ul>
 *	   <li> PAPI_NTV_ENUM_GROUPS - Enumerate groups to which an event belongs
 *	</ul>
 *
 *	@see PAPI @n
 *	PAPIF @n
 *      PAPI_enum_cmp_event @n
 *	PAPI_get_event_info @n
 *	PAPI_event_name_to_code @n
 *	PAPI_preset @n
 *	PAPI_native
 */
int
PAPI_enum_event( int *EventCode, int modifier )
{
	APIDBG( "Entry: EventCode: %#x, modifier: %d\n", *EventCode, modifier);
	int i = *EventCode;
	int retval;
	int cidx;
	int event_code;
	char *evt_name;

	cidx = _papi_hwi_component_index( *EventCode );
	if (cidx < 0) return PAPI_ENOCMP;

	/* Do we handle presets in componets other than CPU? */
	/* if (( IS_PRESET(i) ) && cidx > 0 )) return PAPI_ENOCMP; */
		
	if ( IS_PRESET(i) ) {
		if ( modifier == PAPI_ENUM_FIRST ) {
			*EventCode = ( int ) PAPI_PRESET_MASK;
			APIDBG("EXIT: *EventCode: %#x\n", *EventCode);
			return ( PAPI_OK );
		}
		i &= PAPI_PRESET_AND_MASK;
		while ( ++i < PAPI_MAX_PRESET_EVENTS ) {
			if ( _papi_hwi_presets[i].symbol == NULL ) {
				APIDBG("EXIT: PAPI_ENOEVNT\n");
				return ( PAPI_ENOEVNT );	/* NULL pointer terminates list */
			}
			if ( modifier & PAPI_PRESET_ENUM_AVAIL ) {
				if ( _papi_hwi_presets[i].count == 0 )
					continue;
			}
			*EventCode = ( int ) ( i | PAPI_PRESET_MASK );
			APIDBG("EXIT: *EventCode: %#x\n", *EventCode);
			return ( PAPI_OK );
		}
		papi_return( PAPI_EINVAL );
	}

	if ( IS_NATIVE(i) ) {
	    // save event code so components can get it with call to: _papi_hwi_get_papi_event_code()
	    _papi_hwi_set_papi_event_code(*EventCode, 0);

		/* Should check against num native events here */

	    event_code=_papi_hwi_eventcode_to_native((int)*EventCode);
	    retval = _papi_hwd[cidx]->ntv_enum_events((unsigned int *)&event_code, modifier );

	    if (retval!=PAPI_OK) {
	       APIDBG("VMW: retval=%d\n",retval);
	       return PAPI_EINVAL;
	    }

	    evt_name = _papi_hwi_get_papi_event_string();
    	*EventCode = _papi_hwi_native_to_eventcode(cidx, event_code, -1, evt_name);
	    _papi_hwi_free_papi_event_string();

	    APIDBG("EXIT: *EventCode: %#x\n", *EventCode);
	    return retval;
	}

	if ( IS_USER_DEFINED(i) ) {
		if (user_defined_events_count == 0) {
			APIDBG("EXIT: PAPI_ENOEVNT\n");
			return PAPI_ENOEVNT;
		}
		if ( modifier == PAPI_ENUM_FIRST ) {
			*EventCode = (int) (0 | PAPI_UE_MASK);
			APIDBG("EXIT: *EventCode: %#x\n", *EventCode);
			return ( PAPI_OK );
		}

		i &= PAPI_UE_AND_MASK;
		++i;

		if ( i <= 0  ||  i >= user_defined_events_count ) {
			APIDBG("EXIT: PAPI_ENOEVNT\n");
			return ( PAPI_ENOEVNT );
		}

		// if next entry does not have an event name, we are done
		if (user_defined_events[i].symbol == NULL) {
			APIDBG("EXIT: PAPI_ENOEVNT\n");
			return ( PAPI_ENOEVNT );
		}

		// if next entry does not map to any other events, we are done
		if (user_defined_events[i].count == 0) {
			APIDBG("EXIT: PAPI_ENOEVNT\n");
			return ( PAPI_ENOEVNT );
		}

		*EventCode = (int) (i | PAPI_UE_MASK);
		APIDBG("EXIT: *EventCode: %#x\n", *EventCode);
		return ( PAPI_OK );
	}

	papi_return( PAPI_EINVAL );
}


/** @class PAPI_enum_cmp_event
 *	@brief Enumerate PAPI preset or native events for a given component
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_enum_cmp_event( int *EventCode, int  modifer, int cidx );
 *
 *	Given an event code, PAPI_enum_event replaces the event 
 *	code with the next available event.
 * 
 *	The modifier argument affects which events are returned. 
 *	For all platforms and event types, a value of PAPI_ENUM_ALL (zero) 
 *	directs the function to return all possible events. @n
 *
 *	For native events, the effect of the modifier argument may be
 *      different on each platform. 
 *	See the discussion below for platform-specific definitions.
 *
 *	@param *EventCode
 *		A defined preset or native event such as PAPI_TOT_INS.
 *	@param modifier 
 *		Modifies the search logic. See below for full list.
 *		For native events, each platform behaves differently. 
 *		See platform-specific documentation for details.
 *
 *      @param cidx
 *              Specifies the component to search in 
 *
 *	@retval PAPI_ENOEVNT 
 *		The next requested PAPI preset or native event is not available on 
 *		the underlying hardware.
 *
 *	@par Examples:
 *	@code
 *	// Scan for all supported native events on the first component
 *	printf( "Name\t\t\t       Code\t   Description\n" );
 *	do {
 *		retval = PAPI_get_event_info( i, &info );
 *		if ( retval == PAPI_OK ) {
 *		printf( "%-30s %#-10x\n%s\n", info.symbol, info.event_code, info.long_descr );
 *		}
 *	} while ( PAPI_enum_cmp_event( &i, PAPI_ENUM_ALL, 0 ) == PAPI_OK );
 *	@endcode
 *
 *      @par Generic Modifiers
 *	The following values are implemented for preset events
 *	<ul>
 *         <li> PAPI_ENUM_EVENTS -- Enumerate all (default)
 *         <li> PAPI_ENUM_FIRST -- Enumerate first event (preset or native)
 *                preset/native chosen based on type of EventCode
 *	</ul>
 *
 *      @par Native Modifiers
 *	The following values are implemented for native events
 *	<ul>
 *         <li>PAPI_NTV_ENUM_UMASKS -- Given an event, iterate through
 *                     possible umasks one at a time
 *         <li>PAPI_NTV_ENUM_UMASK_COMBOS -- Given an event, iterate
 *                     through all possible combinations of umasks.
 *                     This is not implemented on libpfm4.
 *	</ul>
 *
 *	@par Preset Modifiers
 *	The following values are implemented for preset events
 *	<ul>
 *         <li> PAPI_PRESET_ENUM_AVAIL -- enumerate only available presets
 *         <li> PAPI_PRESET_ENUM_MSC   -- Miscellaneous preset events
 *         <li> PAPI_PRESET_ENUM_INS   -- Instruction related preset events
 *         <li> PAPI_PRESET_ENUM_IDL   -- Stalled or Idle preset events
 *         <li> PAPI_PRESET_ENUM_BR    -- Branch related preset events
 *         <li> PAPI_PRESET_ENUM_CND   -- Conditional preset events
 *         <li> PAPI_PRESET_ENUM_MEM   -- Memory related preset events
 *         <li> PAPI_PRESET_ENUM_CACH  -- Cache related preset events
 *         <li> PAPI_PRESET_ENUM_L1    -- L1 cache related preset events
 *         <li> PAPI_PRESET_ENUM_L2    -- L2 cache related preset events
 *         <li> PAPI_PRESET_ENUM_L3    -- L3 cache related preset events
 *         <li> PAPI_PRESET_ENUM_TLB   -- Translation Lookaside Buffer events
 *         <li> PAPI_PRESET_ENUM_FP    -- Floating Point related preset events
 *	</ul>
 *
 *	@par ITANIUM Modifiers
 *	The following values are implemented for modifier on Itanium: 
 *	<ul>
 *	   <li> PAPI_NTV_ENUM_IARR - Enumerate IAR (instruction address ranging) events 
 *	   <li> PAPI_NTV_ENUM_DARR - Enumerate DAR (data address ranging) events 
 *	   <li> PAPI_NTV_ENUM_OPCM - Enumerate OPC (opcode matching) events 
 *	   <li> PAPI_NTV_ENUM_IEAR - Enumerate IEAR (instr event address register) events 
 *	   <li> PAPI_NTV_ENUM_DEAR - Enumerate DEAR (data event address register) events
 *	</ul>
 *
 *	@par POWER Modifiers
 *	The following values are implemented for POWER
 *	<ul>
 *	   <li> PAPI_NTV_ENUM_GROUPS - Enumerate groups to which an event belongs
 *	</ul>
 *
 *	@see PAPI @n
 *	PAPIF @n
 *      PAPI_enum_event @n
 *	PAPI_get_event_info @n
 *	PAPI_event_name_to_code @n
 *	PAPI_preset @n
 *	PAPI_native
 */
int
PAPI_enum_cmp_event( int *EventCode, int modifier, int cidx )
{
	APIDBG( "Entry: EventCode: %#x, modifier: %d, cidx: %d\n", *EventCode, modifier, cidx);
	int i = *EventCode;
	int retval;
	int event_code;
	char *evt_name;

	if ( _papi_hwi_invalid_cmp(cidx) || ( (IS_PRESET(i)) && cidx > 0 ) ) {
		return PAPI_ENOCMP;
	}

	if (_papi_hwd[cidx]->cmp_info.disabled) {
	  return PAPI_ENOCMP;
	}

	if ( IS_PRESET(i) ) {
		if ( modifier == PAPI_ENUM_FIRST ) {
			*EventCode = ( int ) PAPI_PRESET_MASK;
			APIDBG("EXIT: *EventCode: %#x\n", *EventCode);
			return PAPI_OK;
		}
		i &= PAPI_PRESET_AND_MASK;
		while ( ++i < PAPI_MAX_PRESET_EVENTS ) {
			if ( _papi_hwi_presets[i].symbol == NULL ) {
				APIDBG("EXIT: PAPI_ENOEVNT\n");
				return ( PAPI_ENOEVNT );	/* NULL pointer terminates list */
			}
			if ( modifier & PAPI_PRESET_ENUM_AVAIL ) {
				if ( _papi_hwi_presets[i].count == 0 )
					continue;
			}
			*EventCode = ( int ) ( i | PAPI_PRESET_MASK );
			APIDBG("EXIT: *EventCode: %#x\n", *EventCode);
			return PAPI_OK;
		}
		papi_return( PAPI_EINVAL );
	}

	if ( IS_NATIVE(i) ) {
	    // save event code so components can get it with call to: _papi_hwi_get_papi_event_code()
	    _papi_hwi_set_papi_event_code(*EventCode, 0);

		/* Should we check against num native events here? */
	    event_code=_papi_hwi_eventcode_to_native(*EventCode);
	    retval = _papi_hwd[cidx]->ntv_enum_events((unsigned int *)&event_code, modifier );

	    if (retval!=PAPI_OK) {
	       APIDBG("EXIT: PAPI_EINVAL retval=%d\n",retval);
	       return PAPI_EINVAL;
	    }

	    evt_name = _papi_hwi_get_papi_event_string();
	    *EventCode = _papi_hwi_native_to_eventcode(cidx, event_code, -1, evt_name);
	    _papi_hwi_free_papi_event_string();

	    APIDBG("EXIT: *EventCode: %#x\n", *EventCode);
	    return retval;
	} 

	papi_return( PAPI_EINVAL );
}

/** @class PAPI_create_eventset
 *	@brief Create a new empty PAPI EventSet.
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	PAPI_create_eventset( int * EventSet );
 *
 *	PAPI_create_eventset creates a new EventSet pointed to by EventSet, 
 *	which must be initialized to PAPI_NULL before calling this routine. 
 *	The user may then add hardware events to the event set by calling 
 *	PAPI_add_event or similar routines.
 *
 *	@note PAPI-C uses a late binding model to bind EventSets to components. 
 *	When an EventSet is first created it is not bound to a component. 
 *	This will cause some API calls that modify EventSet options to fail. 
 *	An EventSet can be bound to a component explicitly by calling 
 *	PAPI_assign_eventset_component or implicitly by calling PAPI_add_event
 *	or similar routines. 
 *
 *	@param *EventSet
 *		Address of an integer location to store the new EventSet handle.
 *
 *	@exception PAPI_EINVAL 
 *		The argument handle has not been initialized to PAPI_NULL or the argument is a NULL pointer.
 *
 *	@exception PAPI_ENOMEM 
 *		Insufficient memory to complete the operation. 
 *
 *	@par Examples:
 *	@code
 *	int EventSet = PAPI_NULL;
 *	if ( PAPI_create_eventset( &EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Add Total Instructions Executed to our EventSet
 *	if ( PAPI_add_event( EventSet, PAPI_TOT_INS)  != PAPI_OK )
 *	handle_error( 1 ); 
 *	@endcode
 *
 *	@see PAPI_add_event @n
 *	PAPI_assign_eventset_component @n
 *	PAPI_destroy_eventset @n
 *	PAPI_cleanup_eventset
  */
int
PAPI_create_eventset( int *EventSet )
{
   APIDBG("Entry: EventSet: %p\n", EventSet);

	ThreadInfo_t *master;
	int retval;

	if ( init_level == PAPI_NOT_INITED )
		papi_return( PAPI_ENOINIT );
	retval = _papi_hwi_lookup_or_create_thread( &master, 0 );
	if ( retval )
		papi_return( retval );

	papi_return( _papi_hwi_create_eventset( EventSet, master ) );
}

/** @class PAPI_assign_eventset_component
 *	@brief Assign a component index to an existing but empty EventSet.
 *	
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	PAPI_assign_eventset_component( int  EventSet, int  cidx );
 *
 *	@param EventSet 
 *		An integer identifier for an existing EventSet.
 *	@param cidx 
 *		An integer identifier for a component. 
 *		By convention, component 0 is always the cpu component. 
 *
 *	@retval PAPI_ENOCMP 
 *		The argument cidx is not a valid component.
 *	@retval PAPI_ENOEVST 
 *		The EventSet doesn't exist.
 *	@retval PAPI_ENOMEM 
 *		Insufficient memory to complete the operation. 
 *
 *	PAPI_assign_eventset_component assigns a specific component index, 
 *	as specified by cidx, to a new EventSet identified by EventSet, as obtained 
 *	from PAPI_create_eventset. EventSets are ordinarily automatically bound 
 *	to components when the first event is added. This routine is useful to 
 *	explicitly bind an EventSet to a component before setting component related 
 *	options. 
 *
 *	@par Examples:
 *	@code
 *	int EventSet = PAPI_NULL;
 *	if ( PAPI_create_eventset( &EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Bind our EventSet to the cpu component
 *	if ( PAPI_assign_eventset_component( EventSet, 0 ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Convert our EventSet to multiplexing
 *	if ( PAPI_set_multiplex( EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	@endcode
 *
 *	@see PAPI_set_opt @n
 *	PAPI_create_eventset @n
 *	PAPI_add_events @n
 *	PAPI_set_multiplex
 */
int
PAPI_assign_eventset_component( int EventSet, int cidx )
{
	EventSetInfo_t *ESI;
	int retval;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

/* validate cidx */
	retval = valid_component( cidx );
	if ( retval < 0 )
		papi_return( retval );

/* cowardly refuse to reassign eventsets */ 
	if ( ESI->CmpIdx >= 0 )
	  return PAPI_EINVAL;

	return ( _papi_hwi_assign_eventset( ESI, cidx ) );
}

/**	@class PAPI_get_eventset_component
 *	@brief return index for component an eventset is assigned to
 *
 *	@retval PAPI_ENOEVST
 *		eventset does not exist
 *	@retval PAPI_ENOCMP
 *		component is invalid or does not exist
 *	@retval positive value
 *		valid component index
 *	
 *	@param EventSet
 *              EventSet for which we want to know the component index
 *	@par Examples:
 *	@code
 		int cidx,eventcode;
 		cidx = PAPI_get_eventset_component(eventset);
 *	@endcode
 *	PAPI_get_eventset_component() returns the component an event
 *      belongs to.
 *	@see  PAPI_get_event_component
 */
int
PAPI_get_eventset_component( int EventSet)
{
	EventSetInfo_t *ESI;
	int retval;

/* validate eventset */
	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

/* check if a component has been assigned */ 
	if ( ESI->CmpIdx < 0 )
	  papi_return( PAPI_ENOCMP );

/* validate CmpIdx */
	retval = valid_component( ESI->CmpIdx );
	if ( retval < 0 )
		papi_return( retval );

/* return the index */
	return ( ESI->CmpIdx );
}


/**	@class PAPI_add_event
 *	@brief add PAPI preset or native hardware event to an event set
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_add_event( int  EventSet, int  EventCode );
 *
 *	PAPI_add_event adds one event to a PAPI Event Set. @n
 *	A hardware event can be either a PAPI preset or a native hardware event code.
 *	For a list of PAPI preset events, see PAPI_presets or run the avail test case
 *	in the PAPI distribution. PAPI presets can be passed to PAPI_query_event to see
 *	if they exist on the underlying architecture.
 *	For a list of native events available on current platform, run the papi_native_avail
 *	utility in the PAPI distribution. For the encoding of native events,
 *	see PAPI_event_name_to_code to learn how to generate native code for the
 *	supported native event on the underlying architecture.
 *
 *	@param EventSet
 *		An integer handle for a PAPI Event Set as created by PAPI_create_eventset.
 *	@param EventCode 
 *		A defined event such as PAPI_TOT_INS. 
 *
 *	@retval Positive-Integer
 *		The number of consecutive elements that succeeded before the error. 
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOMEM 
 *		Insufficient memory to complete the operation.
 *	@retval PAPI_ENOEVST 
 *		The event set specified does not exist.
 *	@retval PAPI_EISRUN 
 *		The event set is currently counting events.
 *	@retval PAPI_ECNFLCT 
 *		The underlying counter hardware can not count this event and other events 
 *		in the event set simultaneously.
 *	@retval PAPI_ENOEVNT 
 *		The PAPI preset is not available on the underlying hardware.
 *	@retval PAPI_EBUG 
 *		Internal error, please send mail to the developers. 
 *
 *	@par Examples:
 *	@code
 *	int EventSet = PAPI_NULL;
 *	unsigned int native = 0x0;
 *	if ( PAPI_create_eventset( &EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Add Total Instructions Executed to our EventSet
 *	if ( PAPI_add_event( EventSet, PAPI_TOT_INS ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Add native event PM_CYC to EventSet
 *	if ( PAPI_event_name_to_code( "PM_CYC", &native ) != PAPI_OK )
 *	handle_error( 1 );
 *	if ( PAPI_add_event( EventSet, native ) != PAPI_OK )
 *	handle_error( 1 );
 *	@endcode
 *
 *	@bug
 *	The vector function should take a pointer to a length argument so a proper 
 *	return value can be set upon partial success.
 *
 *	@see PAPI_cleanup_eventset @n
 *	PAPI_destroy_eventset @n
 *	PAPI_event_code_to_name @n
 *	PAPI_remove_events @n
 *	PAPI_query_event @n
 *	PAPI_presets @n
 *	PAPI_native @n
 *	PAPI_remove_event
 */
int
PAPI_add_event( int EventSet, int EventCode )
{
   APIDBG("Entry: EventSet: %d, EventCode: %#x\n", EventSet, EventCode);
	EventSetInfo_t *ESI;

	/* Is the EventSet already in existence? */

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	/* Check argument for validity */

	if ( ( ( EventCode & PAPI_PRESET_MASK ) == 0 ) &&
		 ( EventCode & PAPI_NATIVE_MASK ) == 0 )
		papi_return( PAPI_EINVAL );

	/* Of course, it must be stopped in order to modify it. */

	if ( ESI->state & PAPI_RUNNING )
		papi_return( PAPI_EISRUN );

	/* Now do the magic. */
	int retval = _papi_hwi_add_event( ESI, EventCode );
	papi_return( retval );
}

/**  @class PAPI_remove_event
 *   @brief removes a hardware event from a PAPI event set. 
 *
 *   A hardware event can be either a PAPI Preset or a native hardware 
 *   event code.  For a list of PAPI preset events, see PAPI_presets or 
 *   run the papi_avail utility in the PAPI distribution.  PAPI Presets 
 *   can be passed to PAPI_query_event to see if they exist on the 
 *   underlying architecture.  For a list of native events available on 
 *   the current platform, run papi_native_avail in the PAPI distribution. 
 *
 *   @par C Interface:
 *   \#include <papi.h> @n
 *   int PAPI_remove_event( int  EventSet, int  EventCode );
 *
 *   @param[in] EventSet
 *	   -- an integer handle for a PAPI event set as created 
 *            by PAPI_create_eventset
 *   @param[in] EventCode
 *	   -- a defined event such as PAPI_TOT_INS or a native event. 
 *
 *   @retval PAPI_OK 
 *		Everything worked.
 *   @retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *   @retval PAPI_ENOEVST 
 *		The EventSet specified does not exist.
 *   @retval PAPI_EISRUN 
 *		The EventSet is currently counting events.
 *   @retval PAPI_ECNFLCT 
 *		The underlying counter hardware can not count this 
 *              event and other events in the EventSet simultaneously.
 *   @retval PAPI_ENOEVNT 
 *		The PAPI preset is not available on the underlying hardware. 
 *
 *   @par Example:
 *   @code
 *   int EventSet = PAPI_NULL;
 *   int ret;
 *
 *   // Create an empty EventSet
 *   ret = PAPI_create_eventset(&EventSet);
 *   if (ret != PAPI_OK) handle_error(ret);
 *
 *   // Add Total Instructions Executed to our EventSet
 *   ret = PAPI_add_event(EventSet, PAPI_TOT_INS);
 *   if (ret != PAPI_OK) handle_error(ret);
 *
 *   // Start counting
 *   ret = PAPI_start(EventSet);
 *   if (ret != PAPI_OK) handle_error(ret);
 *
 *   // Stop counting, ignore values
 *   ret = PAPI_stop(EventSet, NULL);
 *   if (ret != PAPI_OK) handle_error(ret);
 *
 *   // Remove event
 *   ret = PAPI_remove_event(EventSet, PAPI_TOT_INS);
 *   if (ret != PAPI_OK) handle_error(ret);
 *   @endcode
 *
 *   @see PAPI_cleanup_eventset 
 *   @see PAPI_destroy_eventset
 *   @see PAPI_event_name_to_code 
 *   @see PAPI_presets 
 *   @see PAPI_add_event 
 *   @see PAPI_add_events
 */
int
PAPI_remove_event( int EventSet, int EventCode )
{
	APIDBG("Entry: EventSet: %d, EventCode: %#x\n", EventSet, EventCode);
	EventSetInfo_t *ESI;
	int i,retval;

	/* check for pre-existing ESI */

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	/* Check argument for validity */

	if ( ( !IS_PRESET(EventCode) ) &&
		( !IS_NATIVE(EventCode) ) &&
		( !IS_USER_DEFINED(EventCode) ))
		papi_return( PAPI_EINVAL );

	/* Of course, it must be stopped in order to modify it. */

	if ( !( ESI->state & PAPI_STOPPED ) )
		papi_return( PAPI_EISRUN );

	/* if the state is PAPI_OVERFLOWING, you must first call
	   PAPI_overflow with threshold=0 to remove the overflow flag */

	/* Turn off the event that is overflowing */
	if ( ESI->state & PAPI_OVERFLOWING ) {
	   for ( i = 0; i < ESI->overflow.event_counter; i++ ) {
	       if ( ESI->overflow.EventCode[i] == EventCode ) {
		  retval = PAPI_overflow( EventSet, EventCode, 0, 0,
					  ESI->overflow.handler );
		  if (retval!=PAPI_OK) return retval;
		  break;
	       }
	   }
	}

	/* force the user to call PAPI_profil to clear the PAPI_PROFILING flag */
	if ( ESI->state & PAPI_PROFILING ) {
		for ( i = 0; i < ESI->profile.event_counter; i++ ) {
			if ( ESI->profile.EventCode[i] == EventCode ) {
				PAPI_sprofil( NULL, 0, EventSet, EventCode, 0, 0 );
				break;
			}
		}
	}

	/* Now do the magic. */

	papi_return( _papi_hwi_remove_event( ESI, EventCode ) );
}

/**	@class PAPI_add_named_event
 *	@brief add PAPI preset or native hardware event by name to an EventSet
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_add_named_event( int EventSet, const char *EventName );
 *
 *	PAPI_add_named_event adds one event to a PAPI EventSet. @n
 *	A hardware event can be either a PAPI preset or a native hardware event code.
 *	For a list of PAPI preset events, see PAPI_presets or run the avail test case
 *	in the PAPI distribution. PAPI presets can be passed to PAPI_query_event to see
 *	if they exist on the underlying architecture.
 *	For a list of native events available on current platform, run the papi_native_avail
 *	utility in the PAPI distribution.
 *
 *	@param EventSet
 *		An integer handle for a PAPI Event Set as created by PAPI_create_eventset.
 *	@param EventCode 
 *		A defined event such as PAPI_TOT_INS. 
 *
 *	@retval Positive-Integer
 *		The number of consecutive elements that succeeded before the error. 
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOINIT 
 *		The PAPI library has not been initialized.
 *	@retval PAPI_ENOMEM 
 *		Insufficient memory to complete the operation.
 *	@retval PAPI_ENOEVST 
 *		The event set specified does not exist.
 *	@retval PAPI_EISRUN 
 *		The event set is currently counting events.
 *	@retval PAPI_ECNFLCT 
 *		The underlying counter hardware can not count this event and other events 
 *		in the event set simultaneously.
 *	@retval PAPI_ENOEVNT 
 *		The PAPI preset is not available on the underlying hardware.
 *	@retval PAPI_EBUG 
 *		Internal error, please send mail to the developers. 
 *
 *	@par Examples:
 *	@code
 *  char EventName = "PAPI_TOT_INS";
 *	int EventSet = PAPI_NULL;
 *	unsigned int native = 0x0;
 *	if ( PAPI_create_eventset( &EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Add Total Instructions Executed to our EventSet
 *	if ( PAPI_add_named_event( EventSet, EventName ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Add native event PM_CYC to EventSet
 *	if ( PAPI_add_named_event( EventSet, "PM_CYC" ) != PAPI_OK )
 *	handle_error( 1 );
 *	@endcode
 *
 *	@bug
 *	The vector function should take a pointer to a length argument so a proper 
 *	return value can be set upon partial success.
 *
 *	@see PAPI_add_event @n
 *	PAPI_query_named_event @n
 *	PAPI_remove_named_event
 */
int
PAPI_add_named_event( int EventSet, const char *EventName )
{
	APIDBG("Entry: EventSet: %d, EventName: %s\n", EventSet, EventName);

	int ret, code;

	ret = PAPI_event_name_to_code( EventName, &code );
	if ( ret != PAPI_OK ) {
		APIDBG("EXIT: return: %d\n", ret);
		return ret;   // do not use papi_return here because if there was an error PAPI_event_name_to_code already reported it
	}

	ret = PAPI_add_event( EventSet, code );
	APIDBG("EXIT: return: %d\n", ret);
	return ret;   // do not use papi_return here because if there was an error PAPI_add_event already reported it
}

/**  @class PAPI_remove_named_event
 *   @brief removes a named hardware event from a PAPI event set. 
 *
 *   A hardware event can be either a PAPI Preset or a native hardware 
 *   event code.  For a list of PAPI preset events, see PAPI_presets or 
 *   run the papi_avail utility in the PAPI distribution.  PAPI Presets 
 *   can be passed to PAPI_query_event to see if they exist on the 
 *   underlying architecture.  For a list of native events available on 
 *   the current platform, run papi_native_avail in the PAPI distribution. 
 *
 *   @par C Interface:
 *   \#include <papi.h> @n
 *   int PAPI_remove_named_event( int  EventSet, const char *EventName );
 *
 *   @param[in] EventSet
 *	   -- an integer handle for a PAPI event set as created 
 *            by PAPI_create_eventset
 *   @param[in] EventName
 *	   -- a defined event such as PAPI_TOT_INS or a native event. 
 *
 *   @retval PAPI_OK 
 *		Everything worked.
 *   @retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOINIT 
 *		The PAPI library has not been initialized.
 *   @retval PAPI_ENOEVST 
 *		The EventSet specified does not exist.
 *   @retval PAPI_EISRUN 
 *		The EventSet is currently counting events.
 *   @retval PAPI_ECNFLCT 
 *		The underlying counter hardware can not count this 
 *              event and other events in the EventSet simultaneously.
 *   @retval PAPI_ENOEVNT 
 *		The PAPI preset is not available on the underlying hardware. 
 *
 *   @par Example:
 *   @code
 *   char EventName = "PAPI_TOT_INS";
 *   int EventSet = PAPI_NULL;
 *   int ret;
 *
 *   // Create an empty EventSet
 *   ret = PAPI_create_eventset(&EventSet);
 *   if (ret != PAPI_OK) handle_error(ret);
 *
 *   // Add Total Instructions Executed to our EventSet
 *   ret = PAPI_add_named_event(EventSet, EventName);
 *   if (ret != PAPI_OK) handle_error(ret);
 *
 *   // Start counting
 *   ret = PAPI_start(EventSet);
 *   if (ret != PAPI_OK) handle_error(ret);
 *
 *   // Stop counting, ignore values
 *   ret = PAPI_stop(EventSet, NULL);
 *   if (ret != PAPI_OK) handle_error(ret);
 *
 *   // Remove event
 *   ret = PAPI_remove_named_event(EventSet, EventName);
 *   if (ret != PAPI_OK) handle_error(ret);
 *   @endcode
 *
 *   @see PAPI_remove_event @n
 *	PAPI_query_named_event @n
 *	PAPI_add_named_event
 */
int
PAPI_remove_named_event( int EventSet, const char *EventName )
{
	APIDBG("Entry: EventSet: %d, EventName: %s\n", EventSet, EventName);
	int ret, code;

	ret = PAPI_event_name_to_code( EventName, &code );
	if ( ret == PAPI_OK ) ret = PAPI_remove_event( EventSet, code );
	papi_return( ret );

}

/** @class PAPI_destroy_eventset 
 *	@brief Empty and destroy an EventSet.
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_destroy_eventset( int * EventSet );
 *
 * PAPI_destroy_eventset deallocates the memory associated with an empty PAPI EventSet.
 *
 *	@param *EventSet
 *		A pointer to the integer handle for a PAPI event set as created by PAPI_create_eventset.
 *		The value pointed to by EventSet is then set to PAPI_NULL on success. 
 *
 *	@retval PAPI_EINVAL
 *		One or more of the arguments is invalid.
 *		Attempting to destroy a non-empty event set or passing in a null pointer to be destroyed.
 *	@retval PAPI_ENOEVST
 *		The EventSet specified does not exist.
 *	@retval PAPI_EISRUN
 *		The EventSet is currently counting events.
 *	@retval PAPI_EBUG
 *		Internal error, send mail to <ptools-perfapi@icl.utk.edu> and complain.
 *
 *	@par Examples:
 *	@code
 *	// Free all memory and data structures, EventSet must be empty.
 *	if ( PAPI_destroy_eventset( &EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	@endcode
 *
 *	@bug
 *	If the user has set profile on an event with the call, then when destroying 
 *	the EventSet the memory allocated by will not be freed. 
 *	The user should turn off profiling on the Events before destroying the 
 *	EventSet to prevent this behavior.
 *
 *	@see PAPI_profil @n
 *	PAPI_create_eventset @n
 *	PAPI_add_event @n
 *	PAPI_stop
 */
int
PAPI_destroy_eventset( int *EventSet )
{
	APIDBG("Entry: EventSet: %p, *EventSet: %d\n", EventSet, *EventSet);

	EventSetInfo_t *ESI;

	/* check for pre-existing ESI */

	if ( EventSet == NULL )
		papi_return( PAPI_EINVAL );

	ESI = _papi_hwi_lookup_EventSet( *EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	if ( !( ESI->state & PAPI_STOPPED ) )
		papi_return( PAPI_EISRUN );

	if ( ESI->NumberOfEvents )
		papi_return( PAPI_EINVAL );

	_papi_hwi_remove_EventSet( ESI );
	*EventSet = PAPI_NULL;

	return PAPI_OK;
}

/* simply checks for valid EventSet, calls component start() call */
/** @class PAPI_start
 *	@brief Start counting hardware events in an event set.
 *
 * @par C Interface:
 *     \#include <papi.h> @n
 *     int PAPI_start( int  EventSet );
 *
 *	@param EventSet
 *		-- an integer handle for a PAPI event set as created by PAPI_create_eventset
 *
 *	@retval PAPI_OK 
 *	@retval PAPI_EINVAL 
 *		-- One or more of the arguments is invalid.
 *	@retval PAPI_ESYS 
 *		-- A system or C library call failed inside PAPI, see the errno variable.
 *	@retval PAPI_ENOEVST 
 *		-- The EventSet specified does not exist.
 *	@retval PAPI_EISRUN 
 *		-- The EventSet is currently counting events.
 *	@retval PAPI_ECNFLCT 
 *		-- The underlying counter hardware can not count this event and other events 
 *		in the EventSet simultaneously.
 *	@retval PAPI_ENOEVNT 
 *		-- The PAPI preset is not available on the underlying hardware. 
 *
 *	PAPI_start starts counting all of the hardware events contained in the previously defined EventSet. 
 *	All counters are implicitly set to zero before counting.
 *  Assumes an initialized PAPI library and a properly added event set. 
 *
 *  @par Example:
 *  @code
 *  int EventSet = PAPI_NULL;
 *  long long values[2];
 *  int ret;
 *  
 *  ret = PAPI_create_eventset(&EventSet);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  
 *  // Add Total Instructions Executed to our EventSet
 *  ret = PAPI_add_event(EventSet, PAPI_TOT_INS);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  
 *  // Start counting
 *  ret = PAPI_start(EventSet);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  poorly_tuned_function();
 *  ret = PAPI_stop(EventSet, values);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  printf("%lld\\n",values[0]);
 *  @endcode
 *
 *	@see  PAPI_create_eventset PAPI_add_event PAPI_stop
 */
int
PAPI_start( int EventSet )
{
	APIDBG("Entry: EventSet: %d\n", EventSet);

	int is_dirty=0;
	int i,retval;
	EventSetInfo_t *ESI;
	ThreadInfo_t *thread = NULL;
	CpuInfo_t *cpu = NULL;
	hwd_context_t *context;
	int cidx;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL ) {
	   papi_return( PAPI_ENOEVST );
	}

	APIDBG("EventSet: %p\n", ESI);

	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 ) {
	   papi_return( cidx );
	}

	/* only one event set per thread  can be running at any time,    */
	/* so if another event set is running, the user must stop that   */
        /* event set explicitly */

	/* We used to check and not let multiple events be attached */
	/* to the same CPU, but this was unnecessary?               */

      	thread = ESI->master;
	cpu = ESI->CpuInfo;

	if ( thread->running_eventset[cidx] ) {
           APIDBG("Thread Running already (Only one active Eventset per component)\n");
	   papi_return( PAPI_EISRUN );
	}

	/* Check that there are added events */
	if ( ESI->NumberOfEvents < 1 ) {
	   papi_return( PAPI_EINVAL );
	}

	/* If multiplexing is enabled for this eventset,
	   call John May's code. */

	if ( _papi_hwi_is_sw_multiplex( ESI ) ) {
	   retval = MPX_start( ESI->multiplex.mpx_evset );
	   if ( retval != PAPI_OK ) {
	      papi_return( retval );
	   }

	   /* Update the state of this EventSet */
	   ESI->state ^= PAPI_STOPPED;
	   ESI->state |= PAPI_RUNNING;

	   return PAPI_OK;
	}

	/* get the context we should use for this event set */
	context = _papi_hwi_get_context( ESI, &is_dirty );
	if (is_dirty) {
	   /* we need to reset the context state because it was last used   */
	   /* for some other event set and does not contain the information */
           /* for our events.                                               */
	   retval = _papi_hwd[ESI->CmpIdx]->update_control_state(
                                                        ESI->ctl_state,
							ESI->NativeInfoArray,
							ESI->NativeCount,
							context);
	   if ( retval != PAPI_OK ) {
	      papi_return( retval );
	   }

	   //update_control_state disturbs the overflow settings so set 
	   //it to initial values again
	   if ( ESI->overflow.flags & PAPI_OVERFLOW_HARDWARE ) {
           	for( i = 0; i < ESI->overflow.event_counter; i++ ) {
	               	retval = _papi_hwd[ESI->CmpIdx]->set_overflow( ESI,
                                                                       ESI->overflow.EventIndex[i],
                                                                       ESI->overflow.threshold[i] );
                       if ( retval != PAPI_OK ) {
	                       	break;
             		}
          	}
          } 

	   /* now that the context contains this event sets information,    */
	   /* make sure the position array in the EventInfoArray is correct */

	   /* We have to do this because ->update_control_state() can */
	   /* in theory re-order the native events out from under us. */
	   _papi_hwi_map_events_to_native( ESI );

	}

	/* If overflowing is enabled, turn it on */
	if ( ( ESI->state & PAPI_OVERFLOWING ) &&
	     !( ESI->overflow.flags & PAPI_OVERFLOW_HARDWARE ) ) {
	   retval = _papi_hwi_start_signal( _papi_os_info.itimer_sig,
					    NEED_CONTEXT, cidx );
	   if ( retval != PAPI_OK ) {
	      papi_return( retval );
	   }

	   /* Update the state of this EventSet and thread */
	   /* before to avoid races                        */
	   ESI->state ^= PAPI_STOPPED;
	   ESI->state |= PAPI_RUNNING;
           /* can not be attached to thread or cpu if overflowing */
	   thread->running_eventset[cidx] = ESI;

	   retval = _papi_hwd[cidx]->start( context, ESI->ctl_state );
	   if ( retval != PAPI_OK ) {
	      _papi_hwi_stop_signal( _papi_os_info.itimer_sig );
	      ESI->state ^= PAPI_RUNNING;
	      ESI->state |= PAPI_STOPPED;
	      thread->running_eventset[cidx] = NULL;
	      papi_return( retval );
	   }

	   retval = _papi_hwi_start_timer( _papi_os_info.itimer_num,
					   _papi_os_info.itimer_sig,
					   _papi_os_info.itimer_ns );
	   if ( retval != PAPI_OK ) {
	      _papi_hwi_stop_signal( _papi_os_info.itimer_sig );
	      _papi_hwd[cidx]->stop( context, ESI->ctl_state );
	      ESI->state ^= PAPI_RUNNING;
	      ESI->state |= PAPI_STOPPED;
	      thread->running_eventset[cidx] = NULL;
	      papi_return( retval );
	   }
	} else {
	   /* Update the state of this EventSet and thread before */
	   /* to avoid races                                      */
	   ESI->state ^= PAPI_STOPPED;
	   ESI->state |= PAPI_RUNNING;

	   /* if not attached to cpu or another process */
	   if ( !(ESI->state & PAPI_CPU_ATTACHED) ) {
	      if ( !( ESI->state & PAPI_ATTACHED ) ) {
		 thread->running_eventset[cidx] = ESI;
	      }
	   } else {
	      cpu->running_eventset[cidx] = ESI;
	   }

	   retval = _papi_hwd[cidx]->start( context, ESI->ctl_state );
	   if ( retval != PAPI_OK ) {
	      _papi_hwd[cidx]->stop( context, ESI->ctl_state );
	      ESI->state ^= PAPI_RUNNING;
	      ESI->state |= PAPI_STOPPED;
	      if ( !(ESI->state & PAPI_CPU_ATTACHED) ) {
		 if ( !( ESI->state & PAPI_ATTACHED ) ) 
		    thread->running_eventset[cidx] = NULL;
	      } else {
		 cpu->running_eventset[cidx] = NULL;
	      }
	      papi_return( retval );
	   }
	}

	return retval;
}

/* checks for valid EventSet, calls component stop() function. */
/** @class PAPI_stop
 *	@brief Stop counting hardware events in an event set. 
 *
 * @par C Interface:
 *     \#include <papi.h> @n
 *     int PAPI_stop( int  EventSet, long long * values );
 *
 *	@param EventSet
 *		-- an integer handle for a PAPI event set as created by PAPI_create_eventset
 *	@param values
 *		-- an array to hold the counter values of the counting events 
 *
 *	@retval PAPI_OK 
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ESYS 
 *		A system or C library call failed inside PAPI, see the errno variable.
 *	@retval PAPI_ENOEVST 
 *		The EventSet specified does not exist.
 *	@retval PAPI_ENOTRUN 
 *		The EventSet is currently not running.
 *
 *	PAPI_stop halts the counting of a previously defined event set and the 
 *	counter values contained in that EventSet are copied into the values array
 *	Assumes an initialized PAPI library and a properly added event set. 
 *
 *  @par Example:
 *  @code
 *  int EventSet = PAPI_NULL;
 *  long long values[2];
 *  int ret;
 *  
 *  ret = PAPI_create_eventset(&EventSet);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  
 *  // Add Total Instructions Executed to our EventSet
 *  ret = PAPI_add_event(EventSet, PAPI_TOT_INS);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  
 *  // Start counting
 *  ret = PAPI_start(EventSet);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  poorly_tuned_function();
 *  ret = PAPI_stop(EventSet, values);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  printf("%lld\\n",values[0]);
 *  @endcode
 *
 *	@see  PAPI_create_eventset PAPI_start
 */
int
PAPI_stop( int EventSet, long long *values )
{
   APIDBG("Entry: EventSet: %d, values: %p\n", EventSet, values);
	EventSetInfo_t *ESI;
	hwd_context_t *context;
	int cidx, retval;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 )
		papi_return( cidx );

	if ( !( ESI->state & PAPI_RUNNING ) )
		papi_return( PAPI_ENOTRUN );

	/* If multiplexing is enabled for this eventset, turn if off */

	if ( _papi_hwi_is_sw_multiplex( ESI ) ) {
		retval = MPX_stop( ESI->multiplex.mpx_evset, values );
		if ( retval != PAPI_OK )
			papi_return( retval );

		/* Update the state of this EventSet */

		ESI->state ^= PAPI_RUNNING;
		ESI->state |= PAPI_STOPPED;

		return ( PAPI_OK );
	}

	/* get the context we should use for this event set */
	context = _papi_hwi_get_context( ESI, NULL );
	/* Read the current counter values into the EventSet */
	retval = _papi_hwi_read( context, ESI, ESI->sw_stop );
	if ( retval != PAPI_OK )
		papi_return( retval );

	/* Remove the control bits from the active counter config. */
	retval = _papi_hwd[cidx]->stop( context, ESI->ctl_state );
	if ( retval != PAPI_OK )
		papi_return( retval );
	if ( values )
		memcpy( values, ESI->sw_stop,
				( size_t ) ESI->NumberOfEvents * sizeof ( long long ) );

	/* If kernel profiling is in use, flush and process the kernel buffer */

	if ( ESI->state & PAPI_PROFILING ) {
		if ( _papi_hwd[cidx]->cmp_info.kernel_profile &&
			 !( ESI->profile.flags & PAPI_PROFIL_FORCE_SW ) ) {
			retval = _papi_hwd[cidx]->stop_profiling( ESI->master, ESI );
			if ( retval < PAPI_OK )
				papi_return( retval );
		}
	}

	/* If overflowing is enabled, turn it off */

	if ( ESI->state & PAPI_OVERFLOWING ) {
		if ( !( ESI->overflow.flags & PAPI_OVERFLOW_HARDWARE ) ) {
			retval = _papi_hwi_stop_timer( _papi_os_info.itimer_num,
						       _papi_os_info.itimer_sig );
			if ( retval != PAPI_OK )
				papi_return( retval );
			_papi_hwi_stop_signal( _papi_os_info.itimer_sig );
		}
	}

	/* Update the state of this EventSet */

	ESI->state ^= PAPI_RUNNING;
	ESI->state |= PAPI_STOPPED;

	/* Update the running event set for this thread */
	if ( !(ESI->state & PAPI_CPU_ATTACHED) ) {
		if ( !( ESI->state & PAPI_ATTACHED ))
			ESI->master->running_eventset[cidx] = NULL;
	} else {
		ESI->CpuInfo->running_eventset[cidx] = NULL;
	}
	
#if defined(DEBUG)
	if ( _papi_hwi_debug & DEBUG_API ) {
		int i;
		for ( i = 0; i < ESI->NumberOfEvents; i++ ) {
			APIDBG( "PAPI_stop ESI->sw_stop[%d]:\t%llu\n", i, ESI->sw_stop[i] );
		}
	}
#endif

	return ( PAPI_OK );
}

/** @class PAPI_reset
 * @brief Reset the hardware event counts in an event set.
 *
 *	@par C Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_reset( int EventSet );
 *
 *	@param EventSet
 *		an integer handle for a PAPI event set as created by PAPI_create_eventset 
 *
 *	@retval PAPI_OK 
 *	@retval PAPI_ESYS 
 *		A system or C library call failed inside PAPI, see the errno variable.
 *	@retval PAPI_ENOEVST 
 *		The EventSet specified does not exist. 
 *  @details
 *	PAPI_reset() zeroes the values of the counters contained in EventSet. 
 *	This call assumes an initialized PAPI library and a properly added event set 
 *
 *	@par Example:
 *	@code
int EventSet = PAPI_NULL;
int Events[] = {PAPI_TOT_INS, PAPI_FP_OPS};
int ret;
 
// Create an empty EventSet
ret = PAPI_create_eventset(&EventSet);
if (ret != PAPI_OK) handle_error(ret);

// Add two events to our EventSet
ret = PAPI_add_events(EventSet, Events, 2);
if (ret != PAPI_OK) handle_error(ret);

// Start counting
ret = PAPI_start(EventSet);
if (ret != PAPI_OK) handle_error(ret);

// Stop counting, ignore values
ret = PAPI_stop(EventSet, NULL);
if (ret != PAPI_OK) handle_error(ret);

// reset the counters in this EventSet
ret = PAPI_reset(EventSet);
if (ret != PAPI_OK) handle_error(ret);
 *	@endcode
 *
 *	@see PAPI_create_eventset
 */
int
PAPI_reset( int EventSet )
{
	APIDBG("Entry: EventSet: %d\n", EventSet);
	int retval = PAPI_OK;
	EventSetInfo_t *ESI;
	hwd_context_t *context;
	int cidx;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 )
		papi_return( cidx );

	if ( ESI->state & PAPI_RUNNING ) {
		if ( _papi_hwi_is_sw_multiplex( ESI ) ) {
			retval = MPX_reset( ESI->multiplex.mpx_evset );
		} else {
			/* If we're not the only one running, then just
			   read the current values into the ESI->start
			   array. This holds the starting value for counters
			   that are shared. */
			/* get the context we should use for this event set */
			context = _papi_hwi_get_context( ESI, NULL );
			retval = _papi_hwd[cidx]->reset( context, ESI->ctl_state );
		}
	} else {
#ifdef __bgp__
		//  For BG/P, we always want to reset the 'real' hardware counters.  The counters
		//  can be controlled via multiple interfaces, and we need to ensure that the values
		//  are truly zero...
		/* get the context we should use for this event set */
		context = _papi_hwi_get_context( ESI, NULL );
		retval = _papi_hwd[cidx]->reset( context, ESI->ctl_state );
#endif
		memset( ESI->sw_stop, 0x00,
				( size_t ) ESI->NumberOfEvents * sizeof ( long long ) );
	}

	APIDBG( "EXIT: retval %d\n", retval );
	papi_return( retval );
}

/** @class PAPI_read
 *  @brief Read hardware counters from an event set.
 *	
 *  @par C Interface:
 *  \#include <papi.h> @n
 *  int PAPI_read(int  EventSet, long_long * values );
 *
 *  PAPI_read() copies the counters of the indicated event set into 
 *  the provided array. 
 *
 *  The counters continue counting after the read. 
 *
 *  Note the differences between PAPI_read() and PAPI_accum(), specifically
 *  that PAPI_accum() resets the values array to zero.
 *
 *  PAPI_read() assumes an initialized PAPI library and a properly added 
 *  event set. 
 *
 *  @param[in] EventSet
 *     -- an integer handle for a PAPI Event Set as created 
 *        by PAPI_create_eventset()
 *  @param[out] *values 
 *     -- an array to hold the counter values of the counting events 
 *
 *  @retval PAPI_EINVAL 
 *	    One or more of the arguments is invalid.
 *  @retval PAPI_ESYS 
 *	    A system or C library call failed inside PAPI, see the 
 *          errno variable.
 *  @retval PAPI_ENOEVST 
 *	    The event set specified does not exist. 
 *	
 * @par Examples
 * @code
 * do_100events();
 * if (PAPI_read(EventSet, values) != PAPI_OK)
 *    handle_error(1);
 * // values[0] now equals 100
 * do_100events();
 * if (PAPI_accum(EventSet, values) != PAPI_OK)
 *    handle_error(1);
 * // values[0] now equals 200
 * values[0] = -100;
 * do_100events();
 * if (PAPI_accum(EventSet, values) != PAPI_OK)
 *     handle_error(1);
 * // values[0] now equals 0 
 * @endcode
 *
 * @see PAPI_accum 
 * @see PAPI_start 
 * @see PAPI_stop 
 * @see PAPI_reset
 */
int
PAPI_read( int EventSet, long long *values )
{
	APIDBG( "Entry: EventSet: %d, values: %p\n", EventSet, values);
	EventSetInfo_t *ESI;
	hwd_context_t *context;
	int cidx, retval = PAPI_OK;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 )
		papi_return( cidx );

	if ( values == NULL )
		papi_return( PAPI_EINVAL );

	if ( ESI->state & PAPI_RUNNING ) {
		if ( _papi_hwi_is_sw_multiplex( ESI ) ) {
		  retval = MPX_read( ESI->multiplex.mpx_evset, values, 0 );
		} else {
			/* get the context we should use for this event set */
			context = _papi_hwi_get_context( ESI, NULL );
			retval = _papi_hwi_read( context, ESI, values );
		}
		if ( retval != PAPI_OK )
			papi_return( retval );
	} else {
		memcpy( values, ESI->sw_stop,
				( size_t ) ESI->NumberOfEvents * sizeof ( long long ) );
	}

#if defined(DEBUG)
	if ( ISLEVEL( DEBUG_API ) ) {
		int i;
		for ( i = 0; i < ESI->NumberOfEvents; i++ ) {
			APIDBG( "PAPI_read values[%d]:\t%lld\n", i, values[i] );
		}
	}
#endif

	APIDBG( "PAPI_read returns %d\n", retval );
	return ( PAPI_OK );
}

/** @class PAPI_read_ts
 *  @brief Read hardware counters with a timestamp.
 *	
 *  @par C Interface:
 *  \#include <papi.h> @n
 *  int PAPI_read_ts(int EventSet, long long *values, long long *cycles );
 *
 *  PAPI_read_ts() copies the counters of the indicated event set into 
 *  the provided array.  It also places a real-time cycle timestamp 
 *  into the cycles array.
 *
 *  The counters continue counting after the read. 
 *
 *  PAPI_read_ts() assumes an initialized PAPI library and a properly added 
 *  event set. 
 *
 *  @param[in] EventSet
 *     -- an integer handle for a PAPI Event Set as created 
 *        by PAPI_create_eventset()
 *  @param[out] *values 
 *     -- an array to hold the counter values of the counting events 
 *  @param[out] *cycles
 *     -- an array to hold the timestamp values
 *
 *  @retval PAPI_EINVAL 
 *	    One or more of the arguments is invalid.
 *  @retval PAPI_ESYS 
 *	    A system or C library call failed inside PAPI, see the 
 *          errno variable.
 *  @retval PAPI_ENOEVST 
 *	    The event set specified does not exist. 
 *	
 * @par Examples
 * @code
 * @endcode
 *
 * @see PAPI_read 
 * @see PAPI_accum 
 * @see PAPI_start 
 * @see PAPI_stop 
 * @see PAPI_reset
 */
int
PAPI_read_ts( int EventSet, long long *values, long long *cycles )
{
	APIDBG( "Entry: EventSet: %d, values: %p, cycles: %p\n", EventSet, values, cycles);
	EventSetInfo_t *ESI;
	hwd_context_t *context;
	int cidx, retval = PAPI_OK;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 )
		papi_return( cidx );

	if ( values == NULL )
		papi_return( PAPI_EINVAL );

	if ( ESI->state & PAPI_RUNNING ) {
		if ( _papi_hwi_is_sw_multiplex( ESI ) ) {
		  retval = MPX_read( ESI->multiplex.mpx_evset, values, 0 );
		} else {
			/* get the context we should use for this event set */
			context = _papi_hwi_get_context( ESI, NULL );
			retval = _papi_hwi_read( context, ESI, values );
		}
		if ( retval != PAPI_OK )
			papi_return( retval );
	} else {
		memcpy( values, ESI->sw_stop,
				( size_t ) ESI->NumberOfEvents * sizeof ( long long ) );
	}

	*cycles = _papi_os_vector.get_real_cycles(  );

#if defined(DEBUG)
	if ( ISLEVEL( DEBUG_API ) ) {
		int i;
		for ( i = 0; i < ESI->NumberOfEvents; i++ ) {
			APIDBG( "PAPI_read values[%d]:\t%lld\n", i, values[i] );
		}
	}
#endif

	APIDBG( "PAPI_read_ts returns %d\n", retval );
	return PAPI_OK;
}

/**	@class PAPI_accum
 *	@brief Accumulate and reset counters in an EventSet.
 *	
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_accum( int  EventSet, long_long * values );
 *
 *	These calls assume an initialized PAPI library and a properly added event set. 
 *	PAPI_accum adds the counters of the indicated event set into the array values. 
 *	The counters are zeroed and continue counting after the operation.
 *	Note the differences between PAPI_read and PAPI_accum, specifically 
 *	that PAPI_accum resets the values array to zero. 
 *
 *	@param EventSet
 *		an integer handle for a PAPI Event Set 
 *		as created by PAPI_create_eventset
 *	@param *values 
 *		an array to hold the counter values of the counting events 
 *
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ESYS 
 *		A system or C library call failed inside PAPI, see the errno variable.
 *	@retval PAPI_ENOEVST 
 *		The event set specified does not exist. 
 *
 *	@par Examples:
 *	@code
 *	do_100events( );
 *	if ( PAPI_read( EventSet, values) != PAPI_OK )
 *	handle_error( 1 );
 *	// values[0] now equals 100
 *	do_100events( );
 *	if (PAPI_accum( EventSet, values ) != PAPI_OK )
 *	handle_error( 1 );
 *	// values[0] now equals 200
 *	values[0] = -100;
 *	do_100events( );
 *	if (PAPI_accum( EventSet, values ) != PAPI_OK )
 *	handle_error( 1 );
 *	// values[0] now equals 0
 *	@endcode
 *
 *	@see PAPIF_accum
 *	@see PAPI_start
 *	@see PAPI_set_opt
 *	@see PAPI_reset
 */
int
PAPI_accum( int EventSet, long long *values )
{
	APIDBG("Entry: EventSet: %d, values: %p\n", EventSet, values);
	EventSetInfo_t *ESI;
	hwd_context_t *context;
	int i, cidx, retval;
	long long a, b, c;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 )
		papi_return( cidx );

	if ( values == NULL )
		papi_return( PAPI_EINVAL );

	if ( ESI->state & PAPI_RUNNING ) {
		if ( _papi_hwi_is_sw_multiplex( ESI ) ) {
		  retval = MPX_read( ESI->multiplex.mpx_evset, ESI->sw_stop, 0 );
		} else {
			/* get the context we should use for this event set */
			context = _papi_hwi_get_context( ESI, NULL );
			retval = _papi_hwi_read( context, ESI, ESI->sw_stop );
		}
		if ( retval != PAPI_OK )
			papi_return( retval );
	}

	for ( i = 0; i < ESI->NumberOfEvents; i++ ) {
		a = ESI->sw_stop[i];
		b = values[i];
		c = a + b;
		values[i] = c;
	}

	papi_return( PAPI_reset( EventSet ) );
}

/** @class PAPI_write
 *	@brief Write counter values into counters.
 *
 *	@param EventSet 
 *		an integer handle for a PAPI event set as created by PAPI_create_eventset
 *	@param *values
 *		an array to hold the counter values of the counting events 
 *
 *	@retval PAPI_ENOEVST 
 *		The EventSet specified does not exist.
 *	@retval PAPI_ECMP 
 *		PAPI_write() is not implemented for this architecture. 
 *      @retval PAPI_ESYS 
 *              The EventSet is currently counting events and 
 *		the component could not change the values of the 
 *              running counters.
 *
 *	PAPI_write() writes the counter values provided in the array values 
 *	into the event set EventSet. 
 *	The virtual counters managed by the PAPI library will be set to the values provided. 
 *	If the event set is running, an attempt will be made to write the values 
 *	to the running counters. 
 *	This operation is not permitted by all components and may result in a run-time error. 
 *
 *	@see PAPI_read
 */
int
PAPI_write( int EventSet, long long *values )
{
	APIDBG("Entry: EventSet: %d, values: %p\n", EventSet, values);

	int cidx, retval = PAPI_OK;
	EventSetInfo_t *ESI;
	hwd_context_t *context;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 )
		papi_return( cidx );

	if ( values == NULL )
		papi_return( PAPI_EINVAL );

	if ( ESI->state & PAPI_RUNNING ) {
		/* get the context we should use for this event set */
		context = _papi_hwi_get_context( ESI, NULL );
		retval = _papi_hwd[cidx]->write( context, ESI->ctl_state, values );
		if ( retval != PAPI_OK )
			return ( retval );
	}

	memcpy( ESI->hw_start, values,
			( size_t ) _papi_hwd[cidx]->cmp_info.num_cntrs *
			sizeof ( long long ) );

	return ( retval );
}

/** @class PAPI_cleanup_eventset
 *	@brief Empty and destroy an EventSet.
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_cleanup_eventset( int  EventSet );
 *
 * PAPI_cleanup_eventset removes all events from a PAPI event set and turns 
 * off profiling and overflow for all events in the EventSet.
 * This can not be called if the EventSet is not stopped.
 *
 *	@param EventSet
 *		An integer handle for a PAPI event set as created by PAPI_create_eventset.
 *
 *	@retval PAPI_EINVAL
 *		One or more of the arguments is invalid.
 *		Attempting to destroy a non-empty event set or passing in a null pointer to be destroyed.
 *	@retval PAPI_ENOEVST
 *		The EventSet specified does not exist.
 *	@retval PAPI_EISRUN
 *		The EventSet is currently counting events.
 *	@retval PAPI_EBUG
 *		Internal error, send mail to <ptools-perfapi@icl.utk.edu> and complain.
 *
 *	@par Examples:
 *	@code
 *	// Remove all events in the eventset
 *	if ( PAPI_cleanup_eventset( EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	@endcode
 *
 *	@bug
 *	If the user has set profile on an event with the call, then when destroying 
 *	the EventSet the memory allocated by will not be freed. 
 *	The user should turn off profiling on the Events before destroying the 
 *	EventSet to prevent this behavior.
 *
 *	@see PAPI_profil @n
 *	PAPI_create_eventset @n
 *	PAPI_add_event @n
 *	PAPI_stop
 */
int
PAPI_cleanup_eventset( int EventSet )
{
	APIDBG("Entry: EventSet: %d\n",EventSet);

	EventSetInfo_t *ESI;
	int i, cidx, total, retval;

	/* Is the EventSet already in existence? */

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	/* if the eventset has no index and no events, return OK
	   otherwise return NOCMP */
	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 ) {
		if ( ESI->NumberOfEvents )
			papi_return( cidx );
		papi_return( PAPI_OK );
	}

	/* Of course, it must be stopped in order to modify it. */

	if ( ESI->state & PAPI_RUNNING )
		papi_return( PAPI_EISRUN );

	/* clear overflow flag and turn off hardware overflow handler */
	if ( ESI->state & PAPI_OVERFLOWING ) {
		total = ESI->overflow.event_counter;
		for ( i = 0; i < total; i++ ) {
			retval = PAPI_overflow( EventSet,
									ESI->overflow.EventCode[0], 0, 0, NULL );
			if ( retval != PAPI_OK )
				papi_return( retval );
		}
	}

	/* clear profile flag and turn off hardware profile handler */
	if ( ( ESI->state & PAPI_PROFILING ) &&
		 _papi_hwd[cidx]->cmp_info.hardware_intr &&
		 !( ESI->profile.flags & PAPI_PROFIL_FORCE_SW ) ) {
		total = ESI->profile.event_counter;
		for ( i = 0; i < total; i++ ) {
			retval =
				PAPI_sprofil( NULL, 0, EventSet, ESI->profile.EventCode[0], 0,
							  PAPI_PROFIL_POSIX );
			if ( retval != PAPI_OK )
				papi_return( retval );
		}
	}

	if ( _papi_hwi_is_sw_multiplex( ESI ) ) {
		retval = MPX_cleanup( &ESI->multiplex.mpx_evset );
		if ( retval != PAPI_OK )
			papi_return( retval );
	}

	retval = _papi_hwd[cidx]->cleanup_eventset( ESI->ctl_state );
	if ( retval != PAPI_OK ) 
		papi_return( retval );

	/* Now do the magic */
	papi_return( _papi_hwi_cleanup_eventset( ESI ) );
}

/**	@class PAPI_multiplex_init
 *	@brief Initialize multiplex support in the PAPI library.
 *
 *	PAPI_multiplex_init() enables and initializes multiplex support in 
 *      the PAPI library. 
 *	Multiplexing allows a user to count more events than total physical 
 *      counters by time sharing the existing counters at some loss in 
 *      precision. 
 *	Applications that make no use of multiplexing do not need to call 
 *      this routine. 
 *
 * @par C Interface:
 * \#include <papi.h> @n
 * int PAPI_multiplex_init (void);
 *
 * @par Examples
 * @code
 * retval = PAPI_multiplex_init();
 * @endcode

 * @retval PAPI_OK This call always returns PAPI_OK
 *
 * @see PAPI_set_multiplex 
 * @see PAPI_get_multiplex
 */
int
PAPI_multiplex_init( void )
{
	APIDBG("Entry:\n");

	int retval;

	retval = mpx_init( _papi_os_info.itimer_ns );
	papi_return( retval );
}

/** @class PAPI_state
 * @brief Return the counting state of an EventSet.
 *
 * @par C Interface:
 *     \#include <papi.h> @n
 *     int PAPI_state( int  EventSet, int * status );
 *
 *	@param EventSet -- an integer handle for a PAPI event set as created by PAPI_create_eventset
 *	@param status -- an integer containing a boolean combination of one or more of the 
 *	following nonzero constants as defined in the PAPI header file papi.h:
 *	@arg PAPI_STOPPED	-- EventSet is stopped
 *	@arg PAPI_RUNNING	-- EventSet is running
 *	@arg PAPI_PAUSED	-- EventSet temporarily disabled by the library
 *	@arg PAPI_NOT_INIT	-- EventSet defined, but not initialized
 *	@arg PAPI_OVERFLOWING	-- EventSet has overflowing enabled
 *	@arg PAPI_PROFILING	-- EventSet has profiling enabled
 *	@arg PAPI_MULTIPLEXING	-- EventSet has multiplexing enabled
 *	@arg PAPI_ACCUMULATING	-- reserved for future use
 *	@arg PAPI_HWPROFILING	-- reserved for future use 
 *  @manonly
 *  @endmanonly
 *
 *	@retval PAPI_OK 
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOEVST 
 *		The EventSet specified does not exist. 
 *  @manonly
 *  @endmanonly
 *
 *	PAPI_state() returns the counting state of the specified event set.
 *  @manonly
 *  @endmanonly
 *
 *  @par Example:
 *  @code
 *  int EventSet = PAPI_NULL;
 *  int status = 0;
 *  int ret;
 *  
 *  ret = PAPI_create_eventset(&EventSet);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  
 *  // Add Total Instructions Executed to our EventSet
 *  ret = PAPI_add_event(EventSet, PAPI_TOT_INS);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  
 *  // Start counting
 *  ret = PAPI_state(EventSet, &status);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  printf("State is now %d\n",status);
 *  ret = PAPI_start(EventSet);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  ret = PAPI_state(EventSet, &status);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  printf("State is now %d\n",status);
 *  @endcode
 *
 *	@see PAPI_stop PAPI_start
 */
int
PAPI_state( int EventSet, int *status )
{
	APIDBG("Entry: EventSet: %d, status: %p\n", EventSet, status);

	EventSetInfo_t *ESI;

	if ( status == NULL )
		papi_return( PAPI_EINVAL );

	/* check for good EventSetIndex value */

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	/*read status FROM ESI->state */

	*status = ESI->state;

	return ( PAPI_OK );
}

/** @class PAPI_set_debug
 * @brief Set the current debug level for error output from PAPI.
 *
 * @par C Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_set_debug( int level );
 *
 * @param level
 *		one of the constants shown in the table below and defined in the papi.h 
 *		header file. @n
 *	The possible debug levels for debugging are shown below.
 *	@arg PAPI_QUIET			Do not print anything, just return the error code
 *	@arg PAPI_VERB_ECONT	Print error message and continue
 *	@arg PAPI_VERB_ESTOP	Print error message and exit 
 *  @n
 *	@retval PAPI_OK 
 *	@retval PAPI_EINVAL
 *		The debug level is invalid.
 *  @n@n
 *
 *	The current debug level is used by both the internal error and debug message 
 *	handler subroutines. @n
 *	The debug handler is only used if the library was compiled with -DDEBUG. @n
 *	The debug handler is called when there is an error upon a call to the PAPI API.@n 
 *	The error handler is always active and its behavior cannot be modified except 
 *	for whether or not it prints anything.
 *	
 *	The default PAPI debug handler prints out messages in the following form: @n
 *		PAPI Error: Error Code code, symbol, description 
 *
 *	If the error was caused from a system call and the return code is PAPI_ESYS, 
 *	the message will have a colon space and the error string as reported by 
 *	strerror() appended to the end.
 *
 *	The PAPI error handler prints out messages in the following form: @n
 *				PAPI Error: message. 
 *  @n
 *	@note This is the ONLY function that may be called BEFORE PAPI_library_init(). 
 *  @n
 *	@par Example:
 *	@code
 int ret;
 ret = PAPI_set_debug(PAPI_VERB_ECONT);
 if ( ret != PAPI_OK ) handle_error();
 *	@endcode
 *
 *	@see  PAPI_library_init
 *	@see  PAPI_get_opt
 *	@see  PAPI_set_opt
 */
int
PAPI_set_debug( int level )
{
	APIDBG("Entry: level: %d\n", level);
	PAPI_option_t option;

	memset( &option, 0x0, sizeof ( option ) );
	option.debug.level = level;
	option.debug.handler = _papi_hwi_debug_handler;
	return ( PAPI_set_opt( PAPI_DEBUG, &option ) );
}

/* Attaches to or detaches from the specified thread id */
inline_static int
_papi_set_attach( int option, int EventSet, unsigned long tid )
{
	APIDBG("Entry: option: %d, EventSet: %d, tid: %lu\n", option, EventSet, tid);
	PAPI_option_t attach;

	memset( &attach, 0x0, sizeof ( attach ) );
	attach.attach.eventset = EventSet;
	attach.attach.tid = tid;
	return ( PAPI_set_opt( option, &attach ) );
}

/** @class PAPI_attach
 *	@brief Attach PAPI event set to the specified thread id.
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_attach( int EventSet, unsigned long tid );
 *
 *	PAPI_attach is a wrapper function that calls PAPI_set_opt to allow PAPI to 
 *	monitor performance counts on a thread other than the one currently executing. 
 *	This is sometimes referred to as third party monitoring. 
 *	PAPI_attach connects the specified EventSet to the specified thread;
 *	PAPI_detach breaks that connection and restores the EventSet to the 
 *	original executing thread. 
 *
 *	@param EventSet 
 *		An integer handle for a PAPI EventSet as created by PAPI_create_eventset.
 *	@param tid 
 *		A thread id as obtained from, for example, PAPI_list_threads or PAPI_thread_id.
 *
 *	@retval PAPI_ECMP 
 *		This feature is unsupported on this component.
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOEVST 
 *		The event set specified does not exist.
 *	@retval PAPI_EISRUN 
 *		The event set is currently counting events. 
 *
 *	@par Examples:
 *	@code
 *	int EventSet = PAPI_NULL;
 *	unsigned long pid;
 *	pid = fork( );
 *	if ( pid <= 0 )
 *	exit( 1 );
 *	if ( PAPI_create_eventset( &EventSet ) != PAPI_OK )
 *	exit( 1 );
 *	// Add Total Instructions Executed to our EventSet
 *	if ( PAPI_add_event( EventSet, PAPI_TOT_INS ) != PAPI_OK )
 *	exit( 1 );
 *	// Attach this EventSet to the forked process
 *	if ( PAPI_attach( EventSet, pid ) != PAPI_OK )
 *	exit( 1 );
 *	@endcode
 *
 *	@see PAPI_set_opt
 *	@see PAPI_list_threads
 *	@see PAPI_thread_id
 *	@see PAPI_thread_init
 */
int
PAPI_attach( int EventSet, unsigned long tid )
{
	APIDBG( "Entry: EventSet: %d, tid: %lu\n", EventSet, tid);
	return ( _papi_set_attach( PAPI_ATTACH, EventSet, tid ) );
}

/** @class PAPI_detach
 *	@brief Detach PAPI event set from previously specified thread id and restore to executing thread.
 *	
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_detach( int  EventSet, unsigned long  tid );
 *
 *	PAPI_detach is a wrapper function that calls PAPI_set_opt to allow PAPI to 
 *	monitor performance counts on a thread other than the one currently executing. 
 *	This is sometimes referred to as third party monitoring. 
 *	PAPI_attach connects the specified EventSet to the specified thread;
 *	PAPI_detach breaks that connection and restores the EventSet to the 
 *	original executing thread. 
 *
 *	@param EventSet 
 *		An integer handle for a PAPI EventSet as created by PAPI_create_eventset.
 *	@param tid 
 *		A thread id as obtained from, for example, PAPI_list_threads or PAPI_thread_id.
 *
 *	@retval PAPI_ECMP
 *		This feature is unsupported on this component.
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOEVST 
 *		The event set specified does not exist.
 *	@retval PAPI_EISRUN 
 *		The event set is currently counting events. 
 *
 *	@par Examples:
 *	@code
 *	int EventSet = PAPI_NULL;
 *	unsigned long pid;
 *	pid = fork( );
 *	if ( pid <= 0 )
 *	exit( 1 );
 *	if ( PAPI_create_eventset( &EventSet ) != PAPI_OK )
 *	exit( 1 );
 *	// Add Total Instructions Executed to our EventSet
 *	if ( PAPI_add_event( EventSet, PAPI_TOT_INS ) != PAPI_OK )
 *	exit( 1 );
 *	// Attach this EventSet to the forked process
 *	if ( PAPI_attach( EventSet, pid ) != PAPI_OK )
 *	exit( 1 );
 *	@endcode
 *
 *	@see PAPI_set_opt @n
 *	PAPI_list_threads @n
 *	PAPI_thread_id @n
 *	PAPI_thread_init
 */
int
PAPI_detach( int EventSet )
{
	APIDBG( "Entry: EventSet: %d\n", EventSet);
	return ( _papi_set_attach( PAPI_DETACH, EventSet, 0 ) );
}

/** @class PAPI_set_multiplex
 *	@brief Convert a standard event set to a multiplexed event set. 
 *
 * @par C Interface:
 *     \#include <papi.h> @n
 *     int PAPI_set_multiplex( int  EventSet );
 *
 *	@param EventSet
 *		an integer handle for a PAPI event set as created by PAPI_create_eventset
 *
 *	@retval PAPI_OK
 *	@retval PAPI_EINVAL 
 *		-- One or more of the arguments is invalid, or the EventSet is already multiplexed.
 *	@retval PAPI_ENOCMP
 *		-- The EventSet specified is not yet bound to a component.
 *	@retval PAPI_ENOEVST 
 *		-- The EventSet specified does not exist.
 *	@retval PAPI_EISRUN 
 *		-- The EventSet is currently counting events.
 *	@retval PAPI_ENOMEM 
 *		-- Insufficient memory to complete the operation.
 *
 *	PAPI_set_multiplex converts a standard PAPI event set created by a call to 
 *	PAPI_create_eventset into an event set capable of handling multiplexed events. 
 *	This must be done after calling PAPI_multiplex_init, and either PAPI_add_event
 *	or PAPI_assign_eventset_component, but prior to calling PAPI_start(). 
 *	
 *	Events can be added to an event set either before or after converting it 
 *	into a multiplexed set, but the conversion must be done prior to using it 
 *	as a multiplexed set. 
 *
 *  @note Multiplexing can't be enabled until PAPI knows which component is targeted.
 *  Due to the late binding nature of PAPI event sets, this only happens after adding
 *  an event to an event set or explicitly binding the component with a call to
 *  PAPI_assign_eventset_component.
 *
 *	@par Example:
 *	@code
 *	int EventSet = PAPI_NULL;
 *	int ret;
 *	 
 *	// Create an empty EventSet
 *	ret = PAPI_create_eventset(&EventSet);
 *	if (ret != PAPI_OK) handle_error(ret);
 *	
 *	// Bind it to the CPU component
 *	ret = PAPI_assign_eventset_component(EventSet, 0);
 *	if (ret != PAPI_OK) handle_error(ret);
 *	
 *	// Check  current multiplex status
 *	ret = PAPI_get_multiplex(EventSet);
 *	if (ret == TRUE) printf("This event set is ready for multiplexing\n.")
 *	if (ret == FALSE) printf("This event set is not enabled for multiplexing\n.")
 *	if (ret < 0) handle_error(ret);
 *	
 *	// Turn on multiplexing
 *	ret = PAPI_set_multiplex(EventSet);
 *	if ((ret == PAPI_EINVAL) && (PAPI_get_multiplex(EventSet) == TRUE))
 *	  printf("This event set already has multiplexing enabled\n");
 *	else if (ret != PAPI_OK) handle_error(ret);
 *	@endcode
 *
 *	@see  PAPI_multiplex_init
 *	@see  PAPI_get_multiplex
 *	@see  PAPI_set_opt
 *	@see  PAPI_create_eventset
 */

int
PAPI_set_multiplex( int EventSet )
{
	APIDBG( "Entry: EventSet: %d\n", EventSet);

	PAPI_option_t mpx;
	EventSetInfo_t *ESI;
	int cidx;
	int ret;

	/* Is the EventSet already in existence? */

	ESI = _papi_hwi_lookup_EventSet( EventSet );

	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	/* if the eventset has no index return NOCMP */
	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 )
		papi_return( cidx );

	if ( ( ret = mpx_check( EventSet ) ) != PAPI_OK )
		papi_return( ret );

	memset( &mpx, 0x0, sizeof ( mpx ) );
	mpx.multiplex.eventset = EventSet;
	mpx.multiplex.flags = PAPI_MULTIPLEX_DEFAULT;
	mpx.multiplex.ns = _papi_os_info.itimer_ns;
	return ( PAPI_set_opt( PAPI_MULTIPLEX, &mpx ) );
}

/** @class PAPI_set_opt
 *	@brief Set PAPI library or event set options.
 *
 * @par C Interface:
 *     \#include <papi.h> @n
 *     int PAPI_set_opt(  int option, PAPI_option_t * ptr );
 *
 *	@param[in]	option
 *		Defines the option to be set. 
 *		Possible values are briefly described in the table below. 
 *
 *	@param[in,out] ptr
 *		Pointer to a structure determined by the selected option. See PAPI_option_t
 *		for a description of possible structures.
 *
 *	@retval PAPI_OK
 *	@retval PAPI_EINVAL The specified option or parameter is invalid.
 *	@retval PAPI_ENOEVST The EventSet specified does not exist.
 *	@retval PAPI_EISRUN The EventSet is currently counting events.
 *	@retval PAPI_ECMP
 *              The option is not implemented for the current component.
 *	@retval PAPI_ENOINIT PAPI has not been initialized.
 *	@retval PAPI_EINVAL_DOM Invalid domain has been requested.
 *
 *	PAPI_set_opt() changes the options of the PAPI library or a specific EventSet created 
 *	by PAPI_create_eventset. Some options may require that the EventSet be bound to a 
 *	component before they can execute successfully. This can be done either by adding an 
 *	event or by explicitly calling PAPI_assign_eventset_component. 
 *	
 *	Ptr is a pointer to the PAPI_option_t structure, which is actually a union of different
 *	structures for different options. Not all options require or return information in these
 *	structures. Each requires different values to be set. Some options require a component 
 *	index to be provided. These options are handled implicitly through the option structures. 
 *
 *	@note Some options, such as PAPI_DOMAIN and PAPI_MULTIPLEX
 *	are also available as separate entry points in both C and Fortran.
 *
 *	The reader is encouraged to peruse the ctests code in the PAPI distribution for examples
 *  of usage of PAPI_set_opt. 
 *
 *	@par Possible values for the PAPI_set_opt option parameter
 *  @manonly
 * OPTION 			DEFINITION
 * PAPI_DEFDOM		Set default counting domain for newly created event sets. Requires a 
 *					component index.
 * PAPI_DEFGRN		Set default counting granularity. Requires a component index.
 * PAPI_DEBUG		Set the PAPI debug state and the debug handler. The debug state is 
 *					specified in ptr->debug.level. The debug handler is specified in 
 *					ptr->debug.handler. For further information regarding debug states and
 *					the behavior of the handler, see PAPI_set_debug.
 * PAPI_MULTIPLEX	Enable specified EventSet for multiplexing.
 * PAPI_DEF_ITIMER	Set the type of itimer used in software multiplexing, overflowing 
 *					and profiling.
 * PAPI_DEF_MPX_NS	Set the sampling time slice in nanoseconds for multiplexing and overflow.
 * PAPI_DEF_ITIMER_NS See PAPI_DEF_MPX_NS.
 * PAPI_ATTACH		Attach EventSet specified in ptr->attach.eventset to thread or process id
 *					specified in in ptr->attach.tid.
 * PAPI_CPU_ATTACH	Attach EventSet specified in ptr->cpu.eventset to cpu specified in in
 *					ptr->cpu.cpu_num.
 * PAPI_DETACH		Detach EventSet specified in ptr->attach.eventset from any thread
 *					or process id.
 * PAPI_DOMAIN		Set domain for EventSet specified in ptr->domain.eventset. 
 *					Will error if eventset is not bound to a component.
 * PAPI_GRANUL		Set granularity for EventSet specified in ptr->granularity.eventset. 
 *					Will error if eventset is not bound to a component.
 * PAPI_INHERIT		Enable or disable inheritance for specified EventSet.
 * PAPI_DATA_ADDRESS	Set data address range to restrict event counting for EventSet specified
 *					in ptr->addr.eventset. Starting and ending addresses are specified in
 *					ptr->addr.start and ptr->addr.end, respectively. If exact addresses
 *					cannot be instantiated, offsets are returned in ptr->addr.start_off and
 *					ptr->addr.end_off. Currently implemented on Itanium only.
 * PAPI_INSTR_ADDRESS	Set instruction address range as described above. Itanium only.
 * @endmanonly
 * @htmlonly
 * <table class="doxtable">
 * <tr><th>OPTION</th><th>DEFINITION</th></tr>
 * <tr><td>PAPI_DEFDOM</td><td>Set default counting domain for newly created event sets. Requires a component index.</td></tr>
 * <tr><td>PAPI_DEFGRN</td><td>Set default counting granularity. Requires a component index.</td></tr>
 * <tr><td>PAPI_DEBUG</td><td>Set the PAPI debug state and the debug handler. The debug state is specified in ptr->debug.level. The debug handler is specified in ptr->debug.handler. 
 *			For further information regarding debug states and the behavior of the handler, see PAPI_set_debug.</td></tr>
 * <tr><td>PAPI_MULTIPLEX</td><td>Enable specified EventSet for multiplexing.</td></tr>
 * <tr><td>xPAPI_DEF_ITIMER</td><td>Set the type of itimer used in software multiplexing, overflowing and profiling.</td></tr>
 * <tr><td>PAPI_DEF_MPX_NS</td><td>Set the sampling time slice in nanoseconds for multiplexing and overflow.</td></tr>
 * <tr><td>PAPI_DEF_ITIMER_NS</td><td>See PAPI_DEF_MPX_NS.</td></tr>
 * <tr><td>PAPI_ATTACH</td><td>Attach EventSet specified in ptr->attach.eventset to thread or process id specified in in ptr->attach.tid.</td></tr>
 * <tr><td>PAPI_CPU_ATTACH</td><td>Attach EventSet specified in ptr->cpu.eventset to cpu specified in in ptr->cpu.cpu_num.</td></tr>
 * <tr><td>PAPI_DETACH</td><td>Detach EventSet specified in ptr->attach.eventset from any thread or process id.</td></tr>
 * <tr><td>PAPI_DOMAIN</td><td>Set domain for EventSet specified in ptr->domain.eventset. Will error if eventset is not bound to a component.</td></tr>
 * <tr><td>PAPI_GRANUL</td><td>Set granularity for EventSet specified in ptr->granularity.eventset. Will error if eventset is not bound to a component.</td></tr>
 * <tr><td>PAPI_INHERIT</td><td>Enable or disable inheritance for specified EventSet.</td></tr>
 * <tr><td>PAPI_DATA_ADDRESS</td><td>Set data address range to restrict event counting for EventSet specified in ptr->addr.eventset. Starting and ending addresses are specified in ptr->addr.start and ptr->addr.end, respectively. If exact addresses cannot be instantiated, offsets are returned in ptr->addr.start_off and ptr->addr.end_off. Currently implemented on Itanium only.</td></tr>
 * <tr><td>PAPI_INSTR_ADDRESS</td><td>Set instruction address range as described above. Itanium only.</td></tr>
 * </table>
 * @endhtmlonly
 *
 *	@see PAPI_set_debug
 *	@see PAPI_set_multiplex
 *	@see PAPI_set_domain
 *	@see PAPI_option_t
 */
int
PAPI_set_opt( int option, PAPI_option_t * ptr )
{
	APIDBG("Entry:  option: %d, ptr: %p\n", option, ptr);

	_papi_int_option_t internal;
	int retval = PAPI_OK;
	hwd_context_t *context;
	int cidx;

	if ( ( option != PAPI_DEBUG ) && ( init_level == PAPI_NOT_INITED ) )
		papi_return( PAPI_ENOINIT );
	if ( ptr == NULL )
		papi_return( PAPI_EINVAL );

	memset( &internal, 0x0, sizeof ( _papi_int_option_t ) );

	switch ( option ) {
	case PAPI_DETACH:
	{
		internal.attach.ESI = _papi_hwi_lookup_EventSet( ptr->attach.eventset );
		if ( internal.attach.ESI == NULL )
			papi_return( PAPI_ENOEVST );

		cidx = valid_ESI_component( internal.attach.ESI );
		if ( cidx < 0 )
			papi_return( cidx );

		if ( _papi_hwd[cidx]->cmp_info.attach == 0 )
			papi_return( PAPI_ECMP );

		/* if attached to a cpu, return an error */
		if (internal.attach.ESI->state & PAPI_CPU_ATTACHED)
			papi_return( PAPI_ECMP );

		if ( ( internal.attach.ESI->state & PAPI_STOPPED ) == 0 )
			papi_return( PAPI_EISRUN );

		if ( ( internal.attach.ESI->state & PAPI_ATTACHED ) == 0 )
			papi_return( PAPI_EINVAL );

		internal.attach.tid = internal.attach.ESI->attach.tid;
		/* get the context we should use for this event set */
		context = _papi_hwi_get_context( internal.attach.ESI, NULL );
		retval = _papi_hwd[cidx]->ctl( context, PAPI_DETACH, &internal );
		if ( retval != PAPI_OK )
			papi_return( retval );

		internal.attach.ESI->state ^= PAPI_ATTACHED;
		internal.attach.ESI->attach.tid = 0;
		return ( PAPI_OK );
	}
	case PAPI_ATTACH:
	{
		internal.attach.ESI = _papi_hwi_lookup_EventSet( ptr->attach.eventset );
		if ( internal.attach.ESI == NULL )
			papi_return( PAPI_ENOEVST );

		cidx = valid_ESI_component( internal.attach.ESI );
		if ( cidx < 0 )
			papi_return( cidx );

		if ( _papi_hwd[cidx]->cmp_info.attach == 0 )
			papi_return( PAPI_ECMP );

		if ( ( internal.attach.ESI->state & PAPI_STOPPED ) == 0 )
			papi_return( PAPI_EISRUN );

		if ( internal.attach.ESI->state & PAPI_ATTACHED )
			papi_return( PAPI_EINVAL );

		/* if attached to a cpu, return an error */
		if (internal.attach.ESI->state & PAPI_CPU_ATTACHED)
			papi_return( PAPI_ECMP );

		internal.attach.tid = ptr->attach.tid;
		/* get the context we should use for this event set */
		context = _papi_hwi_get_context( internal.attach.ESI, NULL );
		retval = _papi_hwd[cidx]->ctl( context, PAPI_ATTACH, &internal );
		if ( retval != PAPI_OK )
			papi_return( retval );

		internal.attach.ESI->state |= PAPI_ATTACHED;
		internal.attach.ESI->attach.tid = ptr->attach.tid;

		papi_return (_papi_hwi_lookup_or_create_thread( 
				      &(internal.attach.ESI->master), ptr->attach.tid ));
	}
	case PAPI_CPU_ATTACH:
	{
		APIDBG("eventset: %d, cpu_num: %d\n", ptr->cpu.eventset, ptr->cpu.cpu_num);
		internal.cpu.ESI = _papi_hwi_lookup_EventSet( ptr->cpu.eventset );
		if ( internal.cpu.ESI == NULL )
			papi_return( PAPI_ENOEVST );

		internal.cpu.cpu_num = ptr->cpu.cpu_num;
		APIDBG("internal: %p, ESI: %p, cpu_num: %d\n", &internal, internal.cpu.ESI, internal.cpu.cpu_num);

		cidx = valid_ESI_component( internal.cpu.ESI );
		if ( cidx < 0 )
			papi_return( cidx );

		if ( _papi_hwd[cidx]->cmp_info.cpu == 0 )
			papi_return( PAPI_ECMP );

		// can not attach to a cpu if already attached to a process or 
		// counters set to be inherited by child processes
		if ( internal.cpu.ESI->state & (PAPI_ATTACHED | PAPI_INHERIT) )
			papi_return( PAPI_EINVAL );

		if ( ( internal.cpu.ESI->state & PAPI_STOPPED ) == 0 )
			papi_return( PAPI_EISRUN );

		retval = _papi_hwi_lookup_or_create_cpu(&internal.cpu.ESI->CpuInfo, internal.cpu.cpu_num);
		if( retval != PAPI_OK) {
			papi_return( retval );
		}

		/* get the context we should use for this event set */
		context = _papi_hwi_get_context( internal.cpu.ESI, NULL );
		retval = _papi_hwd[cidx]->ctl( context, PAPI_CPU_ATTACH, &internal );
		if ( retval != PAPI_OK )
			papi_return( retval );

		/* set to show this event set is attached to a cpu not a thread */
		internal.cpu.ESI->state |= PAPI_CPU_ATTACHED;
		return ( PAPI_OK );
	}
	case PAPI_DEF_MPX_NS:
	{
		cidx = 0;			 /* xxxx for now, assume we only check against cpu component */
		if ( ptr->multiplex.ns < 0 )
			papi_return( PAPI_EINVAL );
		/* We should check the resolution here with the system, either
		   component if kernel multiplexing or PAPI if SW multiplexing. */
		internal.multiplex.ns = ( unsigned long ) ptr->multiplex.ns;
		/* get the context we should use for this event set */
		context = _papi_hwi_get_context( internal.cpu.ESI, NULL );
		/* Low level just checks/adjusts the args for this component */
		retval = _papi_hwd[cidx]->ctl( context, PAPI_DEF_MPX_NS, &internal );
		if ( retval == PAPI_OK ) {
			_papi_os_info.itimer_ns = ( int ) internal.multiplex.ns;
			ptr->multiplex.ns = ( int ) internal.multiplex.ns;
		}
		papi_return( retval );
	}
	case PAPI_DEF_ITIMER_NS:
	{
		cidx = 0;			 /* xxxx for now, assume we only check against cpu component */
		if ( ptr->itimer.ns < 0 )
			papi_return( PAPI_EINVAL );
		internal.itimer.ns = ptr->itimer.ns;
		/* Low level just checks/adjusts the args for this component */
		retval = _papi_hwd[cidx]->ctl( NULL, PAPI_DEF_ITIMER_NS, &internal );
		if ( retval == PAPI_OK ) {
			_papi_os_info.itimer_ns = internal.itimer.ns;
			ptr->itimer.ns = internal.itimer.ns;
		}
		papi_return( retval );
	}
	case PAPI_DEF_ITIMER:
	{
		cidx = 0;			 /* xxxx for now, assume we only check against cpu component */
		if ( ptr->itimer.ns < 0 )
			papi_return( PAPI_EINVAL );
		memcpy( &internal.itimer, &ptr->itimer,
				sizeof ( PAPI_itimer_option_t ) );
		/* Low level just checks/adjusts the args for this component */
		retval = _papi_hwd[cidx]->ctl( NULL, PAPI_DEF_ITIMER, &internal );
		if ( retval == PAPI_OK ) {
			_papi_os_info.itimer_num = ptr->itimer.itimer_num;
			_papi_os_info.itimer_sig = ptr->itimer.itimer_sig;
			if ( ptr->itimer.ns > 0 )
				_papi_os_info.itimer_ns = ptr->itimer.ns;
			/* flags are currently ignored, eventually the flags will be able
			   to specify whether or not we use POSIX itimers (clock_gettimer) */
		}
		papi_return( retval );
	}
	case PAPI_MULTIPLEX:
	{
		EventSetInfo_t *ESI;
		ESI = _papi_hwi_lookup_EventSet( ptr->multiplex.eventset );
	   
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );

		cidx = valid_ESI_component( ESI );
		if ( cidx < 0 )
			papi_return( cidx );
	   
		if ( !( ESI->state & PAPI_STOPPED ) )
			papi_return( PAPI_EISRUN );
		if ( ESI->state & PAPI_MULTIPLEXING )
			papi_return( PAPI_EINVAL );

		if ( ptr->multiplex.ns < 0 )
			papi_return( PAPI_EINVAL );
		internal.multiplex.ESI = ESI;
		internal.multiplex.ns = ( unsigned long ) ptr->multiplex.ns;
		internal.multiplex.flags = ptr->multiplex.flags;
		if ( ( _papi_hwd[cidx]->cmp_info.kernel_multiplex ) &&
			 ( ( ptr->multiplex.flags & PAPI_MULTIPLEX_FORCE_SW ) == 0 ) ) {
			/* get the context we should use for this event set */
			context = _papi_hwi_get_context( ESI, NULL );
			retval = _papi_hwd[cidx]->ctl( context, PAPI_MULTIPLEX, &internal );
		}
		/* Kernel or PAPI may have changed this value so send it back out to the user */
		ptr->multiplex.ns = ( int ) internal.multiplex.ns;
		if ( retval == PAPI_OK )
			papi_return( _papi_hwi_convert_eventset_to_multiplex
						 ( &internal.multiplex ) );
		return ( retval );
	}
	case PAPI_DEBUG:
	{
		int level = ptr->debug.level;
		switch ( level ) {
		case PAPI_QUIET:
		case PAPI_VERB_ESTOP:
		case PAPI_VERB_ECONT:
			_papi_hwi_error_level = level;
			break;
		default:
			papi_return( PAPI_EINVAL );
		}
		_papi_hwi_debug_handler = ptr->debug.handler;
		return ( PAPI_OK );
	}
	case PAPI_DEFDOM:
	{
		int dom = ptr->defdomain.domain;
		if ( ( dom < PAPI_DOM_MIN ) || ( dom > PAPI_DOM_MAX ) )
			papi_return( PAPI_EINVAL );

		/* Change the global structure. The _papi_hwd_init_control_state function 
		   in the components gets information from the global structure instead of
		   per-thread information. */
		cidx = valid_component( ptr->defdomain.def_cidx );
		if ( cidx < 0 )
			papi_return( cidx );

		/* Check what the component supports */

		if ( dom == PAPI_DOM_ALL )
			dom = _papi_hwd[cidx]->cmp_info.available_domains;

		if ( dom & ~_papi_hwd[cidx]->cmp_info.available_domains )
			papi_return( PAPI_ENOSUPP );

		_papi_hwd[cidx]->cmp_info.default_domain = dom;

		return ( PAPI_OK );
	}
	case PAPI_DOMAIN:
	{
		int dom = ptr->domain.domain;
		if ( ( dom < PAPI_DOM_MIN ) || ( dom > PAPI_DOM_MAX ) )
			papi_return( PAPI_EINVAL_DOM );

		internal.domain.ESI = _papi_hwi_lookup_EventSet( ptr->domain.eventset );
		if ( internal.domain.ESI == NULL )
			papi_return( PAPI_ENOEVST );

		cidx = valid_ESI_component( internal.domain.ESI );
		if ( cidx < 0 )
			papi_return( cidx );

		/* Check what the component supports */

		if ( dom == PAPI_DOM_ALL )
			dom = _papi_hwd[cidx]->cmp_info.available_domains;

		if ( dom & ~_papi_hwd[cidx]->cmp_info.available_domains )
			papi_return( PAPI_EINVAL_DOM );

		if ( !( internal.domain.ESI->state & PAPI_STOPPED ) )
			papi_return( PAPI_EISRUN );

		/* Try to change the domain of the eventset in the hardware */
		internal.domain.domain = dom;
		internal.domain.eventset = ptr->domain.eventset;
		/* get the context we should use for this event set */
		context = _papi_hwi_get_context( internal.domain.ESI, NULL );
		retval = _papi_hwd[cidx]->ctl( context, PAPI_DOMAIN, &internal );
		if ( retval < PAPI_OK )
			papi_return( retval );

		/* Change the domain of the eventset in the library */

		internal.domain.ESI->domain.domain = dom;

		return ( retval );
	}
	case PAPI_DEFGRN:
	{
		int grn = ptr->defgranularity.granularity;
		if ( ( grn < PAPI_GRN_MIN ) || ( grn > PAPI_GRN_MAX ) )
			papi_return( PAPI_EINVAL );

		cidx = valid_component( ptr->defgranularity.def_cidx );
		if ( cidx < 0 )
			papi_return( cidx );

		/* Change the component structure. The _papi_hwd_init_control_state function 
		   in the components gets information from the global structure instead of
		   per-thread information. */

		/* Check what the component supports */

		if ( grn & ~_papi_hwd[cidx]->cmp_info.available_granularities )
			papi_return( PAPI_EINVAL );

		/* Make sure there is only 1 set. */
		if ( grn ^ ( 1 << ( ffs( grn ) - 1 ) ) )
			papi_return( PAPI_EINVAL );

		_papi_hwd[cidx]->cmp_info.default_granularity = grn;

		return ( PAPI_OK );
	}
	case PAPI_GRANUL:
	{
		int grn = ptr->granularity.granularity;

		if ( ( grn < PAPI_GRN_MIN ) || ( grn > PAPI_GRN_MAX ) )
			papi_return( PAPI_EINVAL );

		internal.granularity.ESI =
			_papi_hwi_lookup_EventSet( ptr->granularity.eventset );
		if ( internal.granularity.ESI == NULL )
			papi_return( PAPI_ENOEVST );

		cidx = valid_ESI_component( internal.granularity.ESI );
		if ( cidx < 0 )
			papi_return( cidx );

		/* Check what the component supports */

		if ( grn & ~_papi_hwd[cidx]->cmp_info.available_granularities )
			papi_return( PAPI_EINVAL );

		/* Make sure there is only 1 set. */
		if ( grn ^ ( 1 << ( ffs( grn ) - 1 ) ) )
			papi_return( PAPI_EINVAL );

		internal.granularity.granularity = grn;
		internal.granularity.eventset = ptr->granularity.eventset;
		retval = _papi_hwd[cidx]->ctl( NULL, PAPI_GRANUL, &internal );
		if ( retval < PAPI_OK )
			return ( retval );

		internal.granularity.ESI->granularity.granularity = grn;
		return ( retval );
	}
	case PAPI_INHERIT:
	{
		EventSetInfo_t *ESI;
		ESI = _papi_hwi_lookup_EventSet( ptr->inherit.eventset );
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );

		cidx = valid_ESI_component( ESI );
		if ( cidx < 0 )
			papi_return( cidx );

		if ( _papi_hwd[cidx]->cmp_info.inherit == 0 )
			papi_return( PAPI_ECMP );

		if ( ( ESI->state & PAPI_STOPPED ) == 0 )
			papi_return( PAPI_EISRUN );

		/* if attached to a cpu, return an error */
		if (ESI->state & PAPI_CPU_ATTACHED)
			papi_return( PAPI_ECMP );

		internal.inherit.ESI = ESI;
		internal.inherit.inherit = ptr->inherit.inherit;

		/* get the context we should use for this event set */
		context = _papi_hwi_get_context( internal.inherit.ESI, NULL );
		retval = _papi_hwd[cidx]->ctl( context, PAPI_INHERIT, &internal );
		if ( retval < PAPI_OK )
			return ( retval );

		ESI->inherit.inherit = ptr->inherit.inherit;
		return ( retval );
	}
	case PAPI_DATA_ADDRESS:
	case PAPI_INSTR_ADDRESS:
	{

		EventSetInfo_t *ESI;

		ESI = _papi_hwi_lookup_EventSet( ptr->addr.eventset );
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );

		cidx = valid_ESI_component( ESI );
		if ( cidx < 0 )
			papi_return( cidx );

		internal.address_range.ESI = ESI;

		if ( !( internal.address_range.ESI->state & PAPI_STOPPED ) )
			papi_return( PAPI_EISRUN );

		/*set domain to be PAPI_DOM_USER */
		internal.address_range.domain = PAPI_DOM_USER;

		internal.address_range.start = ptr->addr.start;
		internal.address_range.end = ptr->addr.end;
		/* get the context we should use for this event set */
		context = _papi_hwi_get_context( internal.address_range.ESI, NULL );
		retval = _papi_hwd[cidx]->ctl( context, option, &internal );
		ptr->addr.start_off = internal.address_range.start_off;
		ptr->addr.end_off = internal.address_range.end_off;
		papi_return( retval );
	}
	case PAPI_USER_EVENTS_FILE:
	{
		APIDBG("User Events Filename is -%s-\n", ptr->events_file);

		// go load the user defined event definitions from the applications event definition file
		// do not know how to find a pmu name and type for this operation yet
//		retval = papi_load_derived_events(pmu_str, pmu_type, cidx, 0);

//		_papi_user_defined_events_setup(ptr->events_file);
		return( PAPI_OK );
	}
	default:
		papi_return( PAPI_EINVAL );
	}
}

/** @class PAPI_num_hwctrs
 *  @brief Return the number of hardware counters on the cpu.
 *
 * @deprecated
 *	This is included to preserve backwards compatibility.
 *      Use PAPI_num_cmp_hwctrs() instead.
 *
 * @see PAPI_num_cmp_hwctrs
 */
int
PAPI_num_hwctrs( void )
{
	APIDBG( "Entry:\n");
	return ( PAPI_num_cmp_hwctrs( 0 ) );
}

/** @class PAPI_num_cmp_hwctrs
 *  @brief Return the number of hardware counters for the specified component.
 *
 *  PAPI_num_cmp_hwctrs() returns the number of counters present in the 
 *  specified component. 
 *  By convention, component 0 is always the cpu. 
 *
 *  On some components, especially for CPUs, the value returned is
 *  a theoretical maximum for estimation purposes only.  It might not
 *  be possible to easily create an EventSet that contains the full
 *  number of events.  This can be due to a variety of reasons:
 *  1).  Some CPUs (especially Intel and POWER) have the notion
 *       of fixed counters that can only measure one thing, usually
 *       cycles.
 *  2).  Some CPUs have very explicit rules about which event can
 *       run in which counter.  In this case it might not be possible
 *       to add a wanted event even if counters are free.
 *  3).  Some CPUs halve the number of counters available when
 *       running with SMT (multiple CPU threads) enabled.
 *  4).  Some operating systems "steal" a counter to use for things
 *       such as NMI Watchdog timers.
 *  The only sure way to see if events will fit is to attempt
 *  adding events to an EventSet, and doing something sensible
 *  if an error is generated.
 *
 *  PAPI_library_init() must be called in order for this function to return 
 *  anything greater than 0. 
 *
 * @par C Interface:
 * \#include <papi.h> @n
 * int PAPI_num_cmp_hwctrs(int  cidx );
 *
 * @param[in] cidx
 *         -- An integer identifier for a component. 
 *         By convention, component 0 is always the cpu component.
 *
 * @par Example
 * @code
 * // Query the cpu component for the number of counters.
 * printf(\"%d hardware counters found.\\n\", PAPI_num_cmp_hwctrs(0));
 * @endcode
 *
 * @returns 
 *  On success, this function returns a value greater than zero.@n
 *  A zero result usually means the library has not been initialized.
 *
 * @bug This count may include fixed-use counters in addition
 *      to the general purpose counters.
 */
int
PAPI_num_cmp_hwctrs( int cidx )
{
	APIDBG( "Entry: cidx: %d\n", cidx);
	return ( PAPI_get_cmp_opt( PAPI_MAX_HWCTRS, NULL, cidx ) );
}

/** @class PAPI_get_multiplex
 *	@brief Get the multiplexing status of specified event set.
 *
 * @par C Interface:
 *     \#include <papi.h> @n
 *     int PAPI_get_multiplex( int  EventSet );
 *
 * @par Fortran Interface:
 *     \#include fpapi.h @n
 *     PAPIF_get_multiplex( C_INT  EventSet,  C_INT  check )
 *
 *	@param EventSet
 *	an integer handle for a PAPI event set as created by PAPI_create_eventset
 *
 *	@retval PAPI_OK
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid, or the EventSet 
 *		is already multiplexed.
 *	@retval PAPI_ENOEVST 
 *		The EventSet specified does not exist.
 *	@retval PAPI_EISRUN 
 *		The EventSet is currently counting events.
 *	@retval PAPI_ENOMEM 
 *		Insufficient memory to complete the operation. 
 *
 *	PAPI_get_multiplex tests the state of the PAPI_MULTIPLEXING flag in the specified event set,
 *  returning @em TRUE if a PAPI event set is multiplexed, or FALSE if not.          
 *	@par Example:
 *	@code
 *	int EventSet = PAPI_NULL;
 *	int ret;
 *	 
 *	// Create an empty EventSet
 *	ret = PAPI_create_eventset(&EventSet);
 *	if (ret != PAPI_OK) handle_error(ret);
 *	
 *	// Bind it to the CPU component
 *	ret = PAPI_assign_eventset_component(EventSet, 0);
 *	if (ret != PAPI_OK) handle_error(ret);
 *	
 *	// Check  current multiplex status
 *	ret = PAPI_get_multiplex(EventSet);
 *	if (ret == TRUE) printf("This event set is ready for multiplexing\n.")
 *	if (ret == FALSE) printf("This event set is not enabled for multiplexing\n.")
 *	if (ret < 0) handle_error(ret);
 *	
 *	// Turn on multiplexing
 *	ret = PAPI_set_multiplex(EventSet);
 *	if ((ret == PAPI_EINVAL) && (PAPI_get_multiplex(EventSet) == TRUE))
 *	  printf("This event set already has multiplexing enabled\n");
 *	else if (ret != PAPI_OK) handle_error(ret);
 *	@endcode
 *	@see PAPI_multiplex_init 
 *	@see PAPI_set_opt 
 *	@see PAPI_create_eventset
 */
int
PAPI_get_multiplex( int EventSet )
{
	APIDBG( "Entry: EventSet: %d\n", EventSet);
	PAPI_option_t popt;
	int retval;

	popt.multiplex.eventset = EventSet;
	retval = PAPI_get_opt( PAPI_MULTIPLEX, &popt );
	if ( retval < 0 )
		retval = 0;
	return retval;
}

/** @class PAPI_get_opt
 *	@brief Get PAPI library or event set options.
 *
 * @par C Interface:
 *     \#include <papi.h> @n
 *     int PAPI_get_opt(  int option, PAPI_option_t * ptr );
 *
 *	@param[in]	option
 *		Defines the option to get. 
 *		Possible values are briefly described in the table below. 
 *
 *	@param[in,out] ptr
 *		Pointer to a structure determined by the selected option. See PAPI_option_t
 *		for a description of possible structures.
 *
 *	@retval PAPI_OK
 *	@retval PAPI_EINVAL The specified option or parameter is invalid.
 *	@retval PAPI_ENOEVST The EventSet specified does not exist.
 *	@retval PAPI_ECMP 
 *              The option is not implemented for the current component.
 *	@retval PAPI_ENOINIT PAPI has not been initialized.
 *
 *	PAPI_get_opt() queries the options of the PAPI library or a specific event set created by 
 *	PAPI_create_eventset. Some options may require that the eventset be bound to a component
 *	before they can execute successfully. This can be done either by adding an event or by
 *	explicitly calling PAPI_assign_eventset_component.
 *
 *	Ptr is a pointer to the PAPI_option_t structure, which is actually a union of different
 *	structures for different options. Not all options require or return information in these
 *	structures. Each returns different values in the structure. Some options require a component 
 *	index to be provided. These options are handled explicitly by the PAPI_get_cmp_opt() call. 
 *
 *	@note Some options, such as PAPI_DOMAIN and PAPI_MULTIPLEX
 *	are also available as separate entry points in both C and Fortran.
 *
 *	The reader is encouraged to peruse the ctests code in the PAPI distribution for examples
 *  of usage of PAPI_set_opt. 
 *
 *	@par Possible values for the PAPI_get_opt option parameter
 * @manonly
 * OPTION 			DEFINITION
 * PAPI_DEFDOM		Get default counting domain for newly created event sets. Requires a component index.
 * PAPI_DEFGRN		Get default counting granularity. Requires a component index.
 * PAPI_DEBUG		Get the PAPI debug state and the debug handler. The debug state is specified in ptr->debug.level. The debug handler is specified in ptr->debug.handler. 
 *					For further information regarding debug states and the behavior of the handler, see PAPI_set_debug.
 * PAPI_MULTIPLEX	Get current multiplexing state for specified EventSet.
 * PAPI_DEF_ITIMER	Get the type of itimer used in software multiplexing, overflowing and profiling.
 * PAPI_DEF_MPX_NS	Get the sampling time slice in nanoseconds for multiplexing and overflow.
 * PAPI_DEF_ITIMER_NS	See PAPI_DEF_MPX_NS.
 * PAPI_ATTACH		Get thread or process id to which event set is attached. Returns TRUE if currently attached.
 * PAPI_CPU_ATTACH	Get ptr->cpu.cpu_num and Attach state for EventSet specified in ptr->cpu.eventset.
 * PAPI_DETACH		Get thread or process id to which event set is attached. Returns TRUE if currently attached.
 * PAPI_DOMAIN		Get domain for EventSet specified in ptr->domain.eventset. Will error if eventset is not bound to a component.
 * PAPI_GRANUL		Get granularity for EventSet specified in ptr->granularity.eventset. Will error if eventset is not bound to a component.
 * PAPI_INHERIT		Get current inheritance state for specified EventSet.
 * PAPI_PRELOAD		Get LD_PRELOAD environment equivalent.
 * PAPI_CLOCKRATE	Get clockrate in MHz.
 * PAPI_MAX_CPUS	Get number of CPUs.
 * PAPI_EXEINFO		Get Executable addresses for text/data/bss.
 * PAPI_HWINFO		Get information about the hardware.
 * PAPI_LIB_VERSION	Get the full PAPI version of the library.
 * PAPI_MAX_HWCTRS	Get number of counters. Requires a component index.
 * PAPI_MAX_MPX_CTRS	Get maximum number of multiplexing counters. Requires a component index.
 * PAPI_SHLIBINFO	Get shared library information used by the program.
 * PAPI_COMPONENTINFO	Get the PAPI features the specified component supports. Requires a component index.
 * @endmanonly
 * @htmlonly
 * <table class="doxtable">
 * <tr><th>OPTION</th><th>DEFINITION</th></tr>
 * <tr><td>PAPI_DEFDOM</td><td>Get default counting domain for newly created event sets. Requires a component index.</td></tr>
 * <tr><td>PAPI_DEFGRN</td><td>Get default counting granularity. Requires a component index.</td></tr>
 * <tr><td>PAPI_DEBUG</td><td>Get the PAPI debug state and the debug handler. The debug state is specified in ptr->debug.level. The debug handler is specified in ptr->debug.handler. 
 *			For further information regarding debug states and the behavior of the handler, see PAPI_set_debug.</td></tr>
 * <tr><td>PAPI_MULTIPLEX</td><td>Get current multiplexing state for specified EventSet.</td></tr>
 * <tr><td>PAPI_DEF_ITIMER</td><td>Get the type of itimer used in software multiplexing, overflowing and profiling.</td></tr>
 * <tr><td>PAPI_DEF_MPX_NS</td><td>Get the sampling time slice in nanoseconds for multiplexing and overflow.</td></tr>
 * <tr><td>PAPI_DEF_ITIMER_NS</td><td>See PAPI_DEF_MPX_NS.</td></tr>
 * <tr><td>PAPI_ATTACH</td><td>Get thread or process id to which event set is attached. Returns TRUE if currently attached.</td></tr>
 * <tr><td>PAPI_CPU_ATTACH</td><td>Get ptr->cpu.cpu_num and Attach state for EventSet specified in ptr->cpu.eventset.</td></tr>
 * <tr><td>PAPI_DETACH</td><td>Get thread or process id to which event set is attached. Returns TRUE if currently attached.</td></tr>
 * <tr><td>PAPI_DOMAIN</td><td>Get domain for EventSet specified in ptr->domain.eventset. Will error if eventset is not bound to a component.</td></tr>
 * <tr><td>PAPI_GRANUL</td><td>Get granularity for EventSet specified in ptr->granularity.eventset. Will error if eventset is not bound to a component.</td></tr>
 * <tr><td>PAPI_INHERIT</td><td>Get current inheritance state for specified EventSet.</td></tr>
 * <tr><td>PAPI_PRELOAD</td><td>Get LD_PRELOAD environment equivalent.</td></tr>
 * <tr><td>PAPI_CLOCKRATE</td><td>Get clockrate in MHz.</td></tr>
 * <tr><td>PAPI_MAX_CPUS</td><td>Get number of CPUs.</td></tr>
 * <tr><td>PAPI_EXEINFO</td><td>Get Executable addresses for text/data/bss.</td></tr>
 * <tr><td>PAPI_HWINFO</td><td>Get information about the hardware.</td></tr>
 * <tr><td>PAPI_LIB_VERSION</td><td>Get the full PAPI version of the library.</td></tr>
 * <tr><td>PAPI_MAX_HWCTRS</td><td>Get number of counters. Requires a component index.</td></tr>
 * <tr><td>PAPI_MAX_MPX_CTRS</td><td>Get maximum number of multiplexing counters. Requires a component index.</td></tr>
 * <tr><td>PAPI_SHLIBINFO</td><td>Get shared library information used by the program.</td></tr>
 * <tr><td>PAPI_COMPONENTINFO</td><td>Get the PAPI features the specified component supports. Requires a component index.</td></tr>
 * </table>
 * @endhtmlonly
 *
 *	@see PAPI_get_multiplex
 *	@see PAPI_get_cmp_opt
 *	@see PAPI_set_opt
 *	@see PAPI_option_t
 */
int
PAPI_get_opt( int option, PAPI_option_t * ptr )
{
	APIDBG( "Entry: option: %d, ptr: %p\n", option, ptr);
	EventSetInfo_t *ESI;

	if ( ( option != PAPI_DEBUG ) && ( init_level == PAPI_NOT_INITED ) )
		papi_return( PAPI_ENOINIT );

	switch ( option ) {
	case PAPI_DETACH:
	{
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ESI = _papi_hwi_lookup_EventSet( ptr->attach.eventset );
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );
		ptr->attach.tid = ESI->attach.tid;
		return ( ( ESI->state & PAPI_ATTACHED ) == 0 );
	}
	case PAPI_ATTACH:
	{
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ESI = _papi_hwi_lookup_EventSet( ptr->attach.eventset );
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );
		ptr->attach.tid = ESI->attach.tid;
		return ( ( ESI->state & PAPI_ATTACHED ) != 0 );
	}
	case PAPI_CPU_ATTACH:
	{
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ESI = _papi_hwi_lookup_EventSet( ptr->attach.eventset );
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );
		ptr->cpu.cpu_num = ESI->CpuInfo->cpu_num;
		return ( ( ESI->state & PAPI_CPU_ATTACHED ) != 0 );
	}
	case PAPI_DEF_MPX_NS:
	{
		/* xxxx for now, assume we only check against cpu component */
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ptr->multiplex.ns = _papi_os_info.itimer_ns;
		return ( PAPI_OK );
	}
	case PAPI_DEF_ITIMER_NS:
	{
		/* xxxx for now, assume we only check against cpu component */
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ptr->itimer.ns = _papi_os_info.itimer_ns;
		return ( PAPI_OK );
	}
	case PAPI_DEF_ITIMER:
	{
		/* xxxx for now, assume we only check against cpu component */
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ptr->itimer.itimer_num = _papi_os_info.itimer_num;
		ptr->itimer.itimer_sig = _papi_os_info.itimer_sig;
		ptr->itimer.ns = _papi_os_info.itimer_ns;
		ptr->itimer.flags = 0;
		return ( PAPI_OK );
	}
	case PAPI_MULTIPLEX:
	{
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ESI = _papi_hwi_lookup_EventSet( ptr->multiplex.eventset );
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );
		ptr->multiplex.ns = ESI->multiplex.ns;
		ptr->multiplex.flags = ESI->multiplex.flags;
		return ( ESI->state & PAPI_MULTIPLEXING ) != 0;
	}
	case PAPI_PRELOAD:
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		memcpy( &ptr->preload, &_papi_hwi_system_info.preload_info,
				sizeof ( PAPI_preload_info_t ) );
		break;
	case PAPI_DEBUG:
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ptr->debug.level = _papi_hwi_error_level;
		ptr->debug.handler = _papi_hwi_debug_handler;
		break;
	case PAPI_CLOCKRATE:
		return ( ( int ) _papi_hwi_system_info.hw_info.cpu_max_mhz );
	case PAPI_MAX_CPUS:
		return ( _papi_hwi_system_info.hw_info.ncpu );
		/* For now, MAX_HWCTRS and MAX CTRS are identical.
		   At some future point, they may map onto different values.
		 */
	case PAPI_INHERIT:
	{
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ESI = _papi_hwi_lookup_EventSet( ptr->inherit.eventset );
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );
		ptr->inherit.inherit = ESI->inherit.inherit;
		return ( PAPI_OK );
	}
	case PAPI_GRANUL:
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ESI = _papi_hwi_lookup_EventSet( ptr->granularity.eventset );
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );
		ptr->granularity.granularity = ESI->granularity.granularity;
		break;
	case PAPI_EXEINFO:
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ptr->exe_info = &_papi_hwi_system_info.exe_info;
		break;
	case PAPI_HWINFO:
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ptr->hw_info = &_papi_hwi_system_info.hw_info;
		break;

	case PAPI_DOMAIN:
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ESI = _papi_hwi_lookup_EventSet( ptr->domain.eventset );
		if ( ESI == NULL )
			papi_return( PAPI_ENOEVST );
		ptr->domain.domain = ESI->domain.domain;
		return ( PAPI_OK );
	case PAPI_LIB_VERSION:
		return ( PAPI_VERSION );
/* The following cases all require a component index 
    and are handled by PAPI_get_cmp_opt() with cidx == 0*/
	case PAPI_MAX_HWCTRS:
	case PAPI_MAX_MPX_CTRS:
	case PAPI_DEFDOM:
	case PAPI_DEFGRN:
	case PAPI_SHLIBINFO:
	case PAPI_COMPONENTINFO:
		return ( PAPI_get_cmp_opt( option, ptr, 0 ) );
	default:
		papi_return( PAPI_EINVAL );
	}
	return ( PAPI_OK );
}

/** @class PAPI_get_cmp_opt
 *	@brief Get component specific PAPI options.
 *
 *	@param	option
 *		is an input parameter describing the course of action. 
 *		Possible values are defined in papi.h and briefly described in the table below. 
 *		The Fortran calls are implementations of specific options.
 *	@param ptr
 *		is a pointer to a structure that acts as both an input and output parameter.
 *	@param cidx
 *		An integer identifier for a component. 
 *		By convention, component 0 is always the cpu component. 
 *
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid. 
 *
 *	PAPI_get_opt() and PAPI_set_opt() query or change the options of the PAPI 
 *	library or a specific event set created by PAPI_create_eventset . 
 *	Some options may require that the eventset be bound to a component before 
 *	they can execute successfully. 
 *	This can be done either by adding an event or by explicitly calling 
 *	PAPI_assign_eventset_component . 
 *	
 *	The C interface for these functions passes a pointer to the PAPI_option_t structure. 
 *	Not all options require or return information in this structure, and not all 
 *	options are implemented for both get and set. 
 *	Some options require a component index to be provided. 
 *	These options are handled explicitly by the PAPI_get_cmp_opt() call for 'get' 
 *	and implicitly through the option structure for 'set'. 
 *	The Fortran interface is a series of calls implementing various subsets of 
 *	the C interface. Not all options in C are available in Fortran.
 *
 *	@note Some options, such as PAPI_DOMAIN and PAPI_MULTIPLEX, 
 *	are also available as separate entry points in both C and Fortran.
 *
 *	The reader is urged to see the example code in the PAPI distribution for usage of PAPI_get_opt. 
 *	The file papi.h contains definitions for the structures unioned in the PAPI_option_t structure. 
 *
 *	@see PAPI_set_debug PAPI_set_multiplex PAPI_set_domain PAPI_option_t
 */

int
PAPI_get_cmp_opt( int option, PAPI_option_t * ptr, int cidx )
{
	APIDBG( "Entry: option: %d, ptr: %p, cidx: %d\n", option, ptr, cidx);

  if (_papi_hwi_invalid_cmp(cidx)) {
     return PAPI_ECMP;
  }

	switch ( option ) {
		/* For now, MAX_HWCTRS and MAX CTRS are identical.
		   At some future point, they may map onto different values.
		 */
	case PAPI_MAX_HWCTRS:
		return ( _papi_hwd[cidx]->cmp_info.num_cntrs );
	case PAPI_MAX_MPX_CTRS:
		return ( _papi_hwd[cidx]->cmp_info.num_mpx_cntrs );
	case PAPI_DEFDOM:
		return ( _papi_hwd[cidx]->cmp_info.default_domain );
	case PAPI_DEFGRN:
		return ( _papi_hwd[cidx]->cmp_info.default_granularity );
	case PAPI_SHLIBINFO:
	{
		int retval;
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		retval = _papi_os_vector.update_shlib_info( &_papi_hwi_system_info );
		ptr->shlib_info = &_papi_hwi_system_info.shlib_info;
		papi_return( retval );
	}
	case PAPI_COMPONENTINFO:
		if ( ptr == NULL )
			papi_return( PAPI_EINVAL );
		ptr->cmp_info = &( _papi_hwd[cidx]->cmp_info );
		return PAPI_OK;
	default:
	  papi_return( PAPI_EINVAL );
	}
	return PAPI_OK;
}

/** @class PAPI_num_components
  *	@brief Get the number of components available on the system.
  *
  * @return 
  *		Number of components available on the system
  *
  *	@code
// Query the library for a component count. 
printf("%d components installed., PAPI_num_components() );
  * @endcode
  */
int
PAPI_num_components( void )
{
	APIDBG( "Entry:\n");
	return ( papi_num_components );
}

/** @class PAPI_num_events
  * @brief Return the number of events in an event set.
  * 
  * PAPI_num_events() returns the number of preset and/or native events 
  * contained in an event set. 
  * The event set should be created by @ref PAPI_create_eventset .
  *
  * @par C Interface:
  * \#include <papi.h> @n
  * int PAPI_num_events(int  EventSet );
  *
  * @param[in] EventSet -- 
  *   an integer handle for a PAPI event set created by PAPI_create_eventset.
  * @param[out] *count -- (Fortran only) 
  *   On output the variable contains the number of events in the event set
  *
  * @retval On success, this function returns the positive number of 
  *         events in the event set.
  * @retval PAPI_EINVAL The event count is zero; 
  *                     only if code is compiled with debug enabled.
  * @retval PAPI_ENOEVST The EventSet specified does not exist. 
  *
  * @par Example
  * @code
  * // Count the events in our EventSet 
  * printf(\"%d events found in EventSet.\\n\", PAPI_num_events(EventSet));
  * @endcode
  *
  * @see PAPI_add_event 
  * @see PAPI_create_eventset
  *
  */
int
PAPI_num_events( int EventSet )
{
	APIDBG( "Entry: EventSet: %d\n", EventSet);
	EventSetInfo_t *ESI;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( !ESI )
		papi_return( PAPI_ENOEVST );

#ifdef DEBUG
	/* Not necessary */
	if ( ESI->NumberOfEvents == 0 )
		papi_return( PAPI_EINVAL );
#endif

	return ( ESI->NumberOfEvents );
}


/** @class PAPI_shutdown
  *	@brief Finish using PAPI and free all related resources. 
  *
  *	@par C Prototype:
  *		\#include <papi.h> @n
  *		void PAPI_shutdown( void );
  *
  * PAPI_shutdown() is an exit function used by the PAPI Library 
  * to free resources and shut down when certain error conditions arise. 
  * It is not necessary for the user to call this function, 
  * but doing so allows the user to have the capability to free memory 
  * and resources used by the PAPI Library.
  *
  *	@see PAPI_init_library
  */
void
PAPI_shutdown( void )
{
	APIDBG( "Entry:\n");

        EventSetInfo_t *ESI;
        ThreadInfo_t *master;
        DynamicArray_t *map = &_papi_hwi_system_info.global_eventset_map;
        int i, j = 0, k, retval;


	if ( init_retval == DEADBEEF ) {
		PAPIERROR( PAPI_SHUTDOWN_str );
		return;
	}

	MPX_shutdown(  );

	/* Free all EventSets for this thread */

   master = _papi_hwi_lookup_thread( 0 );

      /* Count number of running EventSets AND */
      /* Stop any running EventSets in this thread */

#ifdef DEBUG
again:
#endif
   for( i = 0; i < map->totalSlots; i++ ) {
      ESI = map->dataSlotArray[i];
      if ( ESI ) {
	 if ( ESI->master == master ) {
	    if ( ESI->state & PAPI_RUNNING ) {
	       if((retval = PAPI_stop( i, NULL )) != PAPI_OK) {
	    	   APIDBG("Call to PAPI_stop failed: %d\n", retval);
	       }
	    }
	    retval=PAPI_cleanup_eventset( i );
	    if (retval!=PAPI_OK) PAPIERROR("Error during cleanup.");
	    _papi_hwi_free_EventSet( ESI );
	 } 
         else {
            if ( ESI->state & PAPI_RUNNING ) {
	       j++;
	    }
	 }
      }
   }

	/* No locking required, we're just waiting for the others
	   to call shutdown or stop their eventsets. */

#ifdef DEBUG
	if ( j != 0 ) {
		PAPIERROR( PAPI_SHUTDOWN_SYNC_str );
		sleep( 1 );
		j = 0;
		goto again;
	}
#endif

	// if we have some user events defined, release the space they allocated
	// give back the strings which were allocated when each event was created
	for ( i=0 ; i<user_defined_events_count ; i++) {
		papi_free (user_defined_events[i].symbol);
		papi_free (user_defined_events[i].postfix);
		papi_free (user_defined_events[i].long_descr);
		papi_free (user_defined_events[i].short_descr);
		papi_free (user_defined_events[i].note);
		for ( k=0 ; k<(int)(user_defined_events[i].count) ; k++) {
			papi_free (user_defined_events[i].name[k]);
		}
	}
	// make sure the user events list is empty
	memset (user_defined_events, '\0' , sizeof(user_defined_events));
	user_defined_events_count = 0;

	/* Shutdown the entire component */
	_papi_hwi_shutdown_highlevel(  );
	_papi_hwi_shutdown_global_internal(  );
	_papi_hwi_shutdown_global_threads(  );
	for( i = 0; i < papi_num_components; i++ ) {
	   if (!_papi_hwd[i]->cmp_info.disabled) {
              _papi_hwd[i]->shutdown_component(  );
	   }
	}

	/* Now it is safe to call re-init */

	init_retval = DEADBEEF;
	init_level = PAPI_NOT_INITED;
	_papi_mem_cleanup_all(  );
}

/** @class PAPI_strerror
 *	@brief Returns a string describing the PAPI error code. 
 *
 *  @par C Interface:
 *     \#include <papi.h> @n
 *     char * PAPI_strerror( int errorCode );
 *
 *  @param[in] code  
 *      -- the error code to interpret 
 *
 *	@retval *error 
 *		-- a pointer to the error string. 
 *	@retval NULL 
 *		-- the input error code to PAPI_strerror() is invalid. 
 *
 *	PAPI_strerror() returns a pointer to the error message corresponding to the 
 *	error code code. 
 *	If the call fails the function returns the NULL pointer. 
 *	This function is not implemented in Fortran.
 *
 *  @par Example:
 *  @code
 *  int ret;
 *  int EventSet = PAPI_NULL;
 *  int native = 0x0;
 *  char error_str[PAPI_MAX_STR_LEN];
 *
 *  ret = PAPI_create_eventset(&EventSet);
 *  if (ret != PAPI_OK)
 *  {
 *     fprintf(stderr, "PAPI error %d: %s\n", ret, PAPI_strerror(retval));
 *     exit(1);
 *  }
 *  // Add Total Instructions Executed to our EventSet
 *  ret = PAPI_add_event(EventSet, PAPI_TOT_INS);
 *  if (ret != PAPI_OK)
 *  {
 *     PAPI_perror( "PAPI_add_event");
 *     fprintf(stderr,"PAPI_error %d: %s\n", ret, error_str);
 *     exit(1);
 *  }
 *  // Start counting
 *  ret = PAPI_start(EventSet);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  @endcode
 *
 *	@see  PAPI_perror PAPI_set_opt PAPI_get_opt PAPI_shutdown PAPI_set_debug
 */
char *
PAPI_strerror( int errorCode )
{
	if ( ( errorCode > 0 ) || ( -errorCode > _papi_hwi_num_errors ) )
		return ( NULL );

	return ( _papi_errlist[-errorCode] );
}

/** @class PAPI_perror
 *  @brief Produces a string on standard error, describing the last library error.
 *
 * @par C Interface:
 *     \#include <papi.h> @n
 *     void PAPI_perror( const char *s );
 *
 *  @param[in] s
 *      -- Optional message to print before the string describing the last error message. 
 * 
 * 	The routine PAPI_perror() produces a message on the standard error output,
 * 	describing the last error encountered during a call to PAPI. 
 * 	If s is not NULL, s is printed, followed by a colon and a space. 
 * 	Then the error message and a new-line are printed. 
 *
 *  @par Example:
 *  @code
 *  int ret;
 *  int EventSet = PAPI_NULL;
 *  int native = 0x0;
 *
 *  ret = PAPI_create_eventset(&EventSet);
 *  if (ret != PAPI_OK)
 *  {
 *     fprintf(stderr, \"PAPI error %d: %s\\n\", ret, PAPI_strerror(retval));
 *     exit(1);
 *  }
 *  // Add Total Instructions Executed to our EventSet
 *  ret = PAPI_add_event(EventSet, PAPI_TOT_INS);
 *  if (ret != PAPI_OK)
 *  {
 *     PAPI_perror( "PAPI_add_event" );
 *     exit(1);
 *  }
 *  // Start counting
 *  ret = PAPI_start(EventSet);
 *  if (ret != PAPI_OK) handle_error(ret);
 *  @endcode
 *
 *  @see PAPI_strerror
 */
void
PAPI_perror( const char *msg )
{
	char *foo;

	foo = PAPI_strerror( _papi_hwi_errno );
	if ( foo == NULL )
		return;

	if ( msg )
		if ( *msg )
			fprintf( stderr, "%s: ", msg );

	fprintf( stderr, "%s\n", foo );
}

/** @class PAPI_overflow
 *  @brief Set up an event set to begin registering overflows.
 *
 * PAPI_overflow() marks a specific EventCode in an EventSet to generate an 
 * overflow signal after every threshold events are counted. 
 * More than one event in an event set can be used to trigger overflows. 
 * In such cases, the user must call this function once for each overflowing 
 * event. 
 * To turn off overflow on a specified event, call this function with a 
 * threshold value of 0.
 *
 * Overflows can be implemented in either software or hardware, but the scope 
 * is the entire event set. 
 * PAPI defaults to hardware overflow if it is available. 
 * In the case of software overflow, a periodic timer interrupt causes PAPI 
 * to compare the event counts against the threshold values and call the 
 * overflow handler if one or more events have exceeded their threshold. 
 * In the case of hardware overflow, the counters are typically set to the 
 * negative of the threshold value and count up to 0. 
 * This zero-crossing triggers a hardware interrupt that calls the overflow 
 * handler. 
 * Because of this counter interrupt, the counter values for overflowing 
 * counters 
 * may be very small or even negative numbers, and cannot be relied upon 
 * as accurate. 
 * In such cases the overflow handler can approximate the counts by supplying 
 * the threshold value whenever an overflow occurs. 
 *
 * _papi_overflow_handler()  is  a placeholder for a user-defined function
 * to process overflow events.  A pointer to this function  is  passed  to
 * the  PAPI_overflow  routine, where it is invoked whenever a software or
 * hardware overflow occurs.  This handler receives the  EventSet  of  the
 * overflowing  event,  the  Program  Counter  address  when the interrupt
 * occurred, an overflow_vector that can be processed to  determined  which
 * event(s)  caused  the  overflow,  and a pointer to the machine context,
 * which can be used in a  platform-specific  manor  to  extract  register
 * information about what was happening when the overflow occurred.
 *
 * @par C Interface:
 * \#include <papi.h> @n
 * int PAPI_overflow (int EventSet, int EventCode, int threshold, 
 * int flags, PAPI_overflow_handler_t handler ); @n@n
 * (*PAPI_overflow_handler_t) _papi_overflow_handler
 * (int  EventSet, void *address, long_long overflow_vector, 
 * void *context );
 *
 * @par Fortran Interface:
 * Not implemented
 *
 * @param[in] EventSet
 *	      -- an integer handle to a PAPI event set as created by 
 *            @ref PAPI_create_eventset
 * @param[in] EventCode
 *	      -- the preset or native event code to be set for overflow 
 *            detection. 
 *	      This event must have already been added to the EventSet.
 * @param[in] threshold
 *	      -- the overflow threshold value for this EventCode.
 * @param[in] flags
 *	      -- bitmap that controls the overflow mode of operation. 
 *	      Set to PAPI_OVERFLOW_FORCE_SW to force software 
 *            overflowing, even if hardware overflow support is available. 
 *	      If hardware overflow support is available on a given system, 
 *            it will be the default mode of operation. 
 *	      There are situations where it is advantageous to use software 
 *            overflow instead. 
 *	      Although software overflow is inherently less accurate, 
 *            with more latency and processing overhead, it does allow for 
 *            overflowing on derived events,  and for the accurate recording 
 *            of overflowing event counts. 
 *	      These two features are typically not available with hardware 
 *            overflow. 
 *	      Only one type of overflow is allowed per event set, so 
 *            setting one event to hardware overflow and another to forced 
 *            software overflow will result in an error being returned.
 *	@param[in] handler
 *	      -- pointer to the user supplied handler function to call upon 
 *            overflow 
 *      @param[in] address 
 *            -- the Program Counter address at the time of the overflow
 *      @param[in] overflow_vector  
 *            -- a long long word containing flag bits to indicate
 *               which hardware counter(s) caused the overflow
 *      @param[in] *context 
 *            -- pointer to a machine specific structure that defines the
 *               register context at the time of overflow. This parameter 
 *               is often unused and can be ignored in the user function.
 *
 * @retval PAPI_OK On success, PAPI_overflow returns PAPI_OK.  
 * @retval PAPI_EINVAL One or more of the arguments is invalid.   
 *            Most likely a bad threshold value.
 * @retval PAPI_ENOMEM Insufficient memory to complete the operation.
 * @retval PAPI_ENOEVST The EventSet specified does not exist.
 * @retval PAPI_EISRUN The EventSet is currently counting events.
 * @retval PAPI_ECNFLCT The underlying counter hardware cannot count 
 *             this event and other events in the EventSet simultaneously. 
 *             Also can happen if you are trying to overflow both by hardware
 *             and by forced software at the same time.
 * @retval PAPI_ENOEVNT The PAPI event is not available on 
 *             the underlying hardware.
 *
 * @par Example
 * @code
 * // Define a simple overflow handler:
 * void handler(int EventSet, void *address, long_long overflow_vector, void *context)
 * {
 *    fprintf(stderr,\"Overflow at %p! bit=%#llx \\n\",
 *             address,overflow_vector);
 * }
 *
 * // Call PAPI_overflow for an EventSet containing PAPI_TOT_INS,
 * // setting the threshold to 100000. Use the handler defined above.
 * retval = PAPI_overflow(EventSet, PAPI_TOT_INS, 100000, 0, handler);
 * @endcode
 *
 *
 * @see PAPI_get_overflow_event_index
 *
 */
int
PAPI_overflow( int EventSet, int EventCode, int threshold, int flags,
	       PAPI_overflow_handler_t handler )
{
	APIDBG( "Entry: EventSet: %d, EventCode: %#x, threshold: %d, flags: %#x, handler: %p\n", EventSet, EventCode, threshold, flags, handler);
	int retval, cidx, index, i;
	EventSetInfo_t *ESI;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL ) {
		OVFDBG("No EventSet\n");
		papi_return( PAPI_ENOEVST );
        }

	cidx = valid_ESI_component( ESI );
	if ( cidx < 0 ) {
		OVFDBG("Component Error\n");
		papi_return( cidx );
	}

	if ( ( ESI->state & PAPI_STOPPED ) != PAPI_STOPPED ) {
		OVFDBG("Already running\n");
		papi_return( PAPI_EISRUN );
	}

	if ( ESI->state & PAPI_ATTACHED ) {
		OVFDBG("Attached\n");
		papi_return( PAPI_EINVAL );
	}
	
	if ( ESI->state & PAPI_CPU_ATTACHED ) {
		OVFDBG("CPU attached\n");
		papi_return( PAPI_EINVAL );
	}
	
	if ( ( index = _papi_hwi_lookup_EventCodeIndex( ESI,
      					( unsigned int ) EventCode ) ) < 0 ) {
		papi_return( PAPI_ENOEVNT );
	}

	if ( threshold < 0 ) {
		OVFDBG("Threshold below zero\n");
		papi_return( PAPI_EINVAL );
	}

	/* We do not support derived events in overflow */
	/* Unless it's DERIVED_CMPD in which no calculations are done */

	if ( !( flags & PAPI_OVERFLOW_FORCE_SW ) && threshold != 0 &&
		 ( ESI->EventInfoArray[index].derived ) &&
		 ( ESI->EventInfoArray[index].derived != DERIVED_CMPD ) ) {
		OVFDBG("Derived event in overflow\n");
		papi_return( PAPI_EINVAL );
	}

	/* the first time to call PAPI_overflow function */

	if ( !( ESI->state & PAPI_OVERFLOWING ) ) {
		if ( handler == NULL ) {
			OVFDBG("NULL handler\n");
			papi_return( PAPI_EINVAL );
		}
		if ( threshold == 0 ) {
			OVFDBG("Zero threshold\n");
			papi_return( PAPI_EINVAL );
		}
	}
	if ( threshold > 0 &&
		 ESI->overflow.event_counter >= _papi_hwd[cidx]->cmp_info.num_cntrs )
		papi_return( PAPI_ECNFLCT );

	if ( threshold == 0 ) {
		for ( i = 0; i < ESI->overflow.event_counter; i++ ) {
			if ( ESI->overflow.EventCode[i] == EventCode )
				break;
		}
		/* EventCode not found */
		if ( i == ESI->overflow.event_counter )
			papi_return( PAPI_EINVAL );
		/* compact these arrays */
		while ( i < ESI->overflow.event_counter - 1 ) {
			ESI->overflow.deadline[i] = ESI->overflow.deadline[i + 1];
			ESI->overflow.threshold[i] = ESI->overflow.threshold[i + 1];
			ESI->overflow.EventIndex[i] = ESI->overflow.EventIndex[i + 1];
			ESI->overflow.EventCode[i] = ESI->overflow.EventCode[i + 1];
			i++;
		}
		ESI->overflow.deadline[i] = 0;
		ESI->overflow.threshold[i] = 0;
		ESI->overflow.EventIndex[i] = 0;
		ESI->overflow.EventCode[i] = 0;
		ESI->overflow.event_counter--;
	} else {
		if ( ESI->overflow.event_counter > 0 ) {
			if ( ( flags & PAPI_OVERFLOW_FORCE_SW ) &&
				 ( ESI->overflow.flags & PAPI_OVERFLOW_HARDWARE ) )
				papi_return( PAPI_ECNFLCT );
			if ( !( flags & PAPI_OVERFLOW_FORCE_SW ) &&
				 ( ESI->overflow.flags & PAPI_OVERFLOW_FORCE_SW ) )
				papi_return( PAPI_ECNFLCT );
		}
		for ( i = 0; i < ESI->overflow.event_counter; i++ ) {
			if ( ESI->overflow.EventCode[i] == EventCode )
				break;
		}
		/* A new entry */
		if ( i == ESI->overflow.event_counter ) {
			ESI->overflow.EventCode[i] = EventCode;
			ESI->overflow.event_counter++;
		}
		/* New or existing entry */
		ESI->overflow.deadline[i] = threshold;
		ESI->overflow.threshold[i] = threshold;
		ESI->overflow.EventIndex[i] = index;
		ESI->overflow.flags = flags;

	}

	/* If overflowing is already active, we should check to
	   make sure that we don't specify a different handler
	   or different flags here. You can't mix them. */

	ESI->overflow.handler = handler;

	/* Set up the option structure for the low level.
	   If we have hardware interrupts and we are not using
	   forced software emulated interrupts */

	if ( _papi_hwd[cidx]->cmp_info.hardware_intr &&
		 !( ESI->overflow.flags & PAPI_OVERFLOW_FORCE_SW ) ) {
		retval = _papi_hwd[cidx]->set_overflow( ESI, index, threshold );
		if ( retval == PAPI_OK )
			ESI->overflow.flags |= PAPI_OVERFLOW_HARDWARE;
		else {
			papi_return( retval );	/* We should undo stuff here */
		}
	} else {
		/* Make sure hardware overflow is not set */
		ESI->overflow.flags &= ~( PAPI_OVERFLOW_HARDWARE );
	}

	APIDBG( "Overflow using: %s\n",
			( ESI->overflow.
			  flags & PAPI_OVERFLOW_HARDWARE ? "[Hardware]" : ESI->overflow.
			  flags & PAPI_OVERFLOW_FORCE_SW ? "[Forced Software]" :
			  "[Software]" ) );

	/* Toggle the overflow flags and ESI state */

	if ( ESI->overflow.event_counter >= 1 )
		ESI->state |= PAPI_OVERFLOWING;
	else {
		ESI->state ^= PAPI_OVERFLOWING;
		ESI->overflow.flags = 0;
		ESI->overflow.handler = NULL;
	}

	return PAPI_OK;
}

/** @class PAPI_sprofil
 *	@brief Generate PC histogram data from multiple code regions where hardware counter overflow occurs.
 *
 * @par C Interface:
 * \#include <papi.h> @n
 * int PAPI_sprofil( PAPI_sprofil_t * prof, int profcnt, int EventSet, int EventCode, int threshold, int flags );
 *
 *	@param *prof 
 *		pointer to an array of PAPI_sprofil_t structures. Each copy of the structure contains the following:
 *  @arg buf -- pointer to a buffer of bufsiz bytes in which the histogram counts are stored in an array of unsigned short, unsigned int, or unsigned long long values, or 'buckets'. The size of the buckets is determined by values in the flags argument.
 *  @arg bufsiz -- the size of the histogram buffer in bytes. It is computed from the length of the code region to be profiled, the size of the buckets, and the scale factor as discussed below.
 *  @arg offset -- the start address of the region to be profiled.
 *  @arg scale -- broadly and historically speaking, a contraction factor that indicates how much smaller the histogram buffer is than the region to be profiled. More precisely, scale is interpreted as an unsigned 16-bit fixed-point fraction with the decimal point implied on the left. Its value is the reciprocal of the number of addresses in a subdivision, per counter of histogram buffer.
 *
 *	@param profcnt 
 *		number of structures in the prof array for hardware profiling.
 *	@param EventSet 
 *		The PAPI EventSet to profile. This EventSet is marked as profiling-ready, 
 *		but profiling doesn't actually start until a PAPI_start() call is issued.
 *	@param EventCode
 *		Code of the Event in the EventSet to profile. 
 *		This event must already be a member of the EventSet.
 *	@param threshold 
 *		minimum number of events that must occur before the PC is sampled. 
 *		If hardware overflow is supported for your component, this threshold will 
 *		trigger an interrupt when reached. 
 *		Otherwise, the counters will be sampled periodically and the PC will be 
 *		recorded for the first sample that exceeds the threshold. 
 *		If the value of threshold is 0, profiling will be disabled for this event.
 *	@param flags 
 *		bit pattern to control profiling behavior. 
 *		Defined values are given in a table in the documentation for PAPI_pofil
 *	@manonly
 *
 *	@endmanonly
 *
 *  @retval
 *		Return values for PAPI_sprofil() are identical to those for PAPI_profil.
 *		Please refer to that page for further details.
 *	@manonly
 *
 *	@endmanonly
 *
 *	PAPI_sprofil() is a structure driven profiler that profiles one or more 
 *	disjoint regions of code in a single call. 
 *	It accepts a pointer to a preinitialized array of sprofil structures, and 
 *	initiates profiling based on the values contained in the array. 
 *	Each structure in the array defines the profiling parameters that are 
 *	normally passed to PAPI_profil(). 
 *	For more information on profiling, @ref PAPI_profil
 *	@manonly
 *
 *	@endmanonly
 *
 * @par Example:
 * @code
 * int retval;
 * unsigned long length;
 * PAPI_exe_info_t *prginfo;
 * unsigned short *profbuf1, *profbuf2, profbucket;
 * PAPI_sprofil_t sprof[3];
 *
 * prginfo = PAPI_get_executable_info();
 * if (prginfo == NULL) handle_error( NULL );
 * length = (unsigned long)(prginfo->text_end - prginfo->text_start);
 * // Allocate 2 buffers of equal length
 * profbuf1 = (unsigned short *)malloc(length);
 * profbuf2 = (unsigned short *)malloc(length);
 * if ((profbuf1 == NULL) || (profbuf2 == NULL))
 *   handle_error( NULL );
 * memset(profbuf1,0x00,length);
 * memset(profbuf2,0x00,length);
 * // First buffer
 * sprof[0].pr_base = profbuf1;
 * sprof[0].pr_size = length;
 * sprof[0].pr_off = (caddr_t) DO_FLOPS;
 * sprof[0].pr_scale = 0x10000;
 * // Second buffer
 * sprof[1].pr_base = profbuf2;
 * sprof[1].pr_size = length;
 * sprof[1].pr_off = (caddr_t) DO_READS;
 * sprof[1].pr_scale = 0x10000;
 * // Overflow bucket
 * sprof[2].pr_base = profbucket;
 * sprof[2].pr_size = 1;
 * sprof[2].pr_off = 0;
 * sprof[2].pr_scale = 0x0002;
 * retval = PAPI_sprofil(sprof, EventSet, PAPI_FP_INS, 1000000,
 * PAPI_PROFIL_POSIX | PAPI_PROFIL_BUCKET_16)) != PAPI_OK)
 * if ( retval != PAPI_OK ) handle_error( retval );
 * @endcode
 *
 *	@see PAPI_overflow
 *	@see PAPI_get_executable_info
 *	@see PAPI_profil
 */
int
PAPI_sprofil( PAPI_sprofil_t *prof, int profcnt, int EventSet,
			  int EventCode, int threshold, int flags )
{
	APIDBG( "Entry: prof: %p, profcnt: %d, EventSet: %d, EventCode: %#x, threshold: %d, flags: %#x\n", prof, profcnt, EventSet, EventCode, threshold, flags);
   EventSetInfo_t *ESI;
   int retval, index, i, buckets;
   int forceSW = 0;
   int cidx;

   /* Check to make sure EventSet exists */
   ESI = _papi_hwi_lookup_EventSet( EventSet );
   if ( ESI == NULL ) {
      papi_return( PAPI_ENOEVST );
   }

   /* Check to make sure EventSet is stopped */
   if ( ( ESI->state & PAPI_STOPPED ) != PAPI_STOPPED ) {
      papi_return( PAPI_EISRUN );
   }

   /* We cannot profile if attached */
   if ( ESI->state & PAPI_ATTACHED ) {
      papi_return( PAPI_EINVAL );
   }

   /* We cannot profile if cpu attached */
   if ( ESI->state & PAPI_CPU_ATTACHED ) {
      papi_return( PAPI_EINVAL );
   }

   /* Get component for EventSet */
   cidx = valid_ESI_component( ESI );
   if ( cidx < 0 ) {
      papi_return( cidx );
   }

   /* Get index of the Event we want to profile */
   if ( ( index = _papi_hwi_lookup_EventCodeIndex( ESI,
				      (unsigned int) EventCode ) ) < 0 ) {
      papi_return( PAPI_ENOEVNT );
   }

   /* We do not support derived events in overflow */
   /* Unless it's DERIVED_CMPD in which no calculations are done */
   if ( ( ESI->EventInfoArray[index].derived ) &&
	( ESI->EventInfoArray[index].derived != DERIVED_CMPD ) &&
	!( flags & PAPI_PROFIL_FORCE_SW ) ) {
      papi_return( PAPI_EINVAL );
   }

   /* If no prof structures, then make sure count is 0 */
   if ( prof == NULL ) {
      profcnt = 0;
   }

   /* check all profile regions for valid scale factors of:
      2 (131072/65536),
      1 (65536/65536),
      or < 1 (65535 -> 2) as defined in unix profil()
      2/65536 is reserved for single bucket profiling
      {0,1}/65536 are traditionally used to terminate profiling
      but are unused here since PAPI uses threshold instead
    */
   for( i = 0; i < profcnt; i++ ) {
      if ( !( ( prof[i].pr_scale == 131072 ) ||
	   ( ( prof[i].pr_scale <= 65536 && prof[i].pr_scale > 1 ) ) ) ) {
	 APIDBG( "Improper scale factor: %d\n", prof[i].pr_scale );
	 papi_return( PAPI_EINVAL );
      }
   }

   /* Make sure threshold is valid */
   if ( threshold < 0 ) {
      papi_return( PAPI_EINVAL );
   }

   /* the first time to call PAPI_sprofil */
   if ( !( ESI->state & PAPI_PROFILING ) ) {
      if ( threshold == 0 ) {
	 papi_return( PAPI_EINVAL );
      }
   }

   /* ??? */
   if ( (threshold > 0) &&
	(ESI->profile.event_counter >= _papi_hwd[cidx]->cmp_info.num_cntrs) ) {
      papi_return( PAPI_ECNFLCT );
   }

   if ( threshold == 0 ) {
      for( i = 0; i < ESI->profile.event_counter; i++ ) {
	 if ( ESI->profile.EventCode[i] == EventCode ) {
	    break;
	 }
      }
		
      /* EventCode not found */
      if ( i == ESI->profile.event_counter ) {
	 papi_return( PAPI_EINVAL );
      }

      /* compact these arrays */
      while ( i < ESI->profile.event_counter - 1 ) {
         ESI->profile.prof[i] = ESI->profile.prof[i + 1];
	 ESI->profile.count[i] = ESI->profile.count[i + 1];
	 ESI->profile.threshold[i] = ESI->profile.threshold[i + 1];
	 ESI->profile.EventIndex[i] = ESI->profile.EventIndex[i + 1];
	 ESI->profile.EventCode[i] = ESI->profile.EventCode[i + 1];
	 i++;
      }
      ESI->profile.prof[i] = NULL;
      ESI->profile.count[i] = 0;
      ESI->profile.threshold[i] = 0;
      ESI->profile.EventIndex[i] = 0;
      ESI->profile.EventCode[i] = 0;
      ESI->profile.event_counter--;
   } else {
      if ( ESI->profile.event_counter > 0 ) {
	 if ( ( flags & PAPI_PROFIL_FORCE_SW ) &&
	      !( ESI->profile.flags & PAPI_PROFIL_FORCE_SW ) ) {
	    papi_return( PAPI_ECNFLCT );
	 }
	 if ( !( flags & PAPI_PROFIL_FORCE_SW ) &&
	      ( ESI->profile.flags & PAPI_PROFIL_FORCE_SW ) ) {
	    papi_return( PAPI_ECNFLCT );
	 }
      }

      for( i = 0; i < ESI->profile.event_counter; i++ ) {
	 if ( ESI->profile.EventCode[i] == EventCode ) {
	    break;
	 }
      }

      if ( i == ESI->profile.event_counter ) {
	 i = ESI->profile.event_counter;
	 ESI->profile.event_counter++;
	 ESI->profile.EventCode[i] = EventCode;
      }
      ESI->profile.prof[i] = prof;
      ESI->profile.count[i] = profcnt;
      ESI->profile.threshold[i] = threshold;
      ESI->profile.EventIndex[i] = index;
   }

   APIDBG( "Profile event counter is %d\n", ESI->profile.event_counter );

   /* Clear out old flags */
   if ( threshold == 0 ) {
      flags |= ESI->profile.flags;
   }

   /* make sure no invalid flags are set */
   if ( flags &
	~( PAPI_PROFIL_POSIX | PAPI_PROFIL_RANDOM | PAPI_PROFIL_WEIGHTED |
	   PAPI_PROFIL_COMPRESS | PAPI_PROFIL_BUCKETS | PAPI_PROFIL_FORCE_SW |
	   PAPI_PROFIL_INST_EAR | PAPI_PROFIL_DATA_EAR ) ) {
      papi_return( PAPI_EINVAL );
   }

   /* if we have kernel-based profiling, then we're just asking for 
      signals on interrupt. */
   /* if we don't have kernel-based profiling, then we're asking for 
      emulated PMU interrupt */
   if ( ( flags & PAPI_PROFIL_FORCE_SW ) &&
	( _papi_hwd[cidx]->cmp_info.kernel_profile == 0 ) ) {
      forceSW = PAPI_OVERFLOW_FORCE_SW;
   }

   /* make sure one and only one bucket size is set */
   buckets = flags & PAPI_PROFIL_BUCKETS;
   if ( !buckets ) {
      flags |= PAPI_PROFIL_BUCKET_16;	/* default to 16 bit if nothing set */
   }
   else {
      /* return error if more than one set */
      if ( !( ( buckets == PAPI_PROFIL_BUCKET_16 ) ||
	      ( buckets == PAPI_PROFIL_BUCKET_32 ) ||
	      ( buckets == PAPI_PROFIL_BUCKET_64 ) ) ) {
	 papi_return( PAPI_EINVAL );
      }
   }

   /* Set up the option structure for the low level */
   ESI->profile.flags = flags;

   if ( _papi_hwd[cidx]->cmp_info.kernel_profile &&
	!( ESI->profile.flags & PAPI_PROFIL_FORCE_SW ) ) {
      retval = _papi_hwd[cidx]->set_profile( ESI, index, threshold );
      if ( ( retval == PAPI_OK ) && ( threshold > 0 ) ) {
	 /* We need overflowing because we use the overflow dispatch handler */
	 ESI->state |= PAPI_OVERFLOWING;
	 ESI->overflow.flags |= PAPI_OVERFLOW_HARDWARE;
      }
   } else {
      retval = PAPI_overflow( EventSet, EventCode, threshold, forceSW,
			      _papi_hwi_dummy_handler );
   }
	
   if ( retval < PAPI_OK ) {
      papi_return( retval );	/* We should undo stuff here */
   }

   /* Toggle the profiling flags and ESI state */

   if ( ESI->profile.event_counter >= 1 ) {
      ESI->state |= PAPI_PROFILING;
   }
   else {
      ESI->state ^= PAPI_PROFILING;
      ESI->profile.flags = 0;
   }

   return PAPI_OK;
}

/** @class PAPI_profil
 *  @brief Generate a histogram of hardware counter overflows vs. PC addresses.
 *
 * @par C Interface:
 * \#include <papi.h> @n
 * int PAPI_profil(void *buf, unsigned bufsiz, unsigned long offset,
 * unsigned scale, int EventSet, int EventCode, int threshold, int flags );
 *
 * @par Fortran Interface
 * The profiling routines have no Fortran interface.
 *
 * @param *buf
 *    -- pointer to a buffer of bufsiz bytes in which the histogram counts are 
 *	 stored in an array of unsigned short, unsigned int, or 
 *	 unsigned long long values, or 'buckets'. 
 *	 The size of the buckets is determined by values in the flags argument.
 * @param bufsiz
 *    -- the size of the histogram buffer in bytes. 
 *	 It is computed from the length of the code region to be profiled, 
 *	 the size of the buckets, and the scale factor as discussed above.
 * @param offset
 *    -- the start address of the region to be profiled.
 * @param scale
 *    -- broadly and historically speaking, a contraction factor that 
 *       indicates how much smaller the histogram buffer is than the 
 *       region to be profiled.  More precisely, scale is interpreted as an 
 *       unsigned 16-bit fixed-point fraction with the decimal point 
 *       implied on the left. 
 *	 Its value is the reciprocal of the number of addresses in a 
 *       subdivision, per counter of histogram buffer. 
 *	 Below is a table of representative values for scale.
 * @param EventSet
 *    -- The PAPI EventSet to profile. This EventSet is marked as 
 *       profiling-ready, but profiling doesn't actually start until a 
 *       PAPI_start() call is issued.
 * @param EventCode
 *    -- Code of the Event in the EventSet to profile. 
 *	 This event must already be a member of the EventSet.
 * @param threshold
 *    -- minimum number of events that must occur before the PC is sampled. 
 *	 If hardware overflow is supported for your component, this threshold 
 *	 will trigger an interrupt when reached. 
 *	 Otherwise, the counters will be sampled periodically and the PC will 
 *       be recorded for the first sample that exceeds the threshold. 
 *	 If the value of threshold is 0, profiling will be disabled for 
 *       this event.
 * @param flags
 *    -- bit pattern to control profiling behavior. 
 *	 Defined values are shown in the table above.
 *
 * @retval PAPI_OK 
 * @retval PAPI_EINVAL 
 *	   One or more of the arguments is invalid.
 * @retval PAPI_ENOMEM 
 *	   Insufficient memory to complete the operation.
 * @retval PAPI_ENOEVST 
 *	   The EventSet specified does not exist.
 * @retval PAPI_EISRUN 
 *	   The EventSet is currently counting events.
 * @retval PAPI_ECNFLCT 
 *	   The underlying counter hardware can not count this event and other 
 *	   events in the EventSet simultaneously.
 * @retval PAPI_ENOEVNT 
 *	   The PAPI preset is not available on the underlying hardware. 
 *
 *	PAPI_profil() provides hardware event statistics by profiling 
 *      the occurrence of specified hardware counter events.
 *	It is designed to mimic the UNIX SVR4 profil call.
 *	
 *	The statistics are generated by creating a histogram of hardware 
 *      counter event overflows vs. program counter addresses for the current 
 *      process. The histogram is defined for a specific region of program 
 *      code to be profiled, and the identified region is logically broken up 
 *      into a set of equal size subdivisions, each of which corresponds to a 
 *      count in the histogram. 
 *	
 *	With each hardware event overflow, the current subdivision is 
 *      identified and its corresponding histogram count is incremented. 
 *	These counts establish a relative measure of how many hardware counter 
 *	events are occurring in each code subdivision.
 *	
 *	The resulting histogram counts for a profiled region can be used to 
 *	identify those program addresses that generate a disproportionately 
 *	high percentage of the event of interest.
 *
 *	Events to be profiled are specified with the EventSet and 
 *      EventCode parameters.   More than one event can be simultaneously 
 *      profiled by calling PAPI_profil() 
 *	several times with different EventCode values. 
 *	Profiling can be turned off for a given event by calling PAPI_profil() 
 *	with a threshold value of 0. 
 *
 *	@par Representative values for the scale variable
 *  @manonly
 * HEX      DECIMAL  DEFININTION  
 * 0x20000  131072   Maps precisely one instruction address to a unique bucket in buf.  
 * 0x10000   65536   Maps precisely two instruction addresses to a unique bucket in buf.  
 * 0x0FFFF   65535   Maps approximately two instruction addresses to a unique bucket in buf.  
 * 0x08000   32768   Maps every four instruction addresses to a bucket in buf.  
 * 0x04000   16384   Maps every eight instruction addresses to a bucket in buf.  
 * 0x00002       2   Maps all instruction addresses to the same bucket in buf.  
 * 0x00001       1   Undefined.  
 * 0x00000       0   Undefined.  
 * @endmanonly
 * @htmlonly
 * <table class="doxtable">
 * <tr><th>HEX</th>     <th>DECIMAL</th>  <th>DEFINITION</th></tr>
 * <tr><td>0x20000</td>	<td> 131072</td>  <td>Maps precisely one instruction address to a unique bucket in buf.</td></tr>
 * <tr><td>0x10000</td>	<td>  65536</td>  <td>Maps precisely two instruction addresses to a unique bucket in buf.</td></tr>
 * <tr><td>0xFFFF</td>	<td>  65535</td> <td>Maps approximately two instruction addresses to a unique bucket in buf.</td></tr>
 * <tr><td>0x8000</td>	<td>  32768</td> <td>Maps every four instruction addresses to a bucket in buf.</td></tr>
 * <tr><td>0x4000</td>	<td>  16384</td> <td>Maps every eight instruction addresses to a bucket in buf.</td></tr>
 * <tr><td>0x0002</td>	<td>      2</td> <td>Maps all instruction addresses to the same bucket in buf.</td></tr>
 * <tr><td>0x0001</td>	<td>      1</td> <td>Undefined.</td></tr>
 * <tr><td>0x0000</td>	<td>      0</td> <td>Undefined. </td></tr>
 * </table>
 * @endhtmlonly
 *
 *	Historically, the scale factor was introduced to allow the 
 *      allocation of buffers smaller than the code size to be profiled. 
 *	Data and instruction sizes were assumed to be multiples of 16-bits. 
 *	These assumptions are no longer necessarily true. 
 *	PAPI_profil() has preserved the traditional definition of 
 *      scale where appropriate, but deprecated the definitions for 0 and 1 
 *      (disable scaling) and extended the range of scale to include 
 *      65536 and 131072 to allow for exactly two 
 *	addresses and exactly one address per profiling bucket.
 *
 *	The value of bufsiz is computed as follows:
 *	
 *	bufsiz = (end - start)*(bucket_size/2)*(scale/65536) where
 * @arg bufsiz - the size of the buffer in bytes
 * @arg end, start - the ending and starting addresses of the profiled region
 * @arg bucket_size - the size of each bucket in bytes; 2, 4, or 8 as defined in flags 
 *
 *	@par Defined bits for the flags variable:
 * @arg PAPI_PROFIL_POSIX	Default type of profiling, similar to profil (3).@n
 * @arg PAPI_PROFIL_RANDOM	Drop a random 25% of the samples.@n
 * @arg PAPI_PROFIL_WEIGHTED	Weight the samples by their value.@n
 * @arg PAPI_PROFIL_COMPRESS	Ignore samples as values in the hash buckets get big.@n
 * @arg PAPI_PROFIL_BUCKET_16	Use unsigned short (16 bit) buckets, This is the default bucket.@n
 * @arg PAPI_PROFIL_BUCKET_32	Use unsigned int (32 bit) buckets.@n
 * @arg PAPI_PROFIL_BUCKET_64	Use unsigned long long (64 bit) buckets.@n
 * @arg PAPI_PROFIL_FORCE_SW	Force software overflow in profiling. @n
 *
 * @par Example
 * @code
 * int retval;
 * unsigned long length;
 * PAPI_exe_info_t *prginfo;
 * unsigned short *profbuf;
 *
 * if ((prginfo = PAPI_get_executable_info()) == NULL)
 *    handle_error(1);
 *
 * length = (unsigned long)(prginfo->text_end - prginfo->text_start);
 *
 * profbuf = (unsigned short *)malloc(length);
 * if (profbuf == NULL)
 *    handle_error(1);
 * memset(profbuf,0x00,length);
 *
 * if ((retval = PAPI_profil(profbuf, length, start, 65536, EventSet,
 *     PAPI_FP_INS, 1000000, PAPI_PROFIL_POSIX | PAPI_PROFIL_BUCKET_16)) 
 *    != PAPI_OK)
 *    handle_error(retval);
 * @endcode
 *
 * @bug If you call PAPI_profil, PAPI allocates buffer space that will not be 
 *      freed if you call PAPI_shutdown or PAPI_cleanup_eventset. 
 *      To clean all memory, you must call PAPI_profil on the Events with 
 *      a 0 threshold. 
 *
 * @see PAPI_overflow 
 * @see PAPI_sprofil
 *
 */
int
PAPI_profil( void *buf, unsigned bufsiz, caddr_t offset,
			 unsigned scale, int EventSet, int EventCode, int threshold,
			 int flags )
{
	APIDBG( "Entry: buf: %p, bufsiz: %d, offset: %p, scale: %u, EventSet: %d, EventCode: %#x, threshold: %d, flags: %#x\n", buf, bufsiz, offset, scale, EventSet, EventCode, threshold, flags);
	EventSetInfo_t *ESI;
	int i;
	int retval;

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	/* scale factors are checked for validity in PAPI_sprofil */

	if ( threshold > 0 ) {
		PAPI_sprofil_t *prof;

		for ( i = 0; i < ESI->profile.event_counter; i++ ) {
			if ( ESI->profile.EventCode[i] == EventCode )
				break;
		}

		if ( i == ESI->profile.event_counter ) {
			prof =
				( PAPI_sprofil_t * ) papi_malloc( sizeof ( PAPI_sprofil_t ) );
			memset( prof, 0x0, sizeof ( PAPI_sprofil_t ) );
			prof->pr_base = buf;
			prof->pr_size = bufsiz;
			prof->pr_off = offset;
			prof->pr_scale = scale;

			retval =
				PAPI_sprofil( prof, 1, EventSet, EventCode, threshold, flags );

			if ( retval != PAPI_OK )
				papi_free( prof );
		} else {
			prof = ESI->profile.prof[i];
			prof->pr_base = buf;
			prof->pr_size = bufsiz;
			prof->pr_off = offset;
			prof->pr_scale = scale;
			retval =
				PAPI_sprofil( prof, 1, EventSet, EventCode, threshold, flags );
		}
		papi_return( retval );
	}

	for ( i = 0; i < ESI->profile.event_counter; i++ ) {
		if ( ESI->profile.EventCode[i] == EventCode )
			break;
	}
	/* EventCode not found */
	if ( i == ESI->profile.event_counter )
		papi_return( PAPI_EINVAL );

	papi_free( ESI->profile.prof[i] );
	ESI->profile.prof[i] = NULL;

	papi_return( PAPI_sprofil( NULL, 0, EventSet, EventCode, 0, flags ) );
}

/* This function sets the low level default granularity
   for all newly manufactured eventsets. The first function
   preserves API compatibility and assumes component 0;
   The second function takes a component argument. */

/** @class PAPI_set_granularity
 *	@brief Set the default counting granularity for eventsets bound to the cpu component.
 *
 *	@par C Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_set_granularity( int granularity );
 *
 *	@param -- granularity one of the following constants as defined in the papi.h header file
 *	@arg PAPI_GRN_THR	-- Count each individual thread
 *	@arg PAPI_GRN_PROC	-- Count each individual process
 *	@arg PAPI_GRN_PROCG	-- Count each individual process group
 *	@arg PAPI_GRN_SYS	-- Count the current CPU
 *	@arg PAPI_GRN_SYS_CPU	-- Count all CPUs individually
 *	@arg PAPI_GRN_MIN	-- The finest available granularity
 *	@arg PAPI_GRN_MAX	-- The coarsest available granularity 
 *  @manonly
 *  @endmanonly
 *
 *	@retval PAPI_OK 
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *  @manonly
 *  @endmanonly
 *
 *	PAPI_set_granularity sets the default counting granularity for all new 
 *	event sets created by PAPI_create_eventset. 
 *	This call implicitly sets the granularity for the cpu component 
 *	(component 0) and is included to preserve backward compatibility. 
 *
 *	@par Example:
 *	@code
int ret;

// Initialize the library
ret = PAPI_library_init(PAPI_VER_CURRENT);
if (ret > 0 && ret != PAPI_VER_CURRENT) {
  fprintf(stderr,"PAPI library version mismatch!\n");
  exit(1); 
}
if (ret < 0) handle_error(ret);

// Set the default granularity for the cpu component
ret = PAPI_set_granularity(PAPI_GRN_PROC);
if (ret != PAPI_OK) handle_error(ret);
ret = PAPI_create_eventset(&EventSet);
if (ret != PAPI_OK) handle_error(ret);
 *	@endcode
 *
 *	@see  PAPI_set_cmp_granularity PAPI_set_domain PAPI_set_opt PAPI_get_opt
 */
int
PAPI_set_granularity( int granularity )
{
	return ( PAPI_set_cmp_granularity( granularity, 0 ) );
}

/** @class PAPI_set_cmp_granularity
 *	@brief Set the default counting granularity for eventsets bound to the specified component.
 *
 *	@par C Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_set_cmp_granularity( int granularity, int cidx );
 *
 *	@param granularity one of the following constants as defined in the papi.h header file
 *	@arg PAPI_GRN_THR	Count each individual thread
 *	@arg PAPI_GRN_PROC	Count each individual process
 *	@arg PAPI_GRN_PROCG	Count each individual process group
 *	@arg PAPI_GRN_SYS	Count the current CPU
 *	@arg PAPI_GRN_SYS_CPU	Count all CPUs individually
 *	@arg PAPI_GRN_MIN	The finest available granularity
 *	@arg PAPI_GRN_MAX	The coarsest available granularity
 *
 *	@param cidx
 *		An integer identifier for a component. 
 *		By convention, component 0 is always the cpu component. 
 *  @manonly
 *  @endmanonly
 *
 *	@retval PAPI_OK 
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOCMP 
 *		The argument cidx is not a valid component.
 *  @manonly
 *  @endmanonly
 *
 *	PAPI_set_cmp_granularity sets the default counting granularity for all new 
 *	event sets, and requires an explicit component argument. 
 *	Event sets that are already in existence are not affected. 
 *
 *	To change the granularity of an existing event set, please see PAPI_set_opt. 
 *	The reader should note that the granularity of an event set affects only 
 *	the mode in which the counter continues to run. 
 *
 *	@par Example:
 *	@code
int ret;

// Initialize the library
ret = PAPI_library_init(PAPI_VER_CURRENT);
if (ret > 0 && ret != PAPI_VER_CURRENT) {
  fprintf(stderr,"PAPI library version mismatch!\n");
  exit(1); 
}
if (ret < 0) handle_error(ret);

// Set the default granularity for the cpu component
ret = PAPI_set_cmp_granularity(PAPI_GRN_PROC, 0);
if (ret != PAPI_OK) handle_error(ret);
ret = PAPI_create_eventset(&EventSet);
if (ret != PAPI_OK) handle_error(ret);
 *	@endcode
 *
 *	@see  PAPI_set_granularity PAPI_set_domain PAPI_set_opt PAPI_get_opt
 */
int
PAPI_set_cmp_granularity( int granularity, int cidx )
{
	PAPI_option_t ptr;

	memset( &ptr, 0, sizeof ( ptr ) );
	ptr.defgranularity.def_cidx = cidx;
	ptr.defgranularity.granularity = granularity;
	papi_return( PAPI_set_opt( PAPI_DEFGRN, &ptr ) );
}

/* This function sets the low level default counting domain
   for all newly manufactured eventsets. The first function
   preserves API compatibility and assumes component 0;
   The second function takes a component argument. */

/** @class PAPI_set_domain
 *	@brief Set the default counting domain for new event sets bound to the cpu component.
 *
 *	@par C Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_set_domain( int domain );
 *
 *	@param domain one of the following constants as defined in the papi.h header file
 *	@arg PAPI_DOM_USER User context counted
 *	@arg PAPI_DOM_KERNEL  Kernel/OS context counted
 *	@arg PAPI_DOM_OTHER Exception/transient mode counted
 *	@arg PAPI_DOM_SUPERVISOR Supervisor/hypervisor context counted
 *	@arg PAPI_DOM_ALL All above contexts counted
 *	@arg PAPI_DOM_MIN The smallest available context
 *	@arg PAPI_DOM_MAX The largest available context 
 *  @manonly
 *  @endmanonly
 *
 *	@retval PAPI_OK 
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *  @manonly
 *  @endmanonly
 * 
 *	PAPI_set_domain sets the default counting domain for all new event sets 
 *	created by PAPI_create_eventset in all threads. 
 *	This call implicitly sets the domain for the cpu component (component 0) 
 *	and is included to preserve backward compatibility. 
 *
 *	@par Example:
 *	@code
int ret;

// Initialize the library
ret = PAPI_library_init(PAPI_VER_CURRENT);
if (ret > 0 && ret != PAPI_VER_CURRENT) {
  fprintf(stderr,"PAPI library version mismatch!\n");
  exit(1); 
}
if (ret < 0) handle_error(ret);

// Set the default domain for the cpu component
ret = PAPI_set_domain(PAPI_DOM_KERNEL);
if (ret != PAPI_OK) handle_error(ret);
ret = PAPI_create_eventset(&EventSet);
if (ret != PAPI_OK) handle_error(ret);
 *	@endcode
 *
 *	@see PAPI_set_cmp_domain PAPI_set_granularity PAPI_set_opt PAPI_get_opt
 */
int
PAPI_set_domain( int domain )
{
	return ( PAPI_set_cmp_domain( domain, 0 ) );
}

/** @class PAPI_set_cmp_domain
 *	@brief Set the default counting domain for new event sets bound to the specified component.
 *
 *	@par C Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_set_cmp_domain( int domain, int  cidx );
 *
 *	@param domain one of the following constants as defined in the papi.h header file
 *	@arg PAPI_DOM_USER User context counted
 *	@arg PAPI_DOM_KERNEL  Kernel/OS context counted
 *	@arg PAPI_DOM_OTHER Exception/transient mode counted
 *	@arg PAPI_DOM_SUPERVISOR Supervisor/hypervisor context counted
 *	@arg PAPI_DOM_ALL All above contexts counted
 *	@arg PAPI_DOM_MIN The smallest available context
 *	@arg PAPI_DOM_MAX The largest available context 
 *	@arg PAPI_DOM_HWSPEC Something other than CPU like stuff. Individual components can decode
 *  low order bits for more meaning
 *
 *	@param cidx
 *		An integer identifier for a component. 
 *		By convention, component 0 is always the cpu component. 
 *  @manonly
 *  @endmanonly
 *
 *	@retval PAPI_OK 
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOCMP 
 *		The argument cidx is not a valid component.
 *  @manonly
 *  @endmanonly
 *
 *	PAPI_set_cmp_domain sets the default counting domain for all new event sets 
 *	in all threads, and requires an explicit component argument. 
 *	Event sets that are already in existence are not affected. 
 *	To change the domain of an existing event set, please see PAPI_set_opt.
 *	The reader should note that the domain of an event set affects only the 
 *	mode in which the counter continues to run. 
 *	Counts are still aggregated for the current process, and not for any other 
 *	processes in the system. 
 *	Thus when requesting PAPI_DOM_KERNEL , the user is asking for events that 
 *	occur on behalf of the process, inside the kernel. 
 *
 *	@par Example:
 *	@code
int ret;

// Initialize the library
ret = PAPI_library_init(PAPI_VER_CURRENT);
if (ret > 0 && ret != PAPI_VER_CURRENT) {
  fprintf(stderr,"PAPI library version mismatch!\n");
  exit(1); 
}
if (ret < 0) handle_error(ret);

// Set the default domain for the cpu component
ret = PAPI_set_cmp_domain(PAPI_DOM_KERNEL,0);
if (ret != PAPI_OK) handle_error(ret);
ret = PAPI_create_eventset(&EventSet);
if (ret != PAPI_OK) handle_error(ret);
 *	@endcode
 *
 *	@see PAPI_set_domain PAPI_set_granularity PAPI_set_opt PAPI_get_opt
 */
int
PAPI_set_cmp_domain( int domain, int cidx )
{
	PAPI_option_t ptr;

	memset( &ptr, 0, sizeof ( ptr ) );
	ptr.defdomain.def_cidx = cidx;
	ptr.defdomain.domain = domain;
	papi_return( PAPI_set_opt( PAPI_DEFDOM, &ptr ) );
}

/**	@class PAPI_add_events
 *	@brief add multiple PAPI presets or native hardware events to an event set 
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	int PAPI_add_events( int  EventSet, int * EventCodes, int  number );
 *
 *	PAPI_add_event adds one event to a PAPI Event Set. PAPI_add_events does 
 *	the same, but for an array of events. @n
 *	A hardware event can be either a PAPI preset or a native hardware event code.
 *	For a list of PAPI preset events, see PAPI_presets or run the avail test case
 *	in the PAPI distribution. PAPI presets can be passed to PAPI_query_event to see
 *	if they exist on the underlying architecture.
 *	For a list of native events available on current platform, run native_avail
 *	test case in the PAPI distribution. For the encoding of native events,
 *	see PAPI_event_name_to_code to learn how to generate native code for the
 *	supported native event on the underlying architecture.
 *
 *	@param EventSet
 *		An integer handle for a PAPI Event Set as created by PAPI_create_eventset.
 *	@param *EventCode 
 *		An array of defined events.
 *	@param number 
 *		An integer indicating the number of events in the array *EventCode.
 *		It should be noted that PAPI_add_events can partially succeed, 
 *		exactly like PAPI_remove_events. 
 *
 *	@retval Positive-Integer
 *		The number of consecutive elements that succeeded before the error. 
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOMEM 
 *		Insufficient memory to complete the operation.
 *	@retval PAPI_ENOEVST 
 *		The event set specified does not exist.
 *	@retval PAPI_EISRUN 
 *		The event set is currently counting events.
 *	@retval PAPI_ECNFLCT 
 *		The underlying counter hardware can not count this event and other events 
 *		in the event set simultaneously.
 *	@retval PAPI_ENOEVNT 
 *		The PAPI preset is not available on the underlying hardware.
 *	@retval PAPI_EBUG 
 *		Internal error, please send mail to the developers. 
 *
 *	@par Examples:
 *	@code
 *	int EventSet = PAPI_NULL;
 *	unsigned int native = 0x0;
 *	if ( PAPI_create_eventset( &EventSet ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Add Total Instructions Executed to our EventSet
 *	if ( PAPI_add_event( EventSet, PAPI_TOT_INS ) != PAPI_OK )
 *	handle_error( 1 );
 *	// Add native event PM_CYC to EventSet
 *	if ( PAPI_event_name_to_code( "PM_CYC", &native ) != PAPI_OK )
 *	handle_error( 1 );
 *	if ( PAPI_add_event( EventSet, native ) != PAPI_OK )
 *	handle_error( 1 );
 *	@endcode
 *
 *	@bug
 *	The vector function should take a pointer to a length argument so a proper 
 *	return value can be set upon partial success.
 *
 *	@see PAPI_cleanup_eventset @n
 *	PAPI_destroy_eventset @n
 *	PAPI_event_code_to_name @n
 *	PAPI_remove_events @n
 *	PAPI_query_event @n
 *	PAPI_presets @n
 *	PAPI_native @n
 *	PAPI_remove_event
 */
int
PAPI_add_events( int EventSet, int *Events, int number )
{
	APIDBG( "Entry: EventSet: %d, Events: %p, number: %d\n", EventSet, Events, number);
	int i, retval;

	if ( ( Events == NULL ) || ( number <= 0 ) )
		papi_return( PAPI_EINVAL );

	for ( i = 0; i < number; i++ ) {
		retval = PAPI_add_event( EventSet, Events[i] );
		if ( retval != PAPI_OK ) {
			if ( i == 0 )
				papi_return( retval );
			else
				return ( i );
		}
	}
	return ( PAPI_OK );
}

/** @class PAPI_remove_events
 * @brief Remove an array of hardware event codes from a PAPI event set.
 *
 * A hardware event can be either a PAPI Preset or a native hardware event code. 
 * For a list of PAPI preset events, see PAPI_presets or run the papi_avail utility in the PAPI distribution. 
 * PAPI Presets can be passed to PAPI_query_event to see if they exist on the underlying architecture. 
 * For a list of native events available on current platform, run papi_native_avail in the PAPI distribution. 
 * It should be noted that PAPI_remove_events can partially succeed, exactly like PAPI_add_events. 
 *
 *	@par C Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_remove_events( int  EventSet, int * EventCode, int  number );
 *
 *	@param EventSet
 *		an integer handle for a PAPI event set as created by PAPI_create_eventset
 *	@param *Events
 *		an array of defined events
 *	@param number
 *		an integer indicating the number of events in the array *EventCode 
 *
 *	@retval Positive integer 
 *		The number of consecutive elements that succeeded before the error.
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *	@retval PAPI_ENOEVST 
 *		The EventSet specified does not exist.
 *	@retval PAPI_EISRUN 
 *		The EventSet is currently counting events.
 *	@retval PAPI_ECNFLCT 
 *		The underlying counter hardware can not count this event and other 
 *		events in the EventSet simultaneously.
 *	@retval PAPI_ENOEVNT 
 *		The PAPI preset is not available on the underlying hardware. 
 *
 *	@par Example:
 *	@code
int EventSet = PAPI_NULL;
int Events[] = {PAPI_TOT_INS, PAPI_FP_OPS};
int ret;
 
 // Create an empty EventSet
ret = PAPI_create_eventset(&EventSet);
if (ret != PAPI_OK) handle_error(ret);

// Add two events to our EventSet
ret = PAPI_add_events(EventSet, Events, 2);
if (ret != PAPI_OK) handle_error(ret);

// Start counting
ret = PAPI_start(EventSet);
if (ret != PAPI_OK) handle_error(ret);

// Stop counting, ignore values
ret = PAPI_stop(EventSet, NULL);
if (ret != PAPI_OK) handle_error(ret);

// Remove event
ret = PAPI_remove_events(EventSet, Events, 2);
if (ret != PAPI_OK) handle_error(ret);
 *	@endcode
 *
 *  @bug The last argument should be a pointer so the count can be returned on partial success in addition
 *  to a real error code.
 *
 *	@see PAPI_cleanup_eventset PAPI_destroy_eventset PAPI_event_name_to_code 
 *		PAPI_presets PAPI_add_event PAPI_add_events
 */
int
PAPI_remove_events( int EventSet, int *Events, int number )
{
	APIDBG( "Entry: EventSet: %d, Events: %p, number: %d\n", EventSet, Events, number);
	int i, retval;

	if ( ( Events == NULL ) || ( number <= 0 ) )
		papi_return( PAPI_EINVAL );

	for ( i = 0; i < number; i++ ) {
		retval = PAPI_remove_event( EventSet, Events[i] );
		if ( retval != PAPI_OK ) {
			if ( i == 0 )
				papi_return( retval );
			else
				return ( i );
		}
	}
	return ( PAPI_OK );
}

/**	@class PAPI_list_events
 *	@brief list the events in an event set
 *
 *	PAPI_list_events() returns an array of events and a count of the
 *  total number of events in an event set.
 *	This call assumes an initialized PAPI library and a successfully created event set.
 *
 * @par C Interface
 * \#include <papi.h> @n
 * int PAPI_list_events(int *EventSet, int *Events, int *number );
*
 *	@param[in] EventSet
 *		An integer handle for a PAPI event set as created by PAPI_create_eventset 
 *	@param[in,out] *Events 
 *		A pointer to a preallocated array of codes for events, such as PAPI_INT_INS. 
 *		No more than *number codes will be stored into the array.
 *	@param[in,out] *number 
 *		On input, the size of the Events array, or maximum number of event codes
 *		to be returned. A value of 0 can be used to probe an event set.
 *		On output, the number of events actually in the event set.
 *		This value may be greater than the actually stored number of event codes. 
 *
 *	@retval PAPI_EINVAL
 *	@retval PAPI_ENOEVST
 *	
 *	@par Examples:
 *	@code
 		if (PAPI_event_name_to_code("PAPI_TOT_INS",&EventCode) != PAPI_OK)
 		exit(1);
 		if (PAPI_add_event(EventSet, EventCode) != PAPI_OK)
 		exit(1);
 		Convert a second event name to an event code 
 		if (PAPI_event_name_to_code("PAPI_L1_LDM",&EventCode) != PAPI_OK)
 		exit(1);
 		if (PAPI_add_event(EventSet, EventCode) != PAPI_OK)
 		exit(1);
 		number = 0;
 		if(PAPI_list_events(EventSet, NULL, &number))
 		exit(1);
 		if(number != 2)
 		exit(1);
 		if(PAPI_list_events(EventSet, Events, &number))
 		exit(1);
 *	@endcode
 *	@see PAPI_event_code_to_name 
 *	@see PAPI_event_name_to_code 
 *	@see PAPI_add_event
 *	@see PAPI_create_eventset
 */
int
PAPI_list_events( int EventSet, int *Events, int *number )
{
	APIDBG( "Entry: EventSet: %d, Events: %p, number: %p\n", EventSet, Events, number);
	EventSetInfo_t *ESI;
	int i, j;

	if ( *number < 0 )
		papi_return( PAPI_EINVAL );

	if ( ( Events == NULL ) && ( *number > 0 ) )
		papi_return( PAPI_EINVAL );

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( !ESI )
		papi_return( PAPI_ENOEVST );

	if ( ( Events == NULL ) || ( *number == 0 ) ) {
		*number = ESI->NumberOfEvents;
		papi_return( PAPI_OK );
	}

	for ( i = 0, j = 0; j < ESI->NumberOfEvents; i++ ) {
		if ( ( int ) ESI->EventInfoArray[i].event_code != PAPI_NULL ) {
			Events[j] = ( int ) ESI->EventInfoArray[i].event_code;
			j++;
			if ( j == *number )
				break;
		}
	}

	*number = j;

	return ( PAPI_OK );
}

/* xxx This is OS dependent, not component dependent, right? */
/** @class PAPI_get_dmem_info
 *	@brief Get information about the dynamic memory usage of the current program. 
 *
 *	@par C Prototype:
 *		\#include <papi.h> @n
 *		int PAPI_get_dmem_info( PAPI_dmem_info_t *dest );
 *
 *	@param dest
 *		structure to be filled in @ref PAPI_dmem_info_t
 *	
 *	@retval PAPI_ECMP
 *		The function is not implemented for the current component.
 *	@retval PAPI_EINVAL 
 *		Any value in the structure or array may be undefined as indicated by 
 *		this error value.
 *	@retval PAPI_SYS 
 *		A system error occurred.
 *
 *	@note This function is only implemented for the Linux operating system.
 *	This function takes a pointer to a PAPI_dmem_info_t structure 
 *	and returns with the structure fields filled in. 
 *	A value of PAPI_EINVAL in any field indicates an undefined parameter. 
 *
 *	@see PAPI_get_executable_info PAPI_get_hardware_info PAPI_get_opt PAPI_library_init
 */
int
PAPI_get_dmem_info( PAPI_dmem_info_t * dest )
{
	if ( dest == NULL )
		return PAPI_EINVAL;

	memset( ( void * ) dest, 0x0, sizeof ( PAPI_dmem_info_t ) );
	return ( _papi_os_vector.get_dmem_info( dest ) );
}


/** @class PAPI_get_executable_info
 *	@brief Get the executable's address space info.
 *
 *	@par C Interface:
 *	\#include <papi.h> @n
 *	const PAPI_exe_info_t *PAPI_get_executable_info( void );
 *
 *	This function returns a pointer to a structure containing information 
 *	about the current program.
 *
 *	@param fullname
 *		Fully qualified path + filename of the executable.
 *	@param name
 *		Filename of the executable with no path information.
 *	@param text_start, text_end
 *		Start and End addresses of program text segment.
 *	@param data_start, data_end
 *		Start and End addresses of program data segment.
 *	@param bss_start, bss_end
 *		Start and End addresses of program bss segment.
 *
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid. 
 *
 *	@par Examples:
 *	@code
 *	const PAPI_exe_info_t *prginfo = NULL;
 *	if ( ( prginfo = PAPI_get_executable_info( ) ) == NULL )
 *	exit( 1 );
 *	printf( "Path+Program: %s\n", exeinfo->fullname );
 *	printf( "Program: %s\n", exeinfo->address_info.name );
 *	printf( "Text start: %p, Text end: %p\n", exeinfo->address_info.text_start, exeinfo->address_info.text_end) ;
 *	printf( "Data start: %p, Data end: %p\n", exeinfo->address_info.data_start, exeinfo->address_info.data_end );
 *	printf( "Bss start: %p, Bss end: %p\n", exeinfo->address_info.bss_start, exeinfo->address_info.bss_end );
 *	@endcode
 *
 *	@see PAPI_get_opt 
 *	@see PAPI_get_hardware_info 
 *	@see PAPI_exe_info_t
 */
const PAPI_exe_info_t *
PAPI_get_executable_info( void )
{
	PAPI_option_t ptr;
	int retval;

	memset( &ptr, 0, sizeof ( ptr ) );
	retval = PAPI_get_opt( PAPI_EXEINFO, &ptr );
	if ( retval == PAPI_OK )
		return ( ptr.exe_info );
	else
		return ( NULL );
}

/** @class PAPI_get_shared_lib_info
 *	@brief Get address info about the shared libraries used by the process. 
 *
 *	In C, this function returns a pointer to a structure containing information 
 *	about the shared library used by the program. 
 *	There is no Fortran equivalent call. 
 *	@note This data will be incorporated into the PAPI_get_executable_info call in the future. PAPI_get_shared_lib_info will be deprecated and should be used with caution.
 *
 *	@bug If called before initialization the behavior of the routine is undefined.
 *
 *	@see PAPI_shlib_info_t
 *	@see PAPI_get_hardware_info
 *	@see PAPI_get_executable_info 
 *	@see PAPI_get_dmem_info 
 *	@see PAPI_get_opt PAPI_library_init
 */
const PAPI_shlib_info_t *
PAPI_get_shared_lib_info( void )
{
	PAPI_option_t ptr;
	int retval;

	memset( &ptr, 0, sizeof ( ptr ) );
	retval = PAPI_get_opt( PAPI_SHLIBINFO, &ptr );
	if ( retval == PAPI_OK )
		return ( ptr.shlib_info );
	else
		return ( NULL );
}
/**	@class PAPI_get_hardware_info 
 *	@brief get information about the system hardware
 *
 *	In C, this function returns a pointer to a structure containing information about the hardware on which the program runs. 
 *       In Fortran, the values of the structure are returned explicitly.
 *
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid.
 *
 *	@bug
 *		If called before initialization the behavior of the routine is undefined. 
 *	
 *	@note The C structure contains detailed information about cache and TLB sizes. 
 *		This information is not available from Fortran.
 *
 *	@par Examples:
 *	@code
 		const PAPI_hw_info_t *hwinfo = NULL;
 		if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)	
 		exit(1);
 		if ((hwinfo = PAPI_get_hardware_info()) == NULL)
 		exit(1);
 		printf("%d CPUs at %f Mhz.\en",hwinfo->totalcpus,hwinfo->mhz);
 *	@endcode	
 *
 *	@see PAPI_hw_info_t
 *	@see PAPI_get_executable_info, PAPI_get_opt, PAPI_get_dmem_info, PAPI_library_init
 */
const PAPI_hw_info_t *
PAPI_get_hardware_info( void )
{
	PAPI_option_t ptr;
	int retval;

	memset( &ptr, 0, sizeof ( ptr ) );
	retval = PAPI_get_opt( PAPI_HWINFO, &ptr );
	if ( retval == PAPI_OK )
		return ( ptr.hw_info );
	else
		return ( NULL );
}


/* The next 4 timing functions always use component 0 */

/**	@class PAPI_get_real_cyc
 *	@brief get real time counter value in clock cycles 
 * 	Returns the total real time passed since some arbitrary starting point. 
 *	The time is returned in clock cycles. 
 *	This call is equivalent to wall clock time.
 *		  
 *	@par Examples:
 *	@code
 		s = PAPI_get_real_cyc();
 		your_slow_code();
 		e = PAPI_get_real_cyc();
 		printf("Wallclock cycles: %lld\en",e-s);
 *	@endcode	
 *	@see PAPIF  PAPI PAPI_get_virt_usec PAPI_get_virt_cyc PAPI_library_init
 */
long long
PAPI_get_real_cyc( void )
{
	return ( _papi_os_vector.get_real_cycles(  ) );
}

/** @class PAPI_get_real_nsec
 *	@brief Get real time counter value in nanoseconds.
 *
 *	This function returns the total real time passed since some arbitrary 
 *	starting point. 
 *	The time is returned in nanoseconds. 
 *	This call is equivalent to wall clock time.
 *
 *	@see PAPI_get_virt_usec 
 *	@see PAPI_get_virt_cyc 
 *	@see PAPI_library_init
 */

/* FIXME */
long long
PAPI_get_real_nsec( void )
{
  return ( ( _papi_os_vector.get_real_nsec(  )));

}

/**	@class PAPI_get_real_usec
 *	@brief get real time counter value in microseconds 
 *
 *	This function returns the total real time passed since some arbitrary 
 *	starting point. 
 *	The time is returned in microseconds. 
 *	This call is equivalent to wall clock time.
 *	@par Examples:
 *	@code
		s = PAPI_get_real_cyc();
		your_slow_code();
		e = PAPI_get_real_cyc();
		printf("Wallclock cycles: %lld\en",e-s);
 *	@endcode
 *	@see PAPIF
 *	@see PAPI
 *	@see PAPI_get_virt_usec 
 *	@see PAPI_get_virt_cyc 
 *	@see PAPI_library_init
 */
long long
PAPI_get_real_usec( void )
{
	return ( _papi_os_vector.get_real_usec(  ) );
}

/**	@class PAPI_get_virt_cyc 
 *	@brief get virtual time counter value in clock cycles 
 *
 *	@retval PAPI_ECNFLCT 
 *		If there is no master event set. 
 *		This will happen if the library has not been initialized, or 	
 *		for threaded applications, if there has been no thread id 
 *		function defined by the  		PAPI_thread_init function.
 *	@retval PAPI_ENOMEM
 *		For threaded applications, if there has not yet been any thread 
 *		specific master event created for the current thread, and if 
 *		the allocation of such an event set fails, the call will return 
 *		PAPI_ENOMEM or PAPI_ESYS . 
 *
 *	This function returns the total number of virtual units from some 
 *	arbitrary starting point. 
 *	Virtual units accrue every time the process is running in user-mode on 
 *	behalf of the process. 
 *	Like the real time counters, this count is guaranteed to exist on every platform 
 *	PAPI supports. 
 *	However on some platforms, the resolution can be as bad as 1/Hz as defined 
 *	by the operating system.
 *	@par Examples:
 *	@code
 		s = PAPI_get_virt_cyc();
 		your_slow_code();
 		e = PAPI_get_virt_cyc();
 		printf("Process has run for cycles: %lld\en",e-s);
 *	@endcode
 */
long long
PAPI_get_virt_cyc( void )
{

	return ( ( long long ) _papi_os_vector.get_virt_cycles( ) );
}

/** @class PAPI_get_virt_nsec
 *	@brief Get virtual time counter values in nanoseconds.
 *
 *	@retval PAPI_ECNFLCT 
 *		If there is no master event set. 
 *		This will happen if the library has not been initialized, or for threaded 
 *		applications, if there has been no thread id function defined by the 
 *		PAPI_thread_init function.
 *	@retval PAPI_ENOMEM
 *		For threaded applications, if there has not yet been any thread specific
 *		master event created for the current thread, and if the allocation of 
 *		such an event set fails, the call will return PAPI_ENOMEM or PAPI_ESYS . 
 *
 *	This function returns the total number of virtual units from some 
 *	arbitrary starting point. 
 *	Virtual units accrue every time the process is running in user-mode on 
 *	behalf of the process. 
 *	Like the real time counters, this count is guaranteed to exist on every platform 
 *	PAPI supports. 
 *	However on some platforms, the resolution can be as bad as 1/Hz as defined 
 *	by the operating system. 
 *
 */
long long
PAPI_get_virt_nsec( void )
{

  return ( ( _papi_os_vector.get_virt_nsec()));

}

/**	@class PAPI_get_virt_usec
 *	@brief get virtual time counter values in microseconds 
 *
 *	@retval PAPI_ECNFLCT 
 *		If there is no master event set. 
 *		This will happen if the library has not been initialized, or for threaded 
 *		applications, if there has been no thread id function defined by the 
 *		PAPI_thread_init function.
 *	@retval PAPI_ENOMEM
 *		For threaded applications, if there has not yet been any thread 
 *		specific master event created for the current thread, and if the 
 *		allocation of such an event set fails, the call will return PAPI_ENOMEM or PAPI_ESYS . 
 *
 *	This function returns the total number of virtual units from some 
 *	arbitrary starting point. 
 *	Virtual units accrue every time the process is running in user-mode on 
 *	behalf of the process. 
 *	Like the real time counters, this count is guaranteed to exist on every 
 *	platform PAPI supports. However on some platforms, the resolution can be 
 *	as bad as 1/Hz as defined by the operating system.
 *	@par Examples:
 *	@code
 		s = PAPI_get_virt_cyc();
 		your_slow_code();
 		e = PAPI_get_virt_cyc();
 		printf("Process has run for cycles: %lld\en",e-s);
 *	@endcode
 *	@see PAPIF
 *	@see PAPI
 *	@see PAPI
 *	@see PAPI_get_real_cyc
 *	@see PAPI_get_virt_cyc

 */
long long
PAPI_get_virt_usec( void )
{

	return ( ( long long ) _papi_os_vector.get_virt_usec() );
}

/** @class PAPI_lock
 *  @brief Lock one of two mutex variables defined in papi.h.
 *
 *  PAPI_lock() grabs access to one of the two PAPI mutex variables. 
 *  This function is provided to the user to have a platform independent call 
 *  to a (hopefully) efficiently implemented mutex.
 *
 *  @par C Interface:
 *  \#include <papi.h> @n
 *  void PAPI_lock(int lock);
 *
 *  @param[in] lock
 *    -- an integer value specifying one of the two user locks: PAPI_USR1_LOCK or PAPI_USR2_LOCK 
 *
 *  @returns
 *      There is no return value for this call. 
 *      Upon return from  PAPI_lock the current thread has acquired 
 *      exclusive access to the specified PAPI mutex.
 *
 *  @see PAPI_unlock 
 *  @see PAPI_thread_init
 */
int
PAPI_lock( int lck )
{
	if ( ( lck < 0 ) || ( lck >= PAPI_NUM_LOCK ) )
		papi_return( PAPI_EINVAL );

	papi_return( _papi_hwi_lock( lck ) );
}

/** @class PAPI_unlock
 *	@brief Unlock one of the mutex variables defined in papi.h.
 *
 *	@param lck
 *		an integer value specifying one of the two user locks: PAPI_USR1_LOCK 
 *		or PAPI_USR2_LOCK 
 *
 *	PAPI_unlock() unlocks the mutex acquired by a call to PAPI_lock .
 *
 *	@see PAPI_thread_init
 */
int
PAPI_unlock( int lck )
{
	if ( ( lck < 0 ) || ( lck >= PAPI_NUM_LOCK ) )
		papi_return( PAPI_EINVAL );

	papi_return( _papi_hwi_unlock( lck ) );
}

/**	@class PAPI_is_initialized
 *	@brief check for initialization
 *	@retval PAPI_NOT_INITED
 *		Library has not been initialized
 *	@retval PAPI_LOW_LEVEL_INITED
 *		Low level has called library init
 *	@retval PAPI_HIGH_LEVEL_INITED
 *		High level has called library init 
 *	@retval PAPI_THREAD_LEVEL_INITED	
 *		Threads have been inited 
 *	
 *	@param version
		 upon initialization, PAPI checks the argument against the internal value of PAPI_VER_CURRENT when the library was compiled. 
 *	This guards against portability problems when updating the PAPI shared libraries on your system.
 *	@par Examples:
 *	@code
 		int retval;
 		retval = PAPI_library_init(PAPI_VER_CURRENT);
 		if (retval != PAPI_VER_CURRENT && retval > 0) {
 		fprintf(stderr,"PAPI library version mismatch!\en");
 		exit(1); }
 		if (retval < 0)
 		handle_error(retval);
 		retval = PAPI_is_initialized();
 		if (retval != PAPI_LOW_LEVEL_INITED)
 		handle_error(retval);
 *	@endcode
 *	PAPI_is_initialized() returns the status of the PAPI library. 
 *	The PAPI library can be in one of four states, as described under RETURN VALUES. 
 *	@bug	If you don't call this before using any of the low level PAPI calls, your application could core dump.
 *	@see PAPI 
 *	@see PAPI_thread_init
 */
int
PAPI_is_initialized( void )
{
	return ( init_level );
}

/* This function maps the overflow_vector to event indexes in the event
   set, so that user can know which PAPI event overflowed.
   int *array---- an array of event indexes in eventset; the first index
                  maps to the highest set bit in overflow_vector
   int *number--- this is an input/output parameter, user should put the
                  size of the array into this parameter, after the function
                  is executed, the number of indexes in *array is written
                  to this parameter
*/

/**	@class PAPI_get_overflow_event_index
 *	@brief converts an overflow vector into an array of indexes to overflowing events 
 *	@param EventSet
 *		an integer handle to a PAPI event set as created by PAPI_create_eventset
 *	@param overflow_vector
 *		a vector with bits set for each counter that overflowed. 
 *		This vector is passed by the system to the overflow handler routine.
 *	@param *array
 *		an array of indexes for events in EventSet. 
 *		No more than *number indexes will be stored into the array.
 *	@param *number 
 *		On input the variable determines the size of the array. 
 *		On output the variable contains the number of indexes in the array. 
 *
 *	@retval PAPI_EINVAL 
 *		One or more of the arguments is invalid. This could occur if the overflow_vector is empty (zero), if the array or number pointers are NULL, if the value of number is less than one, or if the EventSet is empty.
 *	@retval PAPI_ENOEVST
		The EventSet specified does not exist.
 *	@par Examples
 *	@code
 		void handler(int EventSet, void *address, long_long overflow_vector, void *context){
 		int Events[4], number, i;
 		int total = 0, retval;
 		printf("Overflow #%d\n  Handler(%d) Overflow at %p! vector=%#llx\n",
 		total, EventSet, address, overflow_vector);
 		total++;
 		number = 4;
 		retval = PAPI_get_overflow_event_index(EventSet,
 		overflow_vector, Events, &number);
 		if(retval == PAPI_OK)
 		for(i=0; i<number; i++) printf("Event index[%d] = %d", i, Events[i]);}
 *	@endcode
 *	@bug This function may not return all overflowing events if used with software-driven overflow of multiple derived events.
 *	PAPI_get_overflow_event_index decomposes an overflow_vector into an event 
 *	index array in which the first element corresponds to the least significant set bit in overflow_vector and so on. Based on overflow_vector, the user can only tell which physical counters overflowed. Using this function, the user can map overflowing counters to specific events in the event set. An array is used in this function to support the possibility of multiple simultaneous overflow events.
 *
 *	@see PAPI_overflow
 */
int
PAPI_get_overflow_event_index( int EventSet, long long overflow_vector,
							   int *array, int *number )
{
	APIDBG( "Entry: EventSet: %d, overflow_vector: %lld, array: %p, number: %p\n", EventSet, overflow_vector, array, number);
	EventSetInfo_t *ESI;
	int set_bit, j, pos;
	int count = 0, k;

	if ( overflow_vector == ( long long ) 0 )
		papi_return( PAPI_EINVAL );

	if ( ( array == NULL ) || ( number == NULL ) )
		papi_return( PAPI_EINVAL );

	if ( *number < 1 )
		papi_return( PAPI_EINVAL );

	ESI = _papi_hwi_lookup_EventSet( EventSet );
	if ( ESI == NULL )
		papi_return( PAPI_ENOEVST );

	/* in case the eventset is empty */
	if ( ESI->NumberOfEvents == 0 )
		papi_return( PAPI_EINVAL );

	while ( ( set_bit = ffsll( overflow_vector ) ) ) {
		set_bit -= 1;
		overflow_vector ^= ( long long ) 1 << set_bit;
		for ( j = 0; j < ESI->NumberOfEvents; j++ ) {
			for ( k = 0, pos = 0; k < PAPI_EVENTS_IN_DERIVED_EVENT && pos >= 0; k++ ) {
				pos = ESI->EventInfoArray[j].pos[k];
				if ( ( set_bit == pos ) &&
					 ( ( ESI->EventInfoArray[j].derived == NOT_DERIVED ) ||
					   ( ESI->EventInfoArray[j].derived == DERIVED_CMPD ) ) ) {
					array[count++] = j;
					if ( count == *number )
						return PAPI_OK;

					break;
				}
			}
		}
	}
	*number = count;
	return PAPI_OK;
}


/**	@class PAPI_get_event_component
 *	@brief return component an event belongs to
 *	@retval ENOCMP
 *		component does not exist
 *	
 *	@param EventCode
 *              EventCode for which we want to know the component index
 *	@par Examples:
 *	@code
 		int cidx,eventcode;
 		cidx = PAPI_get_event_component(eventcode);
 *	@endcode
 *	PAPI_get_event_component() returns the component an event
 *      belongs to.
 *	@bug	Doesn't work for preset events
 *	@see  PAPI_get_event_info
 */
int
PAPI_get_event_component( int EventCode)
{
    APIDBG( "Entry: EventCode: %#x\n", EventCode);
    return _papi_hwi_component_index( EventCode);
}

/**	@class PAPI_get_component_index
 *	@brief returns the component index for the named component
 *	@retval ENOCMP
 *		component does not exist
 *
 *	@param name
 *              name of component to find index for
 *	@par Examples:
 *	@code
 		int cidx;
 		cidx = PAPI_get_component_index("cuda");
		if (cidx==PAPI_OK) {
                   printf("The CUDA component is cidx %d\n",cidx);
                }
 *	@endcode
 *	PAPI_get_component_index() returns the component index of
 *      the named component.  This is useful for finding out if
 *      a specified component exists.
 *	@bug	Doesn't work for preset events
 *	@see  PAPI_get_event_component
 */
int  PAPI_get_component_index(const char *name)
{
	APIDBG( "Entry: name: %s\n", name);
  int cidx;

  const PAPI_component_info_t *cinfo;

  for(cidx=0;cidx<papi_num_components;cidx++) {

     cinfo=PAPI_get_component_info(cidx); 
     if (cinfo==NULL) return PAPI_ENOCMP;

     if (!strcmp(name,cinfo->name)) {
        return cidx;
     }
  }

  return PAPI_ENOCMP;
}


/**	@class PAPI_disable_component
 *	@brief disables the specified component
 *	@retval ENOCMP
 *		component does not exist
 *      @retval ENOINIT
 *              cannot disable as PAPI has already been initialized
 *
 *	@param cidx
 *              component index of component to be disabled
 *	@par Examples:
 *	@code
               int cidx, result;

               cidx = PAPI_get_component_index("example");

               if (cidx>=0) {
                  result = PAPI_disable_component(cidx);
                  if (result==PAPI_OK)
                     printf("The example component is disabled\n");
               }
               // ... 
               PAPI_library_init();
 *	@endcode
 *      PAPI_disable_component() allows the user to disable components
 *      before PAPI_library_init() time.  This is useful if the user
 *      knows they do not wish to use events from that component and
 *      want to reduce the PAPI library overhead.
 *    
 *      PAPI_disable_component() must be called before
 *      PAPI_library_init().
 *
 *	@see  PAPI_get_event_component
 *      @see  PAPI_library_init
 */
int
PAPI_disable_component( int cidx )
{
	APIDBG( "Entry: cidx: %d\n", cidx);

   const PAPI_component_info_t *cinfo;

   /* Can only run before PAPI_library_init() is called */
   if (init_level != PAPI_NOT_INITED) {
      return PAPI_ENOINIT;
   }
     
   cinfo=PAPI_get_component_info(cidx); 
   if (cinfo==NULL) return PAPI_ENOCMP;

   ((PAPI_component_info_t *)cinfo)->disabled=1;
   strcpy(((PAPI_component_info_t *)cinfo)->disabled_reason,
	       "Disabled by PAPI_disable_component()");

   return PAPI_OK;
 
}

/** \class PAPI_disable_component_by_name
 *	\brief disables the named component
 *	\retval ENOCMP
 *		component does not exist
 *	\retval ENOINIT
 *		unable to disable the component, the library has already been initialized
 *	\param component_name
 *		name of the component to disable.
 *	\par Example:
 *	\code
	int result;
	result = PAPI_disable_component_by_name("example");
	if (result==PAPI_OK)
		printf("component \"example\" has been disabled\n");
	//...
	PAPI_library_init(PAPI_VER_CURRENT);
 *	\endcode
 *	PAPI_disable_component_by_name() allows the user to disable a component
 *	before PAPI_library_init() time. This is useful if the user knows they do
 *	not with to use events from that component and want to reduce the PAPI
 *	library overhead. 
 *
 *	PAPI_disable_component_by_name() must be called before PAPI_library_init().
 *
 *	\bug none known
 *	\see PAPI_library_init
 *	\see PAPI_disable_component
*/
int
PAPI_disable_component_by_name(const char *name )
{
	APIDBG( "Entry: name: %s\n", name);
	int cidx;

	/* I can only be called before init time */
	if (init_level!=PAPI_NOT_INITED) {
		return PAPI_ENOINIT;
	}

	cidx = PAPI_get_component_index(name);
	if (cidx>=0) {
		return PAPI_disable_component(cidx);
	} 

	return PAPI_ENOCMP;
}