This file is indexed.

/usr/bin/ccconfig is in libconvert-binary-c-perl 0.78-1build2.

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

The actual contents of the file can be viewed below.

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

use IO::File;
use Getopt::Long;
use Data::Dumper;
use strict;

my($NAME) = $0 =~ /([\w\.]+)$/;
my $VERSION = '0.78';
my $MESSAGE = "\nThis is $NAME, v$VERSION ($0).\n";
my %OPT = (
  'output-format' => 'dumper',
);

unless( GetOptions( \%OPT, qw(
          cc|c=s inc-path|I=s@ basename=s
          output-file|o=s output-format|f=s
          preprocess=s compile-obj=s compile-exe=s
          obj-ext=s exe-ext=s c-ext=s pp-ext=s
          version debug quiet status! run! delete!
      ) ) ) {
  # poor man's pod2usage...
  my($USAGE) = do { local(@ARGV,$/)=($0); <> }
               =~ /^__END__.*?^=head\d\s+SYNOPSIS(.*?)^=/ms;
  my %M = ( 'I' => '*' );  # minimal markup
  $USAGE =~ s/([A-Z])<([^>]+)>/$M{$1}$2$M{$1}/g;
  $USAGE =~ s/^/    /gm;
  print STDERR "\nUsage:$USAGE",
               "Try `perldoc $NAME' for more information.\n\n";
  exit 2;
}

if( $OPT{version} ) {
  print <<VERSION;
$MESSAGE
Copyright (c) 2002-2015 Marcus Holland-Moritz. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

VERSION
  exit 0;
}

STDERR->autoflush(1);

$OPT{quiet} or print STDERR $MESSAGE, "\n";

my $output = \*STDOUT;

if (exists $OPT{'output-file'}) {
  $output = new IO::File ">$OPT{'output-file'}"
            or die "Cannot open $OPT{'output-file'}: $!\n";
}

my %format = (
  dumper  => sub {
               my $cfg = shift;
               local $Data::Dumper::Sortkeys = 1;
               return Data::Dumper->Dump([$cfg], ['*config']);
             },
  require => sub {
               my $cfg = shift;
               local $Data::Dumper::Indent = 1;
               local $Data::Dumper::Sortkeys = 1;
               my $dump = Data::Dumper->Dump([$cfg], ['config']);
               $dump =~ s/.*(?={)//;
               return $dump;
             },
);

unless (exists $format{$OPT{'output-format'}}) {
  my $valid = join ', ', sort keys %format;
  die <<EOM;
Invalid output format: '$OPT{'output-format'}'
Valid output formats are: $valid
EOM
}

my $cc  = new Compiler::Config %OPT, ccflags => [@ARGV];
my $cfg = $cc->get_config;
$cc->cleanup;

unless( $OPT{quiet} ) {
  my($wall, $usr, $sys, $cusr, $csys) = (time - $^T, times);
  my $cpu = sprintf "%.2f", $usr + $sys + $cusr + $csys;
  $usr = sprintf "%.2f", $usr + $cusr;
  $sys = sprintf "%.2f", $sys + $csys;
  print STDERR <<END;

Finished in $wall wallclock secs ($usr usr + $sys sys = $cpu CPU)

END
}

print $output $format{$OPT{'output-format'}}->($cfg);

exit 0;


package Compiler::Config;

use IO::File;
use Data::Dumper;
use Text::Wrap;
use Text::ParseWords;
use Carp;
use strict;

use constant SUCCESS     => 0;
use constant ERR_REQUIRE => 1;
use constant ERR_CREATE  => 2;
use constant ERR_CONFIG  => 3;

use constant UNKNOWN     => 0;
use constant GNU_GCC     => 1;
use constant INTEL_ICC   => 2;
use constant MS_VCPP     => 3;
use constant CLANG       => 4;

my %type_map;

BEGIN {
  %type_map = (
    &MS_VCPP => { 'long long' => '__int64' }
  );
};

########################################################################
#
#  CONSTANT / AUTOGENERATED STUFF
#
########################################################################

sub ANSI_headers
{
  qw(
    assert.h  ctype.h  errno.h   float.h   limits.h
    locale.h  math.h   setjmp.h  signal.h  stdarg.h
    stddef.h  stdio.h  stdlib.h  string.h  time.h
  )
}

sub _preset_names
{
  qw(
    __386BSD__ __3dNOW__ __3dNOW_A__ __64BIT__ ____386BSD____ a29k ABI64
    ABIN32 ADDR64 aegis AES_SOURCE AIX AIX32 AIX370 AIX41 AIX42 AIX43 AIX51
    AIX64 AIX_SOURCE aixpc ALL_SOURCE alliant ALMOST_STDC alpha ALPHA_
    Alpha_AXP alpha_bwx alpha_cix alpha_ev4 alpha_ev5 alpha_ev6 alpha_fix
    alpha_max alpha_vxworks ALTIVEC AM29000 am29050 AM29K AM33 AM33_2 AMD64
    amiga AMIGAOS AMIX ansi ANSI_C_SOURCE ANSI_COMPAT AOUT APCS_26 APCS_32
    apollo APOLLO_SOURCE APPLE APPLE_CC APX386 arc arch64 arch_ arch__v3
    arch__v8 ARCH_COM ARCH_PPC ARCH_PPC64 ARCH_PWR ARCH_PWR2 arch_v10
    arch_v3 arch_v32 arch_v8 ARCHITECTURE ardent arm arm2 arm32 arm6
    ARM_ARCH_2 ARM_ARCH_3 ARM_ARCH_3M ARM_ARCH_4 ARM_ARCH_4T ARM_ARCH_5
    ARM_ARCH_5E ARM_ARCH_5T ARM_ARCH_5TE arm_elf arm_oabi ARMEB ARMEL
    ARMWEL atarist athlon athlon_sse att386 att3b AUX AUX_SOURCE AVR
    AVR_ARCH AVR_ASM_ONLY AVR_AT43USB320 AVR_AT43USB355 AVR_AT76C711
    AVR_AT90C8534 AVR_AT90S1200 AVR_AT90S2313 AVR_AT90S2323 AVR_AT90S2333
    AVR_AT90S2343 AVR_AT90S4414 AVR_AT90S4433 AVR_AT90S4434 AVR_AT90S8515
    AVR_AT90S8535 AVR_AT94K AVR_ATmega103 AVR_ATmega128 AVR_ATmega16
    AVR_ATmega161 AVR_ATmega163 AVR_ATmega32 AVR_ATmega323 AVR_ATmega603
    AVR_ATmega64 AVR_ATmega8 AVR_ATmega83 AVR_ATmega85 AVR_ATtiny11
    AVR_ATtiny12 AVR_ATtiny15 AVR_ATtiny22 AVR_ATtiny28 AVR_ENHANCED
    AVR_MEGA base BeOS BIG_ENDIAN BIGMODEL BIT_MSF bool BSD bsd43 bsd4_2
    BSD4_3 bsd4_4 BSD_4_3 BSD_4_4 BSD_C BSD_NET2 BSD_SOURCE BSD_TIME
    BSD_TYPES BSDCOMPAT bsdi BUFSIZ bull BULL_SOURCE BYTE_MSF BYTE_ORDER c
    C30 C31 C32 C33 C3x C40 C44 C4x cadmus CALL_AIX CALL_AIXDESC CALL_NT
    CALL_SYSV cdecl CHAR_UNSIGNED CLASSIFY_TYPE clipper CMU COFF COMPATMATH
    COMPILER_VERSION CONCURRENT CONIX convex convex_c1 convex_c2 convex_c32
    convex_c34 convex_c38 CONVEX_FLOAT_ CONVEX_SOURCE cplusplus CPU
    CPU_FAMILY CPU_VARIANT CRAY CRAYIEEE CRAYMPP CRAYT3E CRIS
    CRIS_ABI_version CRIS_arch_tune CRIS_arch_version ctix CX_UX CYGWIN
    CYGWIN32 D30V DCC DCE_THREADS DCPLUSPLUS declspec DGUX DGUX_SOURCE
    DGUX_TARGET DIAB_TOOL DJGPP dmert DOLPHIN DOUBLE_IS_32BITS DPX2 DSO
    DSP1600 DSP1610 DYNAMIC Dynix DynixPTX EABI ECOFF ELF elinux elxsi
    embedded EMBEDDED_CROSS encore EPI EXTENSIONS EXTERN_PREFIX FAVOR_BSD
    FILE_OFFSET_BITS FILENAME_MAX float128 float80 fpreg fr30 FreeBSD frv
    FRV_ACC FRV_DWORD FRV_FPR FRV_GPR FRV_HARD_FLOAT FRV_UNDERSCORE
    FRV_VLIW G_FLOAT gcc GCC_NEW_VARARGS gcos gcx GFLOAT gimpel GLIBC
    GLIBC_MINOR gmicro GNU GNU_CRIS gnu_hurd GNU_LIBRARY gnu_linux
    GNU_SOURCE GNUC GNUC_MINOR GNUC_PATCHLEVEL GO32 gould GOULD_PN
    GP_SUPPORT H3050R H3050RX H8300 H8300H H8300S hardfp HAVE_68881 HAVE_CE
    HAVE_FPA HAVE_FPU HAVE_SHORT_DOUBLE HAVE_SHORT_INT HAVE_SKY hbullx20
    hcx HITACHI HIUX_SOURCE host_mips hp200 hp300 hp64000 hp64902 hp64903
    HP700 hp800 hp9000 hp9000ipc hp9000s200 hp9000s300 hp9000s400
    hp9000s500 hp9000s700 hp9000s800 hp9k8 HP_aCC hp_osf hppa hpux HPUX_ASM
    HPUX_SOURCE hypersparc i186 i286 i370 i386 i486 i586 i686 i8086 I80960
    i860 i960 i960_CA i960_CC i960_CF i960_KA i960_KB i960_MC i960_SA
    i960_SB i960CA i960CC i960CF i960JA i960JD i960JF i960KA i960KB i960MC
    i960RP i960SA i960SB IA64 iAPX286 IBITS32 ibm ibm032 ibmesa IBMR2 ibmrt
    IEEE_FLOAT IEEE_FLOAT_ IEEE_FP IEEE_FP_INEXACT ILP32 ILP64
    INCLUDE__STDC__ INCLUDE_LONGLONG INLINE INLINE_INTRINSICS INT int128
    INT64 INT_MAX INTEL interdata INTERIX INTRINSICS IP2K is68k itanium
    IWMMXT ix86 k6 k6_2 k6_3 KPRINTF_ATTRIBUTE KR ksr1 LANGUAGE_ASSEMBLY
    LANGUAGE_C LANGUAGE_C_PLUS_PLUS LANGUAGE_OBJECTIVE_C LARGE_FILE_API
    LARGEFILE64_SOURCE LARGEFILE_SOURCE LD64 LDBL LE370 LFS64_LARGEFILE
    LFS_LARGEFILE lint Linux LITTLE_ENDIAN LITTLE_ENDIAN_DATA LONG64
    LONG_DOUBLE LONG_DOUBLE_128 LONG_DOUBLE_64 LONG_LONG LONG_LONG_MAX
    LONG_MAX LONGDOUBLE LONGLONG LP64 luna luna88k Lynx M210 M32R m32r2
    m32rx M340 m68 M68000 m68020 m68030 m68040 m68332 m68k m88000 m88100
    m88110 m88k M88KBCS_TARGET M_ALPHA M_BITFIELDS M_COFF M_I186 M_I286
    M_I386 M_I8086 M_I86 M_I86SM M_INTERNAT M_IX86 M_SDATA M_STEXT M_SYS3
    M_SYS5 M_SYSIII M_SYSV M_UNIX M_WORDSWAP M_XENIX MACH machine MachTen
    macII MASSCOMP MATH_HAS_NO_SIDE_EFFECTS MAVERICK MBCS mc300 mc500
    mc68000 mc68010 mc68020 mc68030 mc68040 mc68060 MC6811 MC6812 mc68302
    mc68332 mc68881 mc68hc11 mc68hc12 mc68hc1x mc68hcs12 mc68k mc68k32
    mc700 mc88000 mc88100 mc88110 mcf5200 MCORE MCORE__ALIGN_4
    MCORE_ALIGN_8 MCOREBE MCORELE mcpu32 merlin mert MINGW32 MiNT mips
    mips16 mips64 mips_eabi mips_fpr MIPS_FPSET MIPS_ISA MIPS_SIM
    mips_single_float mips_soft_float MIPS_SZINT MIPS_SZLONG MIPS_SZPTR
    MIPSEB MIPSEL MMIX MMIX_ABI_GNU MMIX_ABI_MMIXWARE MMX MN10200 MN10300
    MODERN_C moss motorola mpc505 mpc604 mpc750 mpc821 mpc860 mpeix MSC_VER
    MSDOS MSVCRT MT MTXINU MULTIMAX MULTITHREADED mvs n16 NATURAL_ALIGNMENT
    ncl_el ncl_mr NetBSD netware news1500 news1700 news1800 news1900
    news3700 news700 news800 news900 NeXT NEXT_SOURCE NLS NO_INLINE
    NO_INLINE_MATH NO_INLINE_STDLIB NO_INTERRUPTS NO_LEADING_UNDERSCORES
    NO_PROTOTYPE NO_UNDERSCORES NODE nofp nonstopux ns16000 ns32000 ns32016
    ns32332 ns32532 ns32k nsc32000 OCS88 OEMVS OPEN_NAMESPACE OpenBSD
    openedition OPENNT OPTIMIZE OS OS2 OS390 osf OSF1 OSF_SOURCE pa_risc
    PA_RISC1_1 PA_RISC2_0 PARAGON PARISC PC532 pdp11 pe pentium pentium2
    pentium3 pentium4 pentium__mmx pentiumpro PGC pic PIC_ pj plexus PORTAR
    POSIX POSIX1B_SOURCE POSIX2_SOURCE POSIX4_SOURCE POSIX_C_SOURCE
    POSIX_SOURCE POSIX_THREADS POWER PowerPC powerpc64 PPC ppc403 ppc601
    ppc602 ppc603 ppc603e PPC64 PPC64_ PPC_ PRAGMA_REDEFINE_EXTNAME pro
    PROTOTYPES ps2 psos PTHREAD_USE_D4 PTHREADS PTHREADS95 PTRDIFF_TYPE PWB
    pyr QNX R3000 R4000 REENTRANT REGPARM RELOCATABLE RES REVARGV Rhapsody
    rios RISC6000 riscbsd riscix riscos ROSE rs6000 RT rtasim rtems RTP
    s390 s390x s64_t SA110 SCO SCO_C_DIALECT SCO_COFF SCO_DS SCO_ELF
    SCO_ODS_30 SCO_XPG_VERS score3 scs semi sequent SEQUENT_ sgi SGI_SOURCE
    sh sh1 sh2 sh3 SH3E SH4 SH4_100 SH4_200 SH4_300 SH4_340 SH4_400 SH4_500
    SH4_NOFPU SH4_SINGLE SH4_SINGLE_ONLY SH5 SHARED SHMEDIA SHRT_MAX
    simulator sinix SIZE_INT SIZE_LONG SIZE_PTR SIZE_TYPE SNI SOCKET_SOURCE
    SOCKETS_SOURCE SOFT_FLOAT SOFTFP SOLARIS_THREADS sony sony_news
    sonyrisc sparc sparc64 sparc_v8 sparc_v9 sparclet sparclite
    sparclite86x sparcv9 spectrum spur SSE SSE2 stardent STATIC
    STD_INCLUDE_DIR STDC STDC_EXT STDC_HOSTED STDC_VERSION stdcall STDCPP
    stratos STRICT_ANSI STRICT_BSD STRICT_NAMES sun sun3 sun386 Sun386i
    supersparc SVID SVR3 SVR4 SVR4_2 SVR4_ABI SVR4_SOURCE svr5 SX system
    SYSTYPE_BSD SYSTYPE_BSD43 SYSTYPE_BSD44 SYSTYPE_SVR4 SYSTYPE_SVR5
    SYSTYPE_SYSV SYSV SYSV3 SYSV4 SYSV5 sysV68 sysV88 SYSV_SOURCE tahoe
    Tek4132 Tek4300 THREAD_SAFE THREADS_POSIX4ad4 thumb THUMB_INTERWORK
    THUMBEB THUMBEL titan TM3200 TM5400 TM5600 TMS320C30 TMS320C31
    TMS320C32 TMS320C33 TMS320C3x TMS320C40 TMS320C44 TMS320C4x tower
    tower32 tower32_200 tower32_600 tower32_700 tower32_800 tower32_850
    TOWER_ASM tss tune_ tune_athlon tune_athlon_sse tune_i386 tune_i486
    tune_i586 tune_i686 tune_k6 tune_k6_2 tune_k6_3 tune_pentium
    tune_pentium2 tune_pentium3 tune_pentium4 tune_pentium_mmx
    tune_pentiumpro tune_v tune_v10 tune_v3 tune_v8 u370 u3b u3b2 u3b20
    u3b200 u3b20d u3b5 u64_t uclinux UINT128_T ultrix UMAXV unaligned
    UnicomPBB UnicomPBD UNICOS UNICOSMK unix UNIX95 UNIX99 unixpc unos
    USE_BSD USE_FILE_OFFSET64 USE_GNU USE_INIT_FINI USE_ISOC9X
    USE_LARGEFILE USE_LARGEFILE64 USE_MISC USE_POSIX USE_POSIX199309
    USE_POSIX199506 USE_POSIX2 USE_REENTRANT USE_RTC USE_SVID USE_UNIX98
    USE_XOPEN USE_XOPEN_EXTENDED USES_INITFINI USG USGr4 USGr4_2 UTek Utek
    UTS UWIN uxpm uxps v20 v33 v850 v850e v850e1 v850ea v851 vax venix
    VMESA VMS VSTA VTHREADS vxworks vxworks_5 wchar_t WCHAR_TYPE we32000
    WIN32 WINNT WINT_TYPE WRS_R3K_EXC_SUPPORT X86_ x86_64 X_FLOAT xenix
    Xenix286 XOPEN_C XOPEN_SOURCE XOPEN_SOURCE_EXTENDED XPG2 XPG2_EXTENDED
    XPG3 XPG3_EXTENDED XPG4 XPG4_EXTENDED XSCALE xstormy16 XTENSA XTENSA_EB
    XTENSA_EL XTENSA_SOFT_FLOAT z8000
  )
}

sub _assert
{
  {
    'cpu' => [qw(
      a29k alpha arc arm bwx cix clipper convex elxsi ev4 ev5 ev6 fix h8300
      h8300h h8300s hppa i370 i386 i860 i960 ia64 ibm032 m32r m68k m88k max
      mc68000 mc68020 mc68030 mc68040 mips ns32k parisc powerpc powerpc64
      pyr rs6000 sh sparc sparc64 spur tahoe tron v850 vax we32000 x86_64
      xtensa
    )],
    'endian' => [qw(
      big little
    )],
    'lint' => [qw(
      off
    )],
    'machine' => [qw(
      a29k alpha arc arm bigendian clipper convex d30v elxsi fr30 h8300
      h8300h h8300s hppa i370 i386 i860 i960 ia64 ibm032 littleendian m32r
      m68k m88k macII mc68000 mips ns32k parisc powerpc powerpc64 pyr
      rs6000 sgi sh sparc sparc64 sparcv9 spur tahoe tron v850 vax we32000
      x86_64 xstormy16 xtensa
    )],
    'model' => [qw(
      ilp32 lp64
    )],
    'system' => [qw(
      aix AUX beos bsd embedded FreeBSD gnu hiux hpux hurd interix linux
      lynx mach msdos mvs NetBSD netware OpenBSD openedition osf1 posix
      ptx4 rtems simulator svr3 svr4 unix vms vsta vxworks winnt xpg4
    )]
  }
}

########################################################################
#
#  CONSTRUCTOR
#
########################################################################

sub new
{
  my $class = shift;
  my $self = bless {
    'headers'     => [&ANSI_headers],
    'ppline'      => qr/^\s*#\s*(?:line\s*)?(\d+)\s*"([^"]*)"/,   # TODO: make configurable?
    'debug'       => 0,
    'quiet'       => 0,
    'status'      => 1,
    'run'         => 1,
    'delete'      => 1,
    'timeout'     => 30,
    'basename'    => '_t_e_s_t',
    'c-ext'       => '.c',
    @_
  }, $class;

  $self->{fatal} = 0;
  $self->{__int__} = 0;

  $SIG{INT} = sub { $self->{__int__} = 1; $SIG{INT} = 'DEFAULT' };

  $self->_configure;

  $self->{fatal} = 1;

  $self;
}

########################################################################
#
#  CONFIGURATION
#
########################################################################

sub _getwarn
{
  my @warn = @_;

  for( @warn ) {
    s/\s+at\s+\Q$0\E\s+line\s+\d+\.//m;
    s/^\s*included\s+from\s+\[buffer\]:\d+[\r\n]+//m;
    s/[\r\n]+$//;
  };

  @warn;
}

sub check_config
{
  my $self    = shift;
  my $config  = shift;
  my @headers = @_;
  my %inc;

  eval { require Convert::Binary::C };
  $@ and return {code => ERR_REQUIRE};

  $self->{debug} and import Convert::Binary::C debug => 'all';

  my $c = eval { new Convert::Binary::C };
  $@ and return {code => ERR_CREATE};

  eval { $c->configure( %$config ) };
  $@ and return {code => ERR_CONFIG};

  @inc{@headers} = (undef) x @headers;

  my %res = (
    code     => SUCCESS,
    header   => \%inc,
    fail     => [],
    succ     => [],
    warnings => [],
  );

  for my $hdr ( keys %inc ) {
    my $code = "#include <$hdr>\n";
    my @warn;
    {
      local $^W = 1;
      local $SIG{__WARN__} = sub { push @warn, @_ };
      eval { $c->clean->parse( $code ) };
    }
    $inc{$hdr} = { warnings => [_getwarn(@warn)] };
    push @{$res{warnings}}, _getwarn(@warn);
    if( $@ ) {
      ($inc{$hdr}{error}) = _getwarn($@);
      push @{$res{fail}}, $hdr;
    }
    else {
      push @{$res{succ}}, $hdr;
    }
  }

  return \%res;
}

sub get_config
{
  my $self = shift;
  exists $self->{config} or $self->run_checks;

  my @headers;
  my @missing;

  $self->_msg( "\nChecking for ANSI headers..." );

  for my $hdr ( @{$self->{headers}} ) {
    my $found = 0;
    for my $inc ( @{$self->{'inc-path'}} ) {
      if( -e $inc.$hdr ) {
        $found = 1;
        last;
      }
    }
    push @{ $found ? \@headers : \@missing }, $hdr;
  }

  if( @missing ) {
    $self->_msg("The following ANSI headers are missing:");
    $self->_wrapped_list( @missing );
  }
  else {
    $self->_msg("All ANSI headers found.");
  }

  $self->_msg( "\nAssembling the configuration..." );

  my %predef = %{$self->{predefined} || {}};
  my %def;
  my $compiler = $self->_compiler;

  if( $compiler == GNU_GCC || $compiler == CLANG || $compiler == INTEL_ICC ) {
    my %name = (
      GNU_GCC, 'GNU',
      INTEL_ICC, 'Intel ICC',
      CLANG, 'Clang',
    );
    $self->_msg( "You're using the $name{$compiler} compiler." );
    %def = (
      '__attribute(x)'         => '',
      '__attribute__(x)'       => '',
      '__typeof(x)'            => 'int',
      '__typeof__(x)'          => 'int',
      '__alignof(x)'           => '1',
      '__alignof__(x)'         => '1',
      '__label__'              => 'int',
      '__builtin_va_list'      => 'int',
      '__has_feature(x)'       => '0',
      '__has_include_next(x)'  => '0',
    );
  }
  elsif( $compiler == MS_VCPP ) {
    $self->_msg( "You're using the Microsoft compiler." );
    $def{'__int64'} = 'long long';
  }

  if( exists $predef{__CYGWIN__} || exists $predef{_WIN32} ) {
    $self->_msg( "This is a Windows compiler." );
    $def{'__cdecl'} = '';
    $def{'__declspec(x)'} = '';
  }

  my %cfg;
  my $define = sub { [ map { "$_=$predef{$_}" } sort keys %{$_[0]} ] };

  if( exists $self->{basic_sizes} ) {
    my %sizes = %{$self->{basic_sizes}};
    my %valid = (
                  PointerSize    => [    0, 1, 2, 4, 8        ],
                  EnumSize       => [-1, 0, 1, 2, 4, 8        ],
                  IntSize        => [    0, 1, 2, 4, 8        ],
                  CharSize       => [    0, 1, 2, 4, 8        ],
                  ShortSize      => [    0, 1, 2, 4, 8        ],
                  LongSize       => [    0, 1, 2, 4, 8        ],
                  LongLongSize   => [    0, 1, 2, 4, 8        ],
                  FloatSize      => [    0, 1, 2, 4, 8, 12, 16],
                  DoubleSize     => [    0, 1, 2, 4, 8, 12, 16],
                  LongDoubleSize => [    0, 1, 2, 4, 8, 12, 16],
                );

    for my $type ( keys %sizes ) {
      my $opt = join( '', map ucfirst, split ' ', $type ) . 'Size';
      if( exists $valid{$opt} ) {
        if( grep { $sizes{$type} == $_ } @{$valid{$opt}} ) {
          $cfg{$opt} = $sizes{$type};
        }
        else {
          $self->_msg( "Strange size '$sizes{$type}' for type '$type'." );
        }
      }
      else {
        $self->_msg( "Strange type '$type' with size '$sizes{$type}'." );
      }
    }
  }

  if( exists $self->{unsigned_chars} and defined $self->{unsigned_chars} ) {
    $cfg{UnsignedChars} = $self->{unsigned_chars};
  }
  if( exists $self->{alignment} and defined $self->{alignment} ) {
    if( grep { $self->{alignment} == $_ } 1, 2, 4, 8, 16 ) {
      $cfg{Alignment} = $self->{alignment};
    }
    else {
      $self->_msg( "Strange alignment '$self->{alignment}'." );
    }
  }
  if( exists $self->{compound_alignment} and defined $self->{compound_alignment} ) {
    if( grep { $self->{compound_alignment} == $_ } 1, 2, 4, 8, 16 ) {
      $cfg{CompoundAlignment} = $self->{compound_alignment};
    }
    else {
      $self->_msg( "Strange compound alignment '$self->{compound_alignment}'." );
    }
  }
  if( exists $self->{invalid_keywords} and @{$self->{invalid_keywords}} > 0 ) {
    $cfg{DisabledKeywords} = $self->{invalid_keywords};
  }
  if( exists $self->{keyword_map} and keys %{$self->{keyword_map}} > 0 ) {
    $cfg{KeywordMap} = $self->{keyword_map};
  }
  if( exists $self->{byteorder} and $self->{byteorder} ) {
    $cfg{ByteOrder} = $self->{byteorder};
  }
  if( exists $self->{cpp_comments} ) {
    $cfg{HasCPPComments} = $self->{cpp_comments};
  }
  if( exists $self->{stdc_version} ) {
    $cfg{StdCVersion} = $self->{stdc_version};
  }
  if( exists $self->{stdc_hosted} ) {
    $cfg{HostedC} = $self->{stdc_hosted};
  }
  if( exists $self->{'inc-path'} and @{$self->{'inc-path'}} > 0 ) {
    $cfg{Include} = [ map { s/[\\\/]+$//; $_ } @{$self->{'inc-path'}} ];
  }

  keys %{$self->{preasserted}} and $cfg{Assert} = [sort keys %{$self->{preasserted}}];

  unless (keys %cfg) {
    $self->_msg("\nI could not get any useful compiler information.");
    $self->_quit;
  }

  $self->_msg( "\nTesting configuration..." );

  $self->_debug(sub { Data::Dumper->Dump( [\%def, \%predef, \%cfg], [qw(*def *predef *cfg)] ) });

  # First, check if the configuration works without additional defines

  my $warnings = 0;
  my $failures = 0;
  keys %predef and $cfg{Define} = $define->( \%predef );

  my $res = $self->check_config( \%cfg, @headers );
  $self->_debug(sub { Data::Dumper->Dump( [$res], [qw(res)] ) });

  if( $res->{code} == SUCCESS ) {
    $failures = @{$res->{fail}};
    $warnings = @{$res->{warnings}};
    if( $failures ) {
      $self->_msg( "Plain configuration failed for these headers:" );
      $self->_wrapped_list( sort @{$res->{fail}} );
    }
    else {
      if( $warnings == 0 ) {
        goto finish;
      }
      $self->_msg( "Plain configuration works fine, but there are some warnings:" );
      $self->_out( "| ", @{$res->{warnings}} );
    }
  }
  else {
    goto finish;
  }

  # There were errors or warnings. Let's see if there's something we can try...

  unless( keys %def ) {
    if( $res->{code} == SUCCESS ) {
      $self->_msg( "\nHowever, there's nothing I can do about it." );
    }
    goto finish;
  }

  $self->_msg( "\nI will try to add couple of defines..." );

  for my $key ( keys %def ) {
    my($name) = $key =~ /(\w+)/;
    delete $predef{$name};
    $predef{$key} = $def{$key};
  }

  keys %predef and $cfg{Define} = $define->( \%predef );

  my $newres = $self->check_config( \%cfg, @headers );
  $self->_debug(sub { Data::Dumper->Dump( [$res], [qw(res)] ) });

  if( $res->{code} != SUCCESS ) {
    $res = $newres;
    goto finish;
  }

  if( @{$newres->{fail}} < $failures  or
      @{$newres->{fail}} == $failures && @{$newres->{warnings}} < $warnings ) {
    $self->_msg( "This configuration feels better." );
    if( $failures ) {
      if( @{$newres->{fail}} ) {
        $self->_msg( "Only these headers still fail:" );
        $self->_wrapped_list( sort @{$newres->{fail}} );
      }
      else {
        $self->_msg( "No more headers that fail." );
      }
    }
    $res = $newres;
    $failures = @{$res->{fail}};
    $warnings = @{$res->{warnings}};
  }
  else {
    if( $failures == 0 and @{$newres->{fail}} > 0 ) {
      $self->_msg( "Whoa, now it fails. Restoring original configuration." );
    }
    else {
      $self->_msg( "Doesn't help. Restoring original configuration." );
    }
    goto finish;
  }

  # Try to remove as many defines as possible

  $self->_msg( "\nNow let's see which defines aren't necessary..." );

  my %orgdef = %{$self->{predefined}};
  my @additional;
  my $tested = 0;

  for my $key ( sort keys %def ) {
    my($name) = $key =~ /(\w+)/;
    delete $predef{$key};
    exists $orgdef{$name} and $predef{$name} = $orgdef{$name};

    keys %predef and $cfg{Define} = $define->( \%predef );

    $newres = $self->check_config( \%cfg, @headers );
    $self->_debug(sub { Data::Dumper->Dump( [$res], [qw(res)] ) });

    if( $newres->{code} == SUCCESS and @{$newres->{fail}} <= $failures
                                   and @{$newres->{warnings}} <= $warnings ) {
      $res = $newres;
      $failures = @{$res->{fail}};
      $warnings = @{$res->{warnings}};
    }
    else {
      push @additional, $name;
      delete $predef{$name};
      $predef{$key} = $def{$key};
    }

    $self->_work_in_progress( sprintf "%d/%d needed", scalar @additional, ++$tested );
  }

  $self->_work_done;

  if( @additional ) {
    $self->_msg( "Additionally defining the following symbols:" );
    $self->_wrapped_list( sort @additional );
  }
  else {
    $self->_msg( "Not defining any additional symbols." );
  }

finish:
  if( $res->{code} == SUCCESS ) {
    if( @{$res->{succ}} > 0 ) {
      $self->_msg( "\n>>>>>>>>>> Successfully tested configuration! <<<<<<<<<<" );
    }
    else {
      $self->_msg( "\n>>>>>>>>>> Configuration test FAILED! <<<<<<<<<<" );
    }

    if( @{$res->{fail}} ) {
      $self->_msg( "\nThese headers fail:" );
      for my $hdr ( sort keys %{$res->{header}} ) {
        exists $res->{header}{$hdr}{error} or next;
        $self->_msg( "  <$hdr> $res->{header}{$hdr}{error}" );
      }
    }
    elsif( @{$res->{warnings}} ) {
      $self->_msg( "\nHowever, there are some warnings that I can't get rid of:" );
      $self->_out( "| ", @{$res->{warnings}} );
    }

    if( defined $self->{float_format} ) {
      if( $self->{float_format} eq 'IEEE' ) {
        Convert::Binary::C::feature('ieeefp') or $self->_msg( <<ENDMSG );

ATTENTION: The floating point format used by the tested compiler
           appears to be IEEE, but Convert::Binary::C was built
           without the 'ieeefp' feature. Don't try to handle
           any floating point values in this configuration.
ENDMSG
      }
      elsif( $self->{float_format} eq 'native' ) {
        Convert::Binary::C::feature('ieeefp') and $self->_msg( <<ENDMSG );

ATTENTION: The tested compiler does not seem to use IEEE floating
           point format. Instead, the format I found was compatible
           with the floating point format used natively by your
           machine. For some reason, Convert::Binary::C was built
           with the 'ieeefp' feature, which is not very clever if
           my tests were correct. However, don't try to handle any
           floating point values in this configuration.
ENDMSG
      }
      else {
        $self->_msg( <<ENDMSG );

ATTENTION: The tested compiler does not seem to use IEEE floating
           point format, nor does it seem to use a format compatible
           with the floating point format used natively by your
           machine. Don't try to handle any floating point values
           with Convert::Binary::C in this configuration.
ENDMSG
      }
    }
  }
  else {
    $res->{code} == ERR_REQUIRE and
      $self->_msg( "Failed to load Convert::Binary::C, cannot test configuration." );
    $res->{code} == ERR_CREATE and
      $self->_msg( "Could not create Convert::Binary::C object." );
    $res->{code} == ERR_CONFIG and
      $self->_msg( "Could not configure Convert::Binary::C object." );
  }

  keys %predef and $cfg{Define} = $define->( \%predef );

  return \%cfg;
}

########################################################################
#
#  COMPILER TESTING
#
########################################################################

sub cleanup
{
  my $self = shift;
  if( $self->{'delete'} ) {
    for( qw( c pp obj exe ) ) {
      my $meth = "_${_}file";
      my $file = $self->$meth();
      -e $file and unlink $file;
    }
    for( glob "$self->{basename}.*" ) { -e and unlink }
  }
}

sub run_checks
{
  my $self = shift;
  my $asserts;

  if ($self->{'inc-path'}) {
    for (@{$self->{'inc-path'}}) {
      $_ .= _OS('file-sep') unless /[:\/\\]$/
    }
  }
  elsif ($self->{can_read_ppout}) {
    $self->{'inc-path'} = $self->_run_incpath;
  }
  else {
    $self->{'inc-path'} = [];
  }

  ($self->{names}, $asserts)  = $self->_names( $self->{'inc-path'} );

  if ($self->{can_preprocess}) {
    $self->{predefined}         = $self->_get_predefined( $self->{names} );
    $self->{preasserted}        = $self->_get_preasserted( $asserts );
    $self->{stdc_version}       = delete $self->{predefined}{__STDC_VERSION__};
    $self->{stdc_hosted}        = delete $self->{predefined}{__STDC_HOSTED__};

    $self->{stdc_version} =~ s/L$// if defined $self->{stdc_version};
  }

  if ($self->{can_compile} || $self->{can_run}) {
    $self->{invalid_keywords}   = $self->_get_invalid_keywords;
    $self->{keyword_map}        = $self->_get_keyword_map;
    $self->{cpp_comments}       = $self->_get_cpp_comments;

    $self->{basic_sizes}        = $self->_get_basic_sizes;
    $self->{byteorder}          = $self->_get_byteorder;
    $self->{unsigned_chars}     = $self->_get_unsigned_chars;
    $self->{alignment}          = $self->_get_alignment;
    $self->{compound_alignment} = $self->_get_compound_alignment;

    # run _after_ byteorder test
    $self->{float_format}       = $self->_get_float_format;
  }
}

sub _compiler
{
  my $self = shift;

  exists $self->{predefined}{__clang__}        and return CLANG;

  exists $self->{predefined}{__GNUC__}         and return GNU_GCC;

  exists $self->{predefined}{__ICC} ||
  exists $self->{predefined}{__INTEL_COMPILER} and return INTEL_ICC;

  exists $self->{predefined}{_MSC_VER}         and return MS_VCPP;

  return UNKNOWN;
}

sub _test_type
{
  my($self, $type, $init, $width) = @_;

  my $begin = "\x21\x05\x19\x77*MHXCBC*\xDE\xAD\xBE\xEF";
  my $end   = "\x21\x05\x19\x77*MARCUS*\xDE\xAD\xBE\xEF";

  my $cvt = sub { join ', ', map { sprintf "0x%02X", $_ } unpack "C*", $_[0] };

  my $c_begin = $cvt->( $begin );
  my $c_end   = $cvt->( $end );

  $self->_temp( <<ENDC );
struct _t_e_s_t_ {
  unsigned char _a_[16];
  $type _x_;
  unsigned char _z_[16];
} _g_x = {
  { $c_begin },
  $init,
  { $c_end }
};
ENDC

  my $res = $self->_compile_temp;
  $res->{status} and return undef;

  my $fh = new IO::File $self->_objfile or return undef;
  binmode $fh;

  my $obj = do { local $/; <$fh> };

  $obj =~ /\Q$begin\E(.{1,$width}?)\Q$end\E/s and return $1;

  return undef;
}

#-----------------------------------------------------------------------
#  FLOATING POINT FORMAT
#-----------------------------------------------------------------------

sub _get_float_format_run
{
  my $self = shift;
  my $value = shift;
  my %res;

  TYPE: for my $type ( qw( float double ) ) {
    $self->_work_in_progress;

    $self->_temp( <<ENDC );
#include <stdio.h>
union fp {
  $type val;
  unsigned char byte[sizeof($type)];
};
int main()
{
  union fp x;
  int i;
  x.val = $value;
  printf("size=%d:", sizeof($type));
  for( i=0; i<sizeof($type); ++i )
    printf(" 0x%02X", (unsigned int) x.byte[i]);
  printf("\\n");
  return 0;
}
ENDC

    my $res = $self->_build_temp;

    if( -e $self->_exefile ) {
      local $self->{fatal} = 0;
      $res = $self->_run_temp;
    }
    else {
      $self->_msg( "Got no output from compiler for '($type) $value'." );
      next;
    }

    if( $res->{didnotrun} or $res->{status} ) {
      $self->_msg( "It seems I cannot run your compiler's executables." );
      last;
    }

    for my $line ( @{$res->{stdout}} ) {
      if( my($size, $hex) = $line =~ /^size=(\d+):\s*(.*)/ ) {
        my $bits = pack 'C*', map hex, $hex =~ /0x(\S{2})/g;
        length($bits) == $size or last;
        $res{$type} = $bits;
        next TYPE;
      }
    }

    $self->_msg( "Strange output for '($type) $value'" );
  }

  return \%res;
}

sub _get_float_format_compile
{
  my $self = shift;
  my $value = shift;
  my %res;

  for my $type ( qw( float double ) ) {
    $self->_work_in_progress;

    $res{$type} = $self->_test_type( $type, $value, 32 );

    unless( defined $res{$type} ) {
      $self->_msg( "Got no output from compiler for '($type) $value'." );
    }
  }

  return \%res;
}

sub _get_float_format
{
  my $self = shift;

  $self->_msg( "\nTrying to determine floating point format..." );

  my @test = (
    {
      value  => '-1.0',
      double => pack( 'C*', 0xBF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ),
      single => pack( 'C*', 0xBF, 0x80, 0x00, 0x00 ),
    },
    {
      value  => '0.0',
      double => pack( 'C*', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ),
      single => pack( 'C*', 0x00, 0x00, 0x00, 0x00 ),
    },
    {
      value  => '0.4',
      double => pack( 'C*', 0x3F, 0xD9, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9A ),
      single => pack( 'C*', 0x3E, 0xCC, 0xCC, 0xCD ),
    },
    {
      value  => '1.0',
      double => pack( 'C*', 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ),
      single => pack( 'C*', 0x3F, 0x80, 0x00, 0x00 ),
    },
    {
      value  => '3.1415926535',
      double => pack( 'C*', 0x40, 0x09, 0x21, 0xFB, 0x54, 0x41, 0x17, 0x44 ),
      single => pack( 'C*', 0x40, 0x49, 0x0F, 0xDB ),
    },
    {
      value  => '1.220703125e-4',
      double => pack( 'C*', 0x3F, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ),
      single => pack( 'C*', 0x39, 0x00, 0x00, 0x00 ),
    },
  );

  my $meth = $self->{can_run} ? "_get_float_format_run" : "_get_float_format_compile";

  for my $t ( @test ) {
    my $res = $self->$meth( $t->{value} );
    $t->{result}{single} = $res->{float};
    $t->{result}{double} = $res->{double};
  }

  my $fail_nat = 0;
  my $fail_i3e = 0;
  my @tests;

  for my $t ( @test ) {
    my $s_nat = pack 'f', $t->{value};
    my $d_nat = pack 'd', $t->{value};
    my $s_i3e = $t->{single};
    my $d_i3e = $t->{double};

    if( defined $self->{byteorder} && $self->{byteorder} eq 'LittleEndian' ) {
      $_ = reverse $_ for $s_i3e, $d_i3e;
    }

    if( defined $t->{result}{single} ) {
      push @tests, { value => $t->{value}, format => 'single', ieee => $s_i3e,
                     native => $s_nat, got => $t->{result}{single} };
      $t->{result}{single} eq $s_nat or $fail_nat++;
      $t->{result}{single} eq $s_i3e or $fail_i3e++;
    }
    if( defined $t->{result}{double} ) {
      push @tests, { value => $t->{value}, format => 'double', ieee => $d_i3e,
                     native => $d_nat, got => $t->{result}{double} };
      $t->{result}{double} eq $d_nat or $fail_nat++;
      $t->{result}{double} eq $d_i3e or $fail_i3e++;
    }
  }

  $self->_work_done;

  my $fp_format;

  if( @tests == 0 ) {
    $self->_msg( "Could not determine floating point format." );
  }
  elsif( $fail_i3e == 0 ) {
    $fp_format = 'IEEE';
    $self->_msg( "Seems to be IEEE floating point format." );
  }
  elsif( $fail_nat == 0 ) {
    $fp_format = 'native';
    $self->_msg( "No IEEE, but at least the natively supported floating point format." );
  }
  else {
    $fp_format = 'unknown';
    $self->_msg( "Neither IEEE nor natively supported floating point format." );
    $self->_msg( "\nFYI, this is what I got:" );
    $self->_msg( "\nvalue           format  IEEE representation      Native representation    Compiler representation" );
    $self->_msg( '-'x97 );
    my $hex = sub { join ' ', map { sprintf "%02X", $_ } unpack "C*", $_[0] };
    for my $t ( @tests ) {
      $self->_msg( sprintf( "%-15s %-7s %-24s %-24s %-24s", $t->{value}, $t->{format},
                            $hex->($t->{ieee}), $hex->($t->{native}), $hex->($t->{got}) ) );
    }
    $self->_msg( '-'x97 );
  }

  return $fp_format;
}

#-----------------------------------------------------------------------
#  ALIGNMENT
#-----------------------------------------------------------------------

sub _get_alignment_run
{
  my $self = shift;
  my $type = shift;

  $self->_work_in_progress;

  $self->_temp( <<ENDC );
#include <stdio.h>
#include <stddef.h>
struct align {
  char a;
  $type b;
};
int main()
{
  printf("align=%d\\n", offsetof(struct align, b));
  return 0;
}
ENDC

  my $res = $self->_build_temp;

  if( -e $self->_exefile ) {
    local $self->{fatal} = 0;
    $res = $self->_run_temp;
  }
  else {
    $self->_work_done;
    $self->_msg( "Got no output from compiler for '$type'." );
    return undef;
  }

  if( $res->{didnotrun} or $res->{status} ) {
    $self->_work_done;
    $self->_msg( "It seems I cannot run your compiler's executables." );
    return undef;
  }

  for my $line ( @{$res->{stdout}} ) {
    $line =~ /^align=(\d+)/ and return $1;
  }

  $self->_work_done;
  $self->_msg( "Strange output..." );
  return undef;
}

sub _get_alignment_compile
{
  my $self = shift;
  my $type = shift;

  $self->_work_in_progress;

  my $init = $type =~ /(struct|union)\s+(\w+)/
                      ? "{ sizeof(struct align) - sizeof($1 $2) }"
                      : "{ sizeof(struct align) - sizeof($type), ($type) -1 }";

  my $res = $self->_test_type( "struct align { char a; $type b; }", $init, 32 );

  unless( defined $res ) {
    $self->_work_done;
    $self->_msg( "Got no output from compiler for '$type'." );
    return undef;
  }

  my $off = unpack "C", $res;

  if( $off == 0 ) {
    $self->_work_done;
    $self->_msg( "Strange output..." );
    return undef;
  }

  return $off;
}

sub _get_alignment
{
  my $self = shift;

  $self->_msg( "\nTrying to determine struct member alignment..." );

  my $meth = $self->{can_run} ? "_get_alignment_run" : "_get_alignment_compile";
  my $align;

  my $compiler = $self->_compiler;

  for my $type ( 'int', 'short', 'long', 'long long', 'float', 'double', 'int *' ) {
    my $real_type = $type_map{$compiler}{$type} || $type;
    if( defined( my $rv = $self->$meth( $real_type ) ) ) {
      !defined($align) || $rv > $align and $align = $rv;
    }
  }

  $self->_work_done;

  if( defined $align ) {
    $self->_msg( "Struct members are aligned to $align-byte boundaries." );
  }
  else {
    $self->_msg( "Could not determine struct member alignment." );
  }

  return $align;
}

sub _get_compound_alignment
{
  my $self = shift;

  $self->_msg( "\nTrying to determine compound alignment..." );

  my $meth = $self->{can_run} ? "_get_alignment_run" : "_get_alignment_compile";
  my $s_align = $self->$meth("struct testit { char a; }");
  my $u_align = $self->$meth("union testit { char a; }");

  $self->_work_done;

  if( defined($s_align) && defined($u_align) && $s_align == $u_align ) {
    $self->_msg( "Compounds are aligned to $s_align-byte boundaries." );
    return $s_align;
  }
  else {
    $self->_msg( "Could not determine compound alignment." );
    return undef;
  }
}

#-----------------------------------------------------------------------
#  BASIC TYPE SIZES
#-----------------------------------------------------------------------

sub _get_basic_sizes_run
{
  my $self = shift;
  my $type = shift;

  $self->_work_in_progress;

  $self->_temp( <<ENDC );
#include <stdio.h>
typedef $type _t_y_p_e_;
int main()
{
  printf("sizeof=%d\\n", sizeof(_t_y_p_e_));
  return 0;
}
ENDC

  my $res = $self->_build_temp;

  if( -e $self->_exefile ) {
    local $self->{fatal} = 0;
    $res = $self->_run_temp;
  }
  else {
    $self->_work_done;
    $self->_msg( "Got no output from compiler for '$type'." );
    return undef;
  }

  if( $res->{didnotrun} or $res->{status} ) {
    $self->_work_done;
    $self->_msg( "It seems I cannot run your compiler's executables." );
    return undef;
  }

  for my $line ( @{$res->{stdout}} ) {
    $line =~ /^sizeof=(\d+)/ and return $1;
  }

  $self->_work_done;
  $self->_msg( "Strange output..." );
  return undef;
}

sub _get_basic_sizes_compile
{
  my $self = shift;
  my $type = shift;

  $self->_work_in_progress;

  my $res = $self->_test_type( $type, "0", 16 );

  unless( defined $res ) {
    $self->_work_done;
    $self->_msg( "Got no output from compiler for '$type'." );
    return undef;
  }

  return length $res;
}

sub _get_basic_sizes
{
  my $self = shift;

  $self->_msg( "\nTrying to determine basic type sizes..." );

  my $meth = $self->{can_run} ? "_get_basic_sizes_run" : "_get_basic_sizes_compile";

  my %sizes;
  my $compiler = $self->_compiler;

  for my $type ( 'int', 'char', 'short', 'long', 'long long', 'float', 'double', 'long double', 'int *' ) {
    my $real_type = $type_map{$compiler}{$type} || $type;
    my $rv = $self->$meth( $real_type ) or next;
    $sizes{$type =~ y/*// ? 'pointer' : $type} = $rv;
  }

  my %enum;

  for my $type (
                 "enum pbyte { PB1 =      0, PB2 =   255 }",
                 "enum nbyte { NB1 =   -128, NB2 =   127 }",
                 "enum pword { PW1 =      0, PW2 = 65535 }",
                 "enum nword { NW1 = -32768, NW2 = 32767 }",
                 "enum plong { PL1 =      0, PL2 = 65536 }",
                 "enum nlong { NL1 = -32768, NL2 = 32768 }",
               ) {
    my $rv = $self->$meth( $type ) or next;
    my($name) = $type =~ /^enum\s+(\w+)/;
    $enum{$name} = $rv;
  }

  $self->_work_done;

  if( keys %enum == 6 ) {
    if( $enum{pbyte} == 2 && $enum{nbyte} == 1 &&
        $enum{pword} == 4 && $enum{nword} == 2 &&
        $enum{plong} == 4 && $enum{nlong} == 4 ) {
      $sizes{enum} = -1;
    }
    elsif( $enum{pbyte} == 1 && $enum{nbyte} == 1 &&
           $enum{pword} == 2 && $enum{nword} == 2 &&
           $enum{plong} == 4 && $enum{nlong} == 4 ) {
      $sizes{enum} = 0;
    }
    elsif( $enum{pbyte} == $enum{nbyte} &&
           $enum{pbyte} == $enum{pword} &&
           $enum{pbyte} == $enum{nword} &&
           $enum{pbyte} == $enum{plong} &&
           $enum{pbyte} == $enum{nlong} ) {
      $sizes{enum} = $enum{pbyte};
    }
    else {
      $self->_msg( "Hmm, your compiler has strange enums." );
    }
  }

  $self->_msg( "Got size information for the following types:" );
  $self->_wrapped_list( sort @{[map {y/ /_/; $_} keys %sizes]} );

  $self->_debug(sub { Data::Dumper->Dump( [\%sizes], ['*sizes'] ) });

  \%sizes;
}

#-----------------------------------------------------------------------
#  UNSIGNED CHARACTERS
#-----------------------------------------------------------------------

sub _get_unsigned_chars_run
{
  my $self = shift;

  $self->_temp( <<ENDC );
#include <stdio.h>
int main()
{
  char c;
  int  i;
  c = -1;
  i = c;
  printf("result=%d\\n", i);
}
ENDC

  my $res = $self->_build_temp;

  if( $res->{status} == 0 and -e $self->_exefile ) {
    {
      local $self->{fatal} = 0;
      $res = $self->_run_temp;
    }

    if( $res->{didnotrun} ) {
      $self->_msg( "It seems I cannot run your compiler executables." );
      return undef;
    }

    for my $line ( @{$res->{stdout}} ) {
      $line =~ /^result=(-?\d+)/ and return $1;
    }
  }
  else {
    $self->_msg( "Could not build the test program." );
    $self->_out( '| ', @{$res->{stderr}} );
  }

  return undef;
}

sub _get_unsigned_chars_compile
{
  my $self = shift;

  my $res = $self->_test_type( "int", "(int)((char)-1)", 8 );

  if( defined $res ) {
    $res =~ /^\xFF+$/        and return -1;
    $res =~ /^\x00+\xFF$/ ||
    $res =~ /^\xFF\x00+$/    and return 255;
  }

  $self->_msg( "Could not determine character signedness." );
  return undef;
}

sub _get_unsigned_chars
{
  my $self = shift;

  $self->_msg( "\nTrying to find out if your chars are unsigned..." );

  my $meth = $self->{can_run} ? "_get_unsigned_chars_run" : "_get_unsigned_chars_compile";

  my $result = $self->$meth();

  if( defined $result ) {
    if( $result == -1 ) {
      $self->_msg( "Your chars are signed." );
      return 0;
    }
    elsif( $result == 255 ) {
      $self->_msg( "Your chars are unsigned." );
      return 1;
    }
    elsif( $result >= 0 ) {
      $self->_msg( "Your chars seem to be unsigned." );
      return 1;
    }
    else {
      $self->_msg( "Your chars seem to be signed." );
      return 0;
    }
  }

  $self->_msg( "No idea." );
  return undef;
}

#-----------------------------------------------------------------------
#  BYTEORDER
#-----------------------------------------------------------------------

sub _get_byteorder_run
{
  my $self = shift;

  $self->_temp( <<ENDC );
#include <stdio.h>
typedef unsigned long UVAL;
typedef union {
  UVAL multi;
  char byte[sizeof(UVAL)];
} order;
int main()
{
  order test;
  int i;
  if( sizeof(UVAL) > 4 )
    test.multi = (((UVAL)0x08070605) << 32) | ((UVAL)0x04030201);
  else
    test.multi = (UVAL)0x04030201;
  printf("order=");
  for( i=0; i<sizeof(long); ++i )
    printf("\%c", '0'+test.byte[i]);
  printf("\\n");
  return 0;
}
ENDC

  my $res = $self->_build_temp;

  if( $res->{status} == 0 and -e $self->_exefile ) {
    {
      local $self->{fatal} = 0;
      $res = $self->_run_temp;
    }

    if( $res->{didnotrun} ) {
      $self->_msg( "It seems I cannot run your compiler executables." );
      return '';
    }

    my $order;

    for my $line ( @{$res->{stdout}} ) {
      $line =~ /^order=(\d+)/ and $order = $1;
    }

    if( defined $order ) {
      my %bo = (
        '87654321' => 'BigEndian',
        '4321'     => 'BigEndian',
        '21'       => 'BigEndian',
        '12345678' => 'LittleEndian',
        '1234'     => 'LittleEndian',
        '12'       => 'LittleEndian',
      );
      if( exists $bo{$order} ) {
        $self->_msg( "The byte order appears to be $bo{$order}." );
        return $bo{$order};
      }
      $self->_msg( "Your compiler seems to have a strange byte order ($order)." );
    }
    else {
      $self->_msg( "The test program delivered some strange output." );
      $self->_out( '| ', @{$res->{stdout}} );
    }
  }
  else {
    $self->_msg( "Could not build the test program." );
    $self->_out( '| ', @{$res->{stderr}} );
  }

  return '';
}

sub _get_byteorder_compile
{
  my $self = shift;

  my $res = $self->_test_type( "unsigned long", <<ENDINIT, 8 );
  sizeof(unsigned long) > 4
    ? (((unsigned long)0x08070605) << 32) | ((unsigned long)0x04030201)
    : (unsigned long)0x04030201
ENDINIT

  unless( defined $res ) {
    $self->_msg( "Could not determine byte order." );
    return '';
  }

  my %bo = (
    "\x08\x07\x06\x05\x04\x03\x02\x01" => 'BigEndian',
    "\x04\x03\x02\x01"                 => 'BigEndian',
    "\x02\x01"                         => 'BigEndian',
    "\x01\x02\x03\x04\x05\x06\x07\x08" => 'LittleEndian',
    "\x01\x02\x03\x04"                 => 'LittleEndian',
    "\x01\x02"                         => 'LittleEndian',
  );

  if( exists $bo{$res} ) {
    $self->_msg( "The byte order appears to be $bo{$res}." );
    return $bo{$res};
  }

  my $str = join '', map { sprintf "%02X", $_ } unpack "C*", $res;
  $self->_msg( "Your compiler seems to have a strange byte order (0x$str)." );

  return '';
}

sub _get_byteorder
{
  my $self = shift;

  $self->_msg( "\nTrying to determine byte order..." );

  my $meth = $self->{can_run} ? "_get_byteorder_run" : "_get_byteorder_compile";

  return $self->$meth();
}

#-----------------------------------------------------------------------
#  C++ COMMENTS
#-----------------------------------------------------------------------

sub _get_cpp_comments
{
  my $self = shift;

  $self->_msg( "\nTrying to find out if your compiler understands C++ comments..." );

  $self->_temp( <<ENDC );
extern int // nothing here
       i;
int main(void) { return 0; }  /* keep _build happy */
ENDC

  my $res = $self->_compile_or_build_temp;

  if( $res->{status} ) {
    $self->_msg( "No, it doesn't." );
    return 0;
  }
  else {
    $self->_msg( "Yes, it does." );
    return 1;
  }
}

#-----------------------------------------------------------------------
#  KEYWORD MAP
#-----------------------------------------------------------------------

sub _get_keyword_map
{
  my $self = shift;

  $self->_msg( "\nTrying to find out which special keywords your compiler knows..." );

  my @remap = qw( asm break case char continue default do else for goto if int return sizeof
                  struct switch typedef union while auto const double enum extern float
                  long register short signed static unsigned void volatile inline restrict );

  my @keywords = map { ("_${_}", "__${_}", "__${_}__") } sort
                 @remap, qw( bounded unbounded imag real complex extension );

  my @known;
  my $count = 0;

  for my $key ( sort @keywords ) {
    $self->_work_in_progress( sprintf "%d/%d keywords", scalar @known, $count++ );

    $self->_temp( <<ENDC );
typedef struct $key { int foo; } $key;
int main(void) { return 0; }  /* keep _build happy */
ENDC

    my $res = $self->_compile_or_build_temp;

    $res->{status} and push @known, $key;
  }

  $self->_work_done;

  if( @known ) {
    $self->_msg( "Your compiler recognizes the following special keywords:" );
    $self->_wrapped_list( sort @known );
  }
  else {
    $self->_msg( "None." );
  }

  $self->_debug(sub { Data::Dumper->Dump( [\@known], ['*known'] ) });

  my $remap = join '|', @remap;

  return { map { ( $_ => (/^_*($remap)_*$/ ? $1 : undef) ) } @known }
}

#-----------------------------------------------------------------------
#  INVALID KEYWORDS
#-----------------------------------------------------------------------

sub _get_invalid_keywords
{
  my $self = shift;

  $self->_msg( "\nTrying to find out which keywords your compiler doesn't know..." );


  my @keywords = qw( inline restrict auto const double enum extern float long
                     register short signed static unsigned void volatile asm );

  my @invalid;
  my $count = 0;

  for my $key ( sort @keywords ) {
    $self->_work_in_progress( sprintf "%d/%d keywords", scalar @invalid, $count++ );

    $self->_temp( <<ENDC );
typedef struct $key { int foo; } $key;
int main(void) { return 0; }  /* keep _build happy */
ENDC

    my $res = $self->_compile_or_build_temp;

    $res->{status} == 0 and push @invalid, $key;
  }

  $self->_work_done;

  if( @invalid ) {
    $self->_msg( "Your compiler doesn't recognize the following keywords:" );
    $self->_wrapped_list( sort @invalid );
  }
  else {
    $self->_msg( "Your compiler recognizes all keywords." );
  }

  $self->_debug(sub { Data::Dumper->Dump( [\@invalid], ['*invalid'] ) });

  \@invalid;
}

#-----------------------------------------------------------------------
#  PREDEFINED ASSERTIONS
#-----------------------------------------------------------------------

sub _get_preasserted
{
  my $self = shift;
  my $assert = shift;

  $self->_msg( "\nChecking for assertions (this may take a while)..." );

  my $code;

  for my $pred ( keys %$assert ) {
    for my $ans ( @{$assert->{$pred}} ) {
      $code .= <<ENDC;
#if #$pred($ans)
"$pred($ans)";
#endif
ENDC
    }
  }

  $self->_temp( $code );

  my $res = $self->_preprocess_temp;

  if( $res->{status} ) {
    $self->_msg( "Your compiler doesn't seem to like assertions." );
    return {};
  }

  my %results;

  for my $line ($self->_read_pp($res)) {
    chomp $line;
    next if $line =~ /^\s*#/;
    next if $line =~ /^\s*$/;
    $line =~ /"\s*([^"]+?)\s*"\s*;/ or next;
    $results{$1} = 1;
  }

  if( my $count = keys %results ) {
    my $what = $count > 1 ? "these $count assertions" : "this assertion";
    $self->_msg( "Your compiler makes $what:" );
    $self->_wrapped_list( sort keys %results );
  }
  else {
    $self->_msg( "Your compiler doesn't seem to assert anything." );
  }

  \%results;
}

#-----------------------------------------------------------------------
#  PREDEFINED MACROS
#-----------------------------------------------------------------------

sub _get_predefined
{
  my $self = shift;
  my $names = shift;
  my $pos = 0;

  my @stdnames = qw( __LINE__ __FILE__ __DATE__ __TIME__ __STDC__ _Pragma );
  my @special = qw( __has_extension __has_include_next __has_feature __has_attribute );

  $self->_msg( "\nChecking for predefined macros (this may take a while)..." );

  my %defs;

  for my $name ( &_preset_names ) {
    my @words = map { ("$_", "_$_", "__$_", "__${_}__" ) }
                    $name, uc($name), lc($name);
    @defs{@words} = (1)x@words;
  }

  my %results = ();
  my $count = 0;
  my $max = @$names;

  while(1) {
    delete @defs{@stdnames};
    delete @defs{@special};

    $self->_work_in_progress( "($count) $pos/$max" );

    my $code;

    for my $def ( keys %defs ) {
      $code .= <<ENDC;
#ifdef $def
"$def";
($def);
#endif
ENDC
    }

    $self->_temp( $code );

    my $res = $self->_preprocess_temp;

    if( $res->{status} ) {
      $self->_work_done;
      $self->_msg( "Your compiler exited unexpectedly:" );
      $self->_out( '| ', @{$res->{stderr}} );
      return {};
    }

    my $out = join '', $self->_read_pp($res);

    while( $out =~ /"\s*([^\s"]+)\s*"\s*;\s*\(\s*([^\r\n]*?)\s*\)\s*;/g ) {
      $results{$1} = $2;
    }

    $count = keys %results;

    %defs = ();

    last if $pos >= @$names;

    my $last = $pos+999;
    $last = $#$names if $last > $#$names;
    @defs{@{$names}[$pos..$last]} = (1)x($last-$pos+1);
    $pos = $last+1;
  }

  delete @results{@stdnames};

  $self->_work_done;

  if( my $count = keys %results ) {
    my $what = $count > 1 ? "these $count symbols" : "this symbol";
    $self->_msg( "Your compiler defines $what:" );
    $self->_wrapped_list( sort keys %results );
  }
  else {
    $self->_msg( "Your compiler doesn't seem to define anything." );
  }

  $self->_debug(sub { Data::Dumper->Dump( [\%results], ['*results'] ) });

  \%results;
}

#-----------------------------------------------------------------------
#  INCLUDE PATH
#-----------------------------------------------------------------------

sub _incpath_main
{
  my($self, $quiet, @headers) = @_;
  my %resolve;

  for my $hdr ( @headers ) {
    $self->_work_in_progress;

    $self->_temp( <<TEMP );
#include <$hdr>
TEMP
    my $res = $self->_preprocess_temp;

    if( $res->{status} ) {
      $quiet or $self->_msg("Compiler choked on including '$hdr'. Maybe a missing ANSI header...");
      next;
    }

    for my $line ($self->_read_pp($res)) {
      if( $line =~ $self->{ppline} ) {
        my $file = $2;
        if( $file =~ /^(.*)\Q$hdr\E$/ ) {
          my $inc = $1;
          $inc =~ y{\\}{/}s;
          $resolve{$hdr} = [$inc];
          last;
        }
      }
    }
  }

  %resolve;
}

sub _get_files
{
  my($dir, $rex) = @_;
  local *DIR;

  opendir DIR, $dir or return ();
  my @files = readdir DIR;
  closedir DIR;

  if( defined $rex ) {
    return grep $_ =~ $rex, @files;
  }

  @files;
}

sub _run_incpath
{
  my $self = shift;
  my(@inc,@newhdr,%resolve);
  my @headers = @{$self->{headers}};

  $self->_msg( "\nTrying to determine include path..." );

  %resolve = $self->_incpath_main(0, @headers);
  @inc = _unique( map $_->[0], values %resolve );

  if( @inc > 1 ) {
    my @files;
    for my $path ( @inc ) {
      push @files, grep !-d $path.$_, _get_files( $path );
    }

    for my $hdr ( _unique( @files ) ) {
      my @f = grep { -e "$_$hdr" } @inc;
      @f > 1 && push @newhdr, $hdr;
    }

    push @headers, @newhdr;
    %resolve = ( %resolve, $self->_incpath_main(1, @newhdr) );

    for my $hdr ( @headers ) {
      for my $path ( @inc ) {
        next unless exists $resolve{$hdr};
        next if $path eq $resolve{$hdr}[0];
        -e $path.$hdr and push @{$resolve{$hdr}}, $path;
      }
    }

    $self->_debug(sub { Data::Dumper->Dump( [\%resolve], ['*resolve'] ) });

    my($i,$j);
    my @h = grep { @{$resolve{$_}} > 1 } keys %resolve;

    for( $i = 0; $i < @inc; ++$i ) {
      for( $j = $i+1; $j < @inc; ++$j ) {
        for my $h ( @h ) {
          my($a,$b) = @inc[$i,$j];
          my @r = @{$resolve{$h}};
          $b eq $r[0] or next;
          for( my $k = 1; $k < @r; ++$k ) {
            $r[$k] eq $a and @inc[$i,$j] = @inc[$j,$i];
          }
        }
      }
    }
  }

  $self->_work_done;

  $self->_debug(sub { Data::Dumper->Dump( [\@inc], ['*inc'] ) });

  $self->_msg( "The include path appears to be:" );
  $self->_msg( "  ($_) $inc[$_-1]" ) for 1 .. @inc;

  \@inc;
}

#-----------------------------------------------------------------------
#  GATHER MACRO / ASSERTION NAMES
#-----------------------------------------------------------------------

sub _names
{
  my $self = shift;
  my $inc_path = shift;
  my @ppkey = qw( define undef include line error pragma if ifdef ifndef defined elif else endif );
  my %files;
  my %names;
  my %asserts;

  $self->_msg( "\nSearching macro names and assertions..." );

  my @files = map { my $p = $_; map { $p.$_ } _get_files( $p, qr/\.[hH]$/ ) } @$inc_path;
  my $ff = 0;

  while( @files ) {
    my $file = shift @files;
    -e $file or next;
    exists $files{$file} and next;
    $files{$file} = 1;
    $ff = keys %files;
    $self->_work_in_progress( "$ff files found" );
    my $fh = new IO::File $file;
    next unless defined $fh;
    while( <$fh> ) {
      if( /^\s*#\s*include\s*[<"]([^>"]+)[>"]/ ) {
        for( '', @$inc_path ) {
          my $f = $_.$1;
          exists $files{$f} or push @files, $f;
        }
      }
    }
  }

  $self->_debug(sub { Data::Dumper->Dump([\%files], ['*files']) });

  $ff = keys %files;
  my $fs = 0;

  for my $name ( keys %files ) {
    my $count = keys %names;
    $fs++;
    $self->_work_in_progress( "($count) $fs/$ff files scanned" );
    -e $name or next;
    my $fh = new IO::File $name;
    next unless defined $fh;
    my $file = do { local $/; <$fh> };
    $file =~ s{\\\s*$/}{}g;
    while( $file =~ /\b([A-Za-z_]\w*)\b/g ) {
      $names{$1} ||= 1;
    }
    for my $line ( $file =~ /^\s*#(?:el)?if(.*)/gm ) {
      while( $line =~ /#\s*(\w+)\s*\(\s*(\w+)\s*\)/g ) {
        $asserts{$1}{$2} ||= 1;
      }
    }
  }

  delete @names{@ppkey};

  my @names = keys %names;

  my $assertions = 0;
  for( keys %asserts ) {
    $assertions += keys %{$asserts{$_}};
  }

  # merge assertions with fixed assertions from _assert()
  my $asserts = _assert();
  for my $q ( keys %$asserts ) {
    for my $a ( @{$asserts->{$q}} ) {
      $asserts{$q}{$a} ||= 1;
    }
  }

  for( keys %asserts ) {
    $asserts{$_} = [sort keys %{$asserts{$_}}];
  }

  $self->_work_done;
  $self->{debug} and $self->_debug(sub { Data::Dumper->Dump([\@names, \%asserts], [qw(*names *asserts)]) });

  $assertions = $assertions ? " and $assertions potential assertions" : '';
  $self->_msg( sprintf "Found %d potential macro names$assertions.", scalar @names );

  (\@names, \%asserts);
}

########################################################################
#
#  CONFIGURE
#
########################################################################

sub _configure
{
  my $self = shift;

  ### Purpose of _configure:
  ### Populate these options unless set by the user and
  ### check if they do what they're supposed to.
  ###
  ###   --cc             the C compiler
  ###   --preprocess     how to get preprocessor output from the compiler
  ###   --compile-obj    how to compile C file to object file
  ###   --compile-exe    how to compile C file to executable file
  ###
  ### TODO: detect a.out. (Probably glob <*> before and after running the compiler?)

  ### Save user values...

  my $user = {};

  for my $c (qw( cc preprocess compile-obj compile-exe )) {
    $user->{$c} = $self->{$c} if exists $self->{$c};
  }

  ### Let's go!

  $self->_cleanup_basename;
  $self->_msg("Checking if your compiler works...");

  ### First, try to find a working CC that we can run...

  my @CC = exists $user->{cc} ? ($user->{cc}) : (qw( cc gcc icc cl ));

  my $res;
  my $didnotrun;
  my $fullcc;

  do {
    my $ccname = shift @CC;
    $fullcc = which($ccname);
    $fullcc = $ccname if !defined $fullcc && -x $ccname;
    $didnotrun = 1;
    if (defined $fullcc) {
      $self->{cc} = $fullcc;
      $res = $self->_runprog($self->{cc});
      $didnotrun = $res->{didnotrun};
    }
    if ($didnotrun and exists $user->{cc}) {
      if (defined $fullcc) {
        $self->_msg("It seems your compiler '$self->{cc}' did not run.");
      }
      else {
        $self->_msg("I could not find your compiler '$self->{cc}'.");
      }
      $self->_quit;
    }
  } while ($didnotrun && @CC);

  if ($didnotrun) {
    $self->_msg("None of the compilers I know seemed to run.");
    $self->_msg("Try specifying a compiler using the --cc option.");
    $self->_quit;
  };

  $self->_msg("Found a working compiler at $self->{cc}\n");

  ### Ok, so we have a compiler. Let's see how to get preprocessor output...

  my $line = 'char*lotr="Very useful, no doubt, that was to Saruman; yet it seems that he was not content.";';

  $self->_temp(<<TEMP);
$line
TEMP

  my @PP  = exists $user->{preprocess} ? ($user->{preprocess}) : ('-E %c |', '-c -E %c |', '-sp %c');
  my @PPE = exists $user->{'pp-ext'}   ? ($user->{'pp-ext'})   : ('.i', '.p');

  my($have_source, $have_ppline, $pp_ext);

  do {
    $have_source = 0;
    $have_ppline = 0;

    $self->{preprocess} = shift @PP;

    $res = $self->_preprocess_temp;
    for my $ext (@PPE) {
      $self->{'pp-ext'} = $ext;
      if (-f $self->_ppfile) {
        $pp_ext = $ext;
        last;
      }
    }
    my @ppout = $self->_read_pp($res);

    for (@ppout) {
      /\Q$line/                                            and $have_source = 1;
      $_ =~ $self->{ppline} && $2 =~ /\Q$self->{basename}/ and $have_ppline = 1;
    }
  } while (!$have_source && @PP);

  $self->{'pp-ext'} = $pp_ext || '';
  $self->{can_preprocess} = $have_source;
  $self->{can_read_ppout} = $have_ppline;

  if (!$self->{can_preprocess}) {
    $self->_msg("I couldn't figure out how to get usable preprocessor output from the compiler.");
  }
  else {
    $self->_msg("I can get preprocessor output using rule [$self->{preprocess}].");
    $self->_msg("But I don't understand the preprocessor output.")
        unless $self->{can_read_ppout};
  }

  ### Compile/build executable files

  $self->{can_compile} = 0;
  $self->{can_build}   = 0;
  $self->{can_run}     = 0;

  $self->_cleanup_basename;
  $self->_temp( <<TEMP );
extern int i;
TEMP

  my @CCO = exists $user->{'compile-obj'} ? ($user->{'compile-obj'}) : ('-c -o %o %c', '%c');
  my @OBJ = exists $user->{'obj-ext'}     ? ($user->{'obj-ext'})     : @{_OS('obj-ext')};
  my $obj_ext;

  do {
    $self->{'compile-obj'} = shift @CCO;
    undef $obj_ext;
    for my $ext (@OBJ) {
      $self->{'obj-ext'} = $ext;
      $res = $self->_compile_temp;
      if (-f $self->_objfile) {
        $obj_ext = $ext;
        last;
      }
    }
    $self->{can_compile} = $res->{didnotrun} == 0 && $res->{status} == 0 && defined $obj_ext;
  } while (!$self->{can_compile} && @CCO);

  $self->{'obj-ext'} = $obj_ext || '';

  if ($self->{can_compile}) {
    $self->_msg("I can compile object files using rule [$self->{'compile-obj'}].");
  }
  else {
    $self->_msg("I cannot compile object files.");
  }

  if ($self->{run}) {
    $self->_cleanup_basename;
    $self->_temp(<<TEMP);
#include <stdio.h>
int main()
{
  printf("Hello World\\n");
  return 0;
}
TEMP

    my @CCE = exists $user->{'compile-exe'} ? ($user->{'compile-exe'}) : ('-o %e %c');
    my @EXE = exists $user->{'exe-ext'}     ? ($user->{'exe-ext'})     : @{_OS('exe-ext')};
    my $exe_ext;

    do {
      $self->{'compile-exe'} = shift @CCE;
      undef $exe_ext;
      for my $ext (@EXE) {
        $self->{'exe-ext'} = $ext;
        $res = $self->_build_temp;
        if (-f $self->_exefile) {
          $exe_ext = $ext;
          last;
        }
      }
      $self->{can_build} = $res->{didnotrun} == 0 && $res->{status} == 0 && defined $exe_ext;
    } while (!$self->{can_build} && @CCE);
  
    $self->{'exe-ext'} = $exe_ext || '';

    if ($self->{can_build}) {
      if ($self->{can_compile}) {
        $self->_msg("I can also build executable files using rule [$self->{'compile-exe'}].");
      }
      else {
        $self->_msg("But it seems I can build executable files using rule [$self->{'compile-exe'}].");
      }
      $res = $self->_run_temp;
  
      $self->{can_run} = $res->{didnotrun} == 0 && $res->{status} == 0
                         && grep /Hello World/, @{$res->{stdout}};
  
      if ($self->{can_run}) {
        $self->_msg("And I can run the executables. Great!");
      }
      else {
        $self->_msg("But I cannot run the executables. That should be fine, too.");
      }
    }
    else {
      if ($self->{can_compile}) {
        $self->_msg("But I cannot build executable files. No big deal.");
      }
      else {
        $self->_msg("And I cannot build executable files. Sigh.");
      }
    }
  }
  else {
    $self->_msg("No need to check if I can build executables.");
  }
  
  $self->_cleanup_basename;

  $self->_debug(sub { Data::Dumper->Dump( [$self], [qw(self)] ) });

  unless ($self->{can_preprocess} || $self->{can_compile} || $self->{can_run}) {
    my @opt = map { "--$_" } grep { !exists $user->{$_} }
              qw( preprocess compile-obj compile-exe );

    if (@opt) {
      my $last = pop @opt;
      my $opt = @opt ? join(', ', @opt) . " and $last options" : "$last option";
      $self->_msg_wrapped("\nTry using the $opt to specify compiler behaviour.");
    }

    $self->_quit;
  }
}

########################################################################
#
#  UTILITY ROUTINES
#
########################################################################

sub _OS
{
  my $prop = shift;
  my %os = (
    (map { ( $_ => {
      'obj-ext' => ['.obj', '.o'],
      'exe-ext' => ['.exe', ''],
      'file-sep' => '\\',
    } ) } qw( MSWin32 dos os2 ) ),
  );
  my %def = (
    'obj-ext' => ['.o', '.obj'],
    'exe-ext' => ['', '.exe'],
    'file-sep' => '/',
  );

  return exists $os{$^O} ? $os{$^O}{$prop} : $def{$prop};
}

sub _cleanup_basename
{
  my $self = shift;
  my %seen;
  my @basefiles = grep !$seen{$_}++, glob "$self->{basename}*";
  push @basefiles, grep !$seen{$_}++, glob "$self->{basename}.*";
  $self->_debug("cleaning up: @basefiles\n");
  unlink @basefiles;
}

sub _unique
{
  my %unique;
  grep !$unique{$_}++, @_;
}

sub _cfile
{
  my $self = shift;
  return $self->{basename} . ($self->{'c-ext'} || '');
}

sub _ppfile
{
  my $self = shift;
  return $self->{basename} . ($self->{'pp-ext'} || '');
}

sub _objfile
{
  my $self = shift;
  return $self->{basename} . ($self->{'obj-ext'} || '');
}

sub _exefile
{
  my $self = shift;
  return $self->{basename} . ($self->{'exe-ext'} || '');
}

sub _read_pp
{
  my($self, $res) = @_;

  if ($self->{preprocess} =~ /\|$/) {
    return @{$res->{stdout}};
  }

  my $f = new IO::File $self->_ppfile or return;

  return <$f>;
}

sub _temp
{
  my $self = shift;
  my $temp = $self->_cfile;
  $self->_debug( "creating temporary file '$temp'\n" );
  if (-e $temp) {
    unlink $temp
        or croak "Could not remove temporary file '$temp': $!\n";
  }
  my $f = new IO::File ">$temp"
      or croak "Could not open temporary file '$temp': $!\n";
  $f->print(@_);
}

sub _quit
{
  my $self = shift;
  $self->_msg("\nSorry, cannot continue.");
  $self->cleanup;
  exit(1);
}

sub _run_temp
{
  my $self = shift;
  $self->_runprog( "." . _OS('file-sep') . $self->_exefile );
}

sub _interpolate
{
  my($self, $template) = @_;
  my %replace = (
    c => $self->_cfile,
    o => $self->_objfile,
    e => $self->_exefile,
    i => $self->_ppfile,
  );
  my $match = join '|', keys %replace;
  $template =~ s/\s+\|$//;
  $template =~ s/%($match)/$replace{$1}/g;
  return shellwords($template);
}

sub _compile_or_build_temp
{
  my $self = shift;
  my $meth = $self->{can_compile} ? '_compile_temp' : '_build_temp';
  $self->$meth();
}

sub _build_temp
{
  my $self = shift;
  unlink $self->_exefile if -f $self->_exefile;  # make sure exe is removed
  $self->_runcc($self->_interpolate($self->{'compile-exe'}));
}

sub _compile_temp
{
  my $self = shift;
  unlink $self->_objfile if -f $self->_objfile;  # make sure obj is removed
  $self->_runcc($self->_interpolate($self->{'compile-obj'}));
}

sub _preprocess_temp
{
  my $self = shift;
  $self->_runcc($self->_interpolate($self->{'preprocess'}));
}

sub _runcc
{
  my $self = shift;
  $self->_runprog($self->{cc}, @{$self->{ccflags}}, @_);
}

sub _runprog
{
  my $self = shift;
  my $prog = shift;
  my @args = @_;

  eval { alarm 10; alarm 0; };
  my $has_alarm = $@ eq '';
  my $tmp = '_t_m_p_';

  $self->_debug( "running '$prog @args'\n" );

  eval {
    local $SIG{ALRM};

    if( $has_alarm ) {
      $SIG{ALRM} = sub { die "TIMEOUT\n" };
      alarm $self->{timeout};
    }

    my $run = $prog =~ m/\s/ ? qq("$prog") : $prog;

    system "$run @args >$tmp.out 2>$tmp.err";

    $has_alarm and alarm 0;
  };

  my %rval = (
    status => $? >> 8,
  );

  for my $p (qw(out err)) {
    my $file = "$tmp.$p";
    my @lines;
    if (-f $file) {
      {
        my $fh = IO::File->new($file);
        if (defined $fh) {
          @lines = <$fh>;
        }
      }
      unlink $file;
    }
    $rval{"std$p"} = \@lines;
  }

  $rval{didnotrun} = 0;

  if( @{$rval{stdout}} && $rval{stdout}[0] =~ /^Can't exec "\Q$prog\E":/ ) {
    $rval{didnotrun} = 1;
  }

  if( $^O eq 'MSWin32' && @{$rval{stdout}} == 0 && @{$rval{stderr}} == 0 && $rval{status} == 1 ) {
    $rval{didnotrun} = 1;
  }

  if( $rval{didnotrun} and $self->{fatal} ) {
    croak "could not run '$prog @args'\n";
  }

  $? & 128 and $rval{core}   = 1;
  $? & 127 and $rval{signal} = $? & 127;

  $self->{debug} and $self->_debug(sub { Data::Dumper->Dump( [\%rval], ['*rval'] ) });

  if( $self->{__int__} ) {
    $self->_msg( "\n\nInterrupted..." );
    $self->_quit;
  }

  \%rval;
}

sub _work_in_progress
{
  my $self = shift;
  $self->{quiet} and return;
  $self->{status} or return;
  my @prog = qw(
    ----------
    >---------
    *>--------
    +*>-------
    -+*>------
    --+*>-----
    ---+*>----
    ----+*>---
    -----+*>--
    ------+*>-
    -------+*>
    --------+*
    ---------+
    ----------
    ---------<
    --------<*
    -------<*+
    ------<*+-
    -----<*+--
    ----<*+---
    ---<*+----
    --<*+-----
    -<*+------
    <*+-------
    *+--------
    +---------
  );
  my $index = 0;
  my @t = times;
  my $t = $t[0]+$t[1]+$t[2]+$t[3];
  if( exists $self->{__progress__} ) {
    $t - $self->{__progress__} < 0.1 and return;
    $index = ++$self->{__prog_index__} % @prog;
  }
  print STDERR "\r", $prog[$index];
  if( @_ ) {
    my $str = ' ' . join( '', @_ );
    $str .= ' 'x(40-length($str));
    print STDERR $str;
  }
  if( $self->{__int__} ) {
    $self->_msg( "\n\nInterrupted..." );
    $self->_quit;
  }
  $self->{__progress__} = $t;
}

sub _work_done
{
  my $self = shift;
  $self->{quiet} and return;
  $self->{status} or return;
  delete $self->{__progress__};
  delete $self->{__prog_index__};
  print STDERR "\r", ' 'x50, "\r";
}

sub _msg
{
  my $self = shift;
  $self->{quiet} and return;
  if( $self->{debug} ) {
    my (undef,undef,$line,$sub) = caller 1;
    print STDERR "($sub:$line): ";
  }
  print STDERR @_, "\n";
}

sub _msg_wrapped
{
  my $self = shift;
  $self->{quiet} and return;
  my $string = '';
  if( $self->{debug} ) {
    my (undef,undef,$line,$sub) = caller 1;
    $string .= "($sub:$line): ";
  }
  $string .= join '', @_, "\n";
  print STDERR wrap('', '', $string);
}

sub _wrapped_list
{
  my $self = shift;
  $self->{quiet} and return;
  my $string = "[@_]\n";
  print STDERR wrap( '  ', '   ', $string );
}

sub _out
{
  my $self = shift;
  $self->{quiet} and return;
  my $pre = shift;
  my @args = @_;
  for( @args ) {
    s/^/$pre/gms;
    /[\r\n]+$/ or s/$/\n/;
  }
  print STDERR @args;
}

sub _debug
{
  my $self = shift;
  $self->{debug} or return;
  my @args = @_;
  my (undef,undef,$line,$sub) = caller 1;
  for (@args) {
    $_ = $_->() if ref $_ eq 'CODE';
    s/^/DEBUG | /gms;
  }
  print STDERR "DEBUG @ $sub:$line\n", @args;
}

sub which
{
  my $command = shift;
  my(@PATH, @PATHEXT, $cfg);

  my @config = (
    { os => 'MSWin32|dos|os2', path_sep => ';' , file_sep => '\\', var => 'PATH'     },
    { os => 'MacOS'          , path_sep => '\,', file_sep => ':' , var => 'Commands' },
    { os => '.*'             , path_sep => ':' , file_sep => '/' , var => 'PATH'     },
  );

  for( @config ) {
    if( $^O =~ /^(?:$_->{os})$/ ) {
      $cfg = $_;
      last;
    }
  }

  if( index( $command, $cfg->{file_sep} ) >= 0 ) {
    my $full;

    if( $^O eq 'MacOS' ) {
      -e $command and return $command;
    }
    else {
      -x $command and return $command;
      for my $ext ( @PATHEXT ) {
        -x "$command$ext" and return "$command$ext";
      }
    }
  }
  else {
    if( exists $ENV{$cfg->{var}} ) {
      my %uni;
      @PATH = grep !$uni{$_}++,
              split /$cfg->{path_sep}/, $ENV{$cfg->{var}};
    }

    if( exists $ENV{PATHEXT} ) {
      my %uni;
      @PATHEXT = grep !$uni{$_}++,
                 split /$cfg->{path_sep}/, $ENV{PATHEXT};
    }

    for my $dir ( @PATH ) {
      my $full;

      if( $^O eq 'MacOS' ) {
        $full = "$dir$command";
        -e $full and return $full;
      }
      else {
        $full = "$dir$cfg->{file_sep}$command";
        -x $full and return $full;
        for my $ext ( @PATHEXT ) {
          -x "$full$ext" and return "$full$ext";
        }
      }
    }
  }

  return undef;
}


__END__

=head1 NAME

ccconfig - Get Convert::Binary::C configuration for a compiler

=head1 SYNOPSIS

ccconfig I<options> [-- compiler-options]

I<options>:

  -c
  --cc             compiler   compiler executable to test
                              default: auto-determined
  
  -o
  --output-file    file       output filename
                              default: output to stdout

  -f
  --output-format  format     output format
                              default: dumper

  --basename       name       basename of the temporary test files
                              default: _t_e_s_t

  -I
  --inc-path       path       manually set compiler include path

  --preprocess     rule       compiler rule for preprocessing
  --compile-obj    rule       compiler rule for compiling objects
  --compile-exe    rule       compiler rule for compiling executables

  --c-ext          ext        extension of C source files
  --pp-ext         ext        extension of preprocessor output files
  --obj-ext        ext        extension of object files
  --exe-ext        ext        extension of executable files

  --nodelete                  don't delete temporary files
  --norun                     don't try to run executables
  --quiet                     don't display anything
  --nostatus                  don't display status indicator
  
  --version                   print version number
  
  --debug                     debug mode

Placeholders allowed in compiler rules:

  %c    C source file
  %o    object file
  %e    executable file
  %i    preprocessor output file
  |     result is written to stdout (only at end of rule)

=head1 DESCRIPTION

C<ccconfig> will try to determine a usable configuration for
Convert::Binary::C from testing a compiler executable. It is not
necessary that the binaries generated by the compiler can be
executed, so C<ccconfig> can also be used for cross-compilers.

This tool is still experimental, and you should neither rely
on its output without checking, nor expect it to work in your
environment.

=head1 OPTIONS

=head2 C<--cc> compiler

This option allows you to explicitly specify a compiler
executable. This is especially useful if you don't want
to use your system compiler. If this options is not given,
C<ccconfig> tries to guess a compiler.

=head2 C<--output-file> file

Write Convert::Binary::C configuration to the specified
file. The default is to write the configuration to C<stdout>.

=head2 C<--output-format> format

Specify the output format of the Convert::Binary::C configuration.
The following formats are currently supported:

  dumper      Output a %config hash using Data::Dumper
  require     Output in a format suitable for require

The default is C<dumper>.

=head2 C<--basename> name

Allows you to change the base name of the temporary test files.
This is used along with the various C<-ext> options to build
the filenames of C source files, preprocessor output files,
object files and executables.

=head2 C<--inc-path> path

This option allows you to manually set the include path of the
compiler. This is useful if C<ccconfig> cannot determine the
include path automatically, most probably because it cannot
parse the preprocessor output. This option can be specified
more than once.

=head2 C<--preprocess> rule

Using this option, you can specify a I<rule> that C<ccconfig>
uses to run the compiler to get preprocessor output. Most
compilers write the preprocessor output to standard output
when given the C<-E> option, i.e.

  cc -E foo.c

will preprocess F<foo.c> to standard output. The corresponding
rule for C<ccconfig> would be:

  ccconfig --preprocess='-E %c |'

The <%c> will be replaced with the C source filename, and the
pipe symbol signals that the result will be written to standard
output.

The following placeholders can be used in C<ccconfig> rules:

  %c    C source file
  %o    object file
  %e    executable file
  %i    preprocessor output file

Usually, C<ccconfig> tries to figure out the correct rules on
its own.

=head2 C<--compile-obj> rule

Like C<--preprocess>, this option allows you to define a rule
for how to compile an object file. For most compilers, this rule
will be something like

  ccconfig --compile-obj='-c -o %o %c'

=head2 C<--compile-exe> rule

Like C<--preprocess>, this option allows you to define a rule
for how to compile an executable file. For most compilers, this
rule will be something like

  ccconfig --compile-exe='-o %e %c'

Note that it is sufficient to specify either C<--compile-obj>
or C<--compile-exe>. So if your compiler can only create object
files, that's just fine.

=head2 C<--c-ext>

This option is used along with C<--basename> to build the name
of a C source file. This is usually set to C<.c>.
 
=head2 C<--pp-ext>

This option is used along with C<--basename> to build the name
of a preprocessor output file.
 
=head2 C<--obj-ext>

This option is used along with C<--basename> to build the name
of an object file.
 
=head2 C<--exe-ext>

This option is used along with C<--basename> to build the name
of an executable file.
 
=head2 C<--nodelete>

Don't attempt to delete temporary files that have been created
by the compiler. Normally, C<ccconfig> will look for all files
with the same basename as the temporary test file and delete
them.

=head2 C<--norun>

You can specify this option if the executables generated
by your compiler cannot be run on your machine, i.e. if
you have a cross-compiler. However, C<ccconfig> will
automatically find out that it cannot run the executables.

When this option is set, a different set of algorithms is
used to determine a couple of configuration settings. These
algorithms are all based upon placing a special signature
in the object file. They are less reliable that the standard
algorithms, so you shouldn't use them unless you have to.

=head2 C<--quiet>

Don't display anything except for the final configuration.

=head2 C<--nostatus>

Hide the status indicator. Recommended if you want to
redirect the script output to a file:

  ccconfig --nostatus >config.pl 2>ccconfig.log

=head2 C<--version>

Writes the program name, version and path to standard
output.

=head2 C<--debug>

Generate tons of debug output. Don't use unless you know
what you're doing.

=head1 EXAMPLES

Normally, a simple

  ccconfig

without arguments is enough if you want the configuration for
your system compiler. While C<ccconfig> is running, it will
write lots of status information to C<stderr>. When it's done,
it will usually dump a Perl hash table to C<stdout> which can
be directly used as a configuration for Convert::Binary::C.

If you want the configuration for a different compiler,
or C<ccconfig> cannot determine your system compiler
automatically, use

  ccconfig -c gcc32

if your compiler's name is C<gcc32>.

If you want to pass additional options to the compiler, you
can do so after a double-dash on the command line:

  ccconfig -- -g -DDEBUGGING

or

  ccconfig -c gcc32 -- -ansi -fshort-enums

If you'd like to interface with the Perl core, you may find
a suitable configuration using something like:

  ccconfig --cc=`perl -MConfig -e 'print $Config{cc}'` \
           -- `perl -MConfig -e 'print $Config{ccflags}'`

=head1 COPYRIGHT

Copyright (c) 2002-2015 Marcus Holland-Moritz. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 SEE ALSO

See L<Convert::Binary::C>.

=cut