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

    Copyright (c) 2019-2022 Stephen Whittle  All rights reserved.

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom
    the Software is furnished to do so, subject to the following conditions:
    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    IN THE SOFTWARE.
*/

#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::unit_arg)]
#![allow(clippy::upper_case_acronyms)]

use std::{
    char, ptr, slice, time, mem, ffi, path::Path, io::{Write, Read},
    os::unix::io::AsRawFd
};
use libc::{c_void, EINTR};
use crate::{
    constants::{
        ERR, OK, KEY_MIN, KEY_MAX, KEY_CODE_YES, KEY_RESIZE,
        TRUE, FALSE
    },
    normal, extend,
    attributescolorpairset::*, changed::*, characterresult::*,
    chtypet::*, complex::*, cursortype::*, cstring::*, gen::*,
    keybinding::*, legacy::*, origin::*, orientation::*,
    justification::*, wide::*, ncursescolortype::*,
    ncurseswerror::*, region::*, size::*, softlabeltype::*,
    shims::{funcs, ncurses, bindings}
};

macro_rules! path_to_cstring_as_slice { ($name: ident) => { &*(path_to_cstring_as_vec($name)?.as_slice() as *const [u8] as *const [i8]) } }
macro_rules! str_to_cstring_as_slice { ($name: ident) => { &*(str_to_cstring_as_vec($name)?.as_slice() as *const [u8] as *const [i8]) } }

static MODULE_PATH: &str = "ncursesw::ncurses::";

// The maximum buffer size used in a variety of functions.
const LINE_MAX: usize = 4096;

/// NCurses window raw pointer.
type WINDOW = ncurses::WINDOW;
/// NCurses screen raw pointer.
type SCREEN = ncurses::SCREEN;
/// Ripoff line callback function signature.
type RipoffInit = crate::shims::bindings::RipoffInit;

// Raw attribute type value.
type attr_t = ncurses::attr_t;
type cchar_t = ncurses::cchar_t;
type chtype = ncurses::chtype;
type short_t = ncurses::short_t;
type wchar_t = ncurses::wchar_t;
type wint_t = ncurses::wint_t;

/// Return the raw pointer to the current screen.
pub fn curscr() -> WINDOW {
    unsafe { ncurses::curscr() }
}

/// Return the raw pointer to the new screen.
pub fn newscr() -> WINDOW {
    unsafe { ncurses::newscr() }
}

/// Return the raw pointer to the standard screen.
pub fn stdscr() -> WINDOW {
    unsafe { ncurses::stdscr() }
}

pub fn ttytype() -> result!(String) {
    ncurses::ttytype().ok_or(ncurses_function_error!("ttytype"))
}

/// Return the number of colors available.
pub fn COLORS() -> i32 {
    ncurses::COLORS()
}

#[deprecated(since = "0.4.0", note = "use shims::ncurses::COLOR_PAIR() instead")]
/// Return the attribute value of a given `normal` color pair.
pub fn COLOR_PAIR(color_pair: i32) -> attr_t {
    ncurses::COLOR_PAIR(color_pair) as attr_t
}

#[deprecated(since = "0.4.0", note = "use normal::Attributes::color_pair() instead")]
/// Return the color pair number from  given `normal` attributes value.
pub fn PAIR_NUMBER(attrs: attr_t) -> short_t {
    ncurses::PAIR_NUMBER(attrs.try_into().unwrap()) as short_t
}

/// Return the number of color pairs available.
pub fn COLOR_PAIRS() -> i32 {
    ncurses::COLOR_PAIRS()
}

/// Return the number of columns (x-axis) available on the terminal.
pub fn COLS() -> i32 {
    ncurses::COLS()
}

/// Return the delay used to interpret termianl keyboard escape sequences.
pub fn ESCDELAY() -> result!(time::Duration) {
    Ok(time::Duration::from_millis(u64::try_from(ncurses::ESCDELAY())?))
}

/// Return the number of lines (y-axis) available on the terminal.
pub fn LINES() -> i32 {
    ncurses::LINES()
}

/// Return the number of columns a tab represents on the terminal.
pub fn TABSIZE() -> i32 {
    ncurses::TABSIZE()
}

/// Equivalent of `wadd_wch()` using `stdscr()` as window `handle`.
pub fn add_wch(wch: ComplexChar) -> result!(()) {
    match ncurses::add_wch(&ComplexChar::into(wch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("add_wch", rc))
    }
}

/// Equivalent of `wadd_wchnstr()` using `stdscr()` as window `handle`.
pub fn add_wchnstr(wchstr: &ComplexString, number: i32) -> result!(()) {
    match ncurses::add_wchnstr(raw_with_nul_as_slice!(wchstr), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("add_wchnstr", rc))
    }
}

/// Equivalent of `wadd_wchstr()` using `stdscr()` as window `handle`.
pub fn add_wchstr(wchstr: &ComplexString) -> result!(()) {
    match ncurses::add_wchstr(raw_with_nul_as_slice!(wchstr)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("add_wchstr", rc))
    }
}

/// Equivalent of `waddch()` using `stdscr()` as window `handle`.
pub fn addch(ch: ChtypeChar) -> result!(()) {
    match ncurses::addch(ChtypeChar::into(ch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("addch", rc))
    }
}

/// Equivalent of `waddchnstr()` using `stdscr()` as window `handle`.
pub fn addchnstr(chstr: &ChtypeString, number: i32) -> result!(()) {
    match ncurses::addchnstr(raw_with_nul_as_slice!(chstr), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("addchnstr", rc))
    }
}

/// Equivalent of `waddchstr()` using `stdscr()` as window `handle`.
pub fn addchstr(chstr: &ChtypeString) -> result!(()) {
    match ncurses::addchstr(raw_with_nul_as_slice!(chstr)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("addchstr", rc))
    }
}

/// Equivalent of `waddnstr()` using `stdscr()` as window `handle`.
pub fn addnstr<S: Into<String>>(str: S, number: i32) -> result!(()) {
    let str = str.into().to_string();

    match ncurses::addnstr(unsafe { c_str_with_nul!(str) }, number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("addnstr", rc)),
    }
}

/// Equivalent of `waddnwstr()` using `stdscr()` as window `handle`.
pub fn addnwstr(wstr: &WideString, number: i32) -> result!(()) {
    match ncurses::addnwstr(raw_with_nul_as_slice!(wstr), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("addnwstr", rc))
    }
}

/// Equivalent of `waddstr()` using `stdscr()` as window `handle`.
pub fn addstr<S: Into<String>>(str: S) -> result!(()) {
    let str = str.into().to_string();

    match ncurses::addstr(unsafe { c_str_with_nul!(str) }) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("addstr", rc))
    }
}

/// Equivalent of `waddwstr()` using `stdscr()` as window `handle`.
pub fn addwstr(wstr: &WideString) -> result!(()) {
    match ncurses::addwstr(raw_with_nul_as_slice!(wstr)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("addwstr", rc))
    }
}

/// This defines which colors to paint for color pair 0. This function
/// recognizes a special color `Color::TerminalDefault`, which denotes
/// the default terminal color.
///
/// The following are equivalent:
/// ```text
/// use_default_colors()?;
/// assume_default_colors(Colors::default())?;
/// ```
pub fn assume_default_colors<S, C, T>(colors: S) -> result!(())
    where S: ColorsType<C, T>,
          C: ColorType<T>,
          T: ColorAttributeTypes
{
    match ncurses::assume_default_colors(colors.foreground().number(), colors.background().number()) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("assume_default_colors", rc))
    }
}

/// Equivalent of `wattr_get()` using `stdscr()` as window `handle`.
pub fn attr_get() -> result!(AttributesColorPairSet) {
    let mut attrs: [attr_t; 1] = [0];
    let mut color_pair: [short_t; 1] = [0];
    let mut opts: [i32; 1] = [0];

    match unsafe { ncurses::attr_get(attrs.as_mut_ptr(), color_pair.as_mut_ptr(), opts.as_mut_ptr() as *mut c_void) } {
        OK => Ok(match ncurses_colortype() {
            NCursesColorType::Normal => {
                AttributesColorPairSet::Normal(
                    normal::AttributesColorPair::new(
                        normal::Attributes::_from(None, attrs[0]),
                        normal::ColorPair::_from(None, color_pair[0])
                    )
                )
            },
            NCursesColorType::Extend => {
                AttributesColorPairSet::Extend(
                    extend::AttributesColorPair::new(
                        extend::Attributes::_from(None, attrs[0]),
                        extend::ColorPair::_from(None, opts[0])
                    )
                )
            }
        }),
        rc => Err(ncurses_function_error_with_rc!("attr_get", rc))
    }
}

/// Equivalent of `wattr_off()` using `stdscr()` as window `handle`.
pub fn attr_off<A, T>(attrs: A) -> result!(())
    where A: AttributesType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::attr_off(attrs.as_attr_t(), ptr::null_mut()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("attr_off", rc))
    }
}

/// Equivalent of `wattr_on()` using `stdscr()` as window `handle`.
pub fn attr_on<A, T>(attrs: A) -> result!(())
    where A: AttributesType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::attr_on(attrs.as_attr_t(), ptr::null_mut()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("attr_on", rc))
    }
}

/// Equivalent of `wattr_set()` using `stdscr()` as window `handle`.
pub fn attr_set<A, P, T>(attrs: A, color_pair: P) -> result!(())
    where A: AttributesType<T>,
          P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::attr_set(attrs.as_attr_t(), color_pair.as_short_t(), color_pair.as_mut_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("attr_set", rc))
    }
}

/// Equivalent of `wattroff()` using `stdscr()` as window `handle`.
pub fn attroff(attrs: normal::Attributes) -> result!(()) {
    match ncurses::attroff(normal::Attributes::into(attrs)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("attroff", rc))
    }
}

/// Equivalent of `wattron()` using `stdscr()` as window `handle`.
pub fn attron(attrs: normal::Attributes) -> result!(()) {
    match ncurses::attron(normal::Attributes::into(attrs)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("attron", rc))
    }
}

/// Equivalent of `wattron()` using `stdscr()` as window `handle`.
pub fn attrset(attrs: normal::Attributes) -> result!(()) {
    match ncurses::attrset(normal::Attributes::into(attrs)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("attrset", rc))
    }
}

/// Return the output speed of the terminal in bits per second.
/// On software terminal emulators it will have a fixed high value.
/// Included for historical reasons; in former times, it was used
/// to write output loops for time delays and occasionally to
/// change interfaces depending on the line speed.
pub fn baudrate() -> i32 {
    ncurses::baudrate()
}

/// Emit a short attention sound.
pub fn beep() -> result!(()) {
    match ncurses::beep() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("beep", rc))
    }
}

/// Set the background property of the window to the character `ch`.
/// The change is then applied to every character position in that window:
///
/// - The attribute of every character in the window is changed to the new background attribute.
/// - Wherever the former background character appears, it is changed to the new background character.
pub fn bkgd(ch: ChtypeChar) -> result!(()) {
    match ncurses::bkgd(ChtypeChar::into(ch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("bkgd", rc))
    }
}

/// Set the window’s background. A window’s background consists of a character
/// and it's combination of attributes. The attribute part of the background is
/// combined (OR’ed) with all non-blank characters that are written into the
/// window. Both the character and attribute parts of the background are combined
/// with the blank characters. The background becomes a property of the character
/// and moves with the character through any scrolling and
/// insert/delete line/character operations.
pub fn bkgdset(ch: ChtypeChar) {
    ncurses::bkgdset(ChtypeChar::into(ch))
}

/// Equivalent of `wbkgrnd()` using `stdscr()` as window `handle`.
pub fn bkgrnd(wch: ComplexChar) -> result!(()) {
    match ncurses::bkgrnd(&ComplexChar::into(wch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("bkgrnd", rc))
    }
}

/// Equivalent of `wbkgrndset()` using `stdscr()` as window `handle`.
pub fn bkgrndset(wch: ComplexChar) {
    ncurses::bkgrndset(&ComplexChar::into(wch))
}

/// Equivalent of `wborder()` using `stdscr()` as window `handle`.
pub fn border(
    ls: ChtypeChar,
    rs: ChtypeChar,
    ts: ChtypeChar,
    bs: ChtypeChar,
    tl: ChtypeChar,
    tr: ChtypeChar,
    bl: ChtypeChar,
    br: ChtypeChar) -> result!(())
{
    match ncurses::border(
        ChtypeChar::into(ls),
        ChtypeChar::into(rs),
        ChtypeChar::into(ts),
        ChtypeChar::into(bs),
        ChtypeChar::into(tl),
        ChtypeChar::into(tr),
        ChtypeChar::into(bl),
        ChtypeChar::into(br)
    ) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("border", rc))
    }
}

/// Equivalent of `wborder_set()` using `stdscr()` as window `handle`.
pub fn border_set(
    ls: ComplexChar,
    rs: ComplexChar,
    ts: ComplexChar,
    bs: ComplexChar,
    tl: ComplexChar,
    tr: ComplexChar,
    bl: ComplexChar,
    br: ComplexChar) -> result!(())
{
    match ncurses::border_set(
        &ComplexChar::into(ls),
        &ComplexChar::into(rs),
        &ComplexChar::into(ts),
        &ComplexChar::into(bs),
        &ComplexChar::into(tl),
        &ComplexChar::into(tr),
        &ComplexChar::into(bl),
        &ComplexChar::into(br)
    ) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("border_set", rc))
    }
}

/// Similar to `border()`, but both ls and rs are vertch and both ts and
/// bs are horch. The default corner characters are always used by this function.
pub fn r#box(handle: WINDOW, verch: ChtypeChar, horch: ChtypeChar) -> result!(()) {
    match unsafe { ncurses::r#box(handle, ChtypeChar::into(verch), ChtypeChar::into(horch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("box", rc))
    }
}

/// Similar to `border_set()`, but both ls and rs are vertch and both ts and
/// bs are horch. The default corner characters are always used by this function.
pub fn box_set(handle: WINDOW, verch: ComplexChar, horch: ComplexChar) -> result!(()) {
    match unsafe { ncurses::box_set(handle, &ComplexChar::into(verch), &ComplexChar::into(horch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("box_set", rc))
    }
}

/// Return `true` or `false`, depending on whether the programmer
/// can change the colors displayed by the terminal.
pub fn can_change_color() -> bool {
    ncurses::can_change_color()
}

/// Enter cbreak mode. In cbreak mode (sometimes called “rare” mode)
/// normal tty line buffering is turned off and characters are available
/// to be read one by one. However, unlike raw mode, special characters
/// (interrupt, quit, suspend, and flow control) retain their effects
/// on the tty driver and calling program. Calling first raw() then
/// cbreak() leaves the terminal in cbreak mode.
pub fn cbreak() -> result!(()) {
    match ncurses::cbreak() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("cbreak", rc))
    }
}

/// Equivalent of `wchgat()` using `stdscr()` as window `handle`.
pub fn chgat<A, P, T>(number: i32, attrs: A, color_pair: P) -> result!(())
    where A: AttributesType<T>,
          P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::chgat(number, attrs.as_attr_t(), color_pair.as_short_t(), color_pair.as_const_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("chgat", rc))
    }
}

/// Equivalent of `wclear()` using `stdscr()` as window `handle`.
pub fn clear() -> result!(()) {
    match ncurses::clear() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("clear", rc))
    }
}

/// If flag is `true`, the next call to `refresh()` will clear the window completely.
pub fn clearok(handle: WINDOW, flag: bool) -> result!(()) {
    match unsafe { ncurses::clearok(handle, flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("clearok", rc))
    }
}

/// Equivalent of `wclrtobot()` using `stdscr()` as window `handle`.
pub fn clrtobot() -> result!(()) {
    match ncurses::clrtobot() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("clrtobot", rc))
    }
}

/// Equivalent of `wclrtoeol()` using `stdscr()` as window `handle`.
pub fn clrtoeol() -> result!(()) {
    match ncurses::clrtoeol() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("clrtoeol", rc))
    }
}

#[deprecated(since = "0.4.0", note = "Use normal::Color::rgb() or shims::ncurses::color_content() instead")]
/// Return the intensity of the red, green, and blue (RGB) components in
/// the color, which must be between 0 and COLORS. Return a structure,
/// containing the R,G,B values for the given color, which will be
/// between 0 (no component) and 1000 (maximum amount of component).
pub fn color_content(color_number: short_t) -> result!(normal::RGB) {
    let mut r: [short_t; 1] = [0];
    let mut g: [short_t; 1] = [0];
    let mut b: [short_t; 1] = [0];

    match unsafe { ncurses::color_content(color_number, r.as_mut_ptr(), g.as_mut_ptr(), b.as_mut_ptr()) } {
        OK => Ok(normal::RGB::new(r[0], g[0], b[0])),
        rc => Err(ncurses_function_error_with_rc!("color_content", rc))
    }
}

/// Equivalent of `wcolor_set()` using `stdscr()` as window `handle`.
pub fn color_set<P, T>(color_pair: P) -> result!(())
    where P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::color_set(color_pair.as_short_t(), color_pair.as_mut_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("color_set", rc))
    }
}

/// The `copywin()` routine provides a finer granularity of control over
/// the `overlay()` and `overwrite()` routines. As in the `prefresh()`
/// routine, a rectangle is specified in the destination  window, (`dmin`)
/// and (`dmax`), and the upper-left-corner coordinates of the source window,
/// (`smin`). If the argument `overlay` is `true`, then copying is
/// non-destructive, as in `overlay()`.
pub fn copywin(
    src_handle: WINDOW,
    dst_handle: WINDOW,
    smin:       Origin,
    dmin:       Origin,
    dmax:       Origin,
    overlay:    bool) -> result!(())
{
    let olay = if overlay {
        TRUE
    } else {
        FALSE
    };

    match unsafe { ncurses::copywin(src_handle, dst_handle, smin.y, smin.x, dmin.y, dmin.x, dmax.y, dmax.x, olay) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("copywin", rc))
    }
}

/// Set the cursor state. visibility can be set to invisible, normal,
/// or very visible. If the terminal supports the visibility requested,
/// return the previous cursor state; otherwise raise an exception.
/// On many terminals, the “visible” mode is an underline cursor
/// and the “very visible” mode is a block cursor.
pub fn curs_set(cursor: CursorType) -> result!(CursorType) {
    let rc = ncurses::curs_set(cursor.value());

    CursorType::new(rc).ok_or(ncurses_function_error_with_rc!("curs_set", rc))
}

/// Return the version number, including patch level of the underlying
/// library, e.g., 6.1.20180127.
pub fn curses_version() -> result!(String) {
    ncurses::curses_version().ok_or(ncurses_function_error!("curses_version"))
}

/// Save the current terminal mode as the “program” mode, the mode when
/// the running program is using NCurses. (Its counterpart is the “shell”
/// mode, for when the program is not in NCurses.) Subsequent calls to
/// `reset_prog_mode()` will restore this mode.
pub fn def_prog_mode() -> result!(()) {
    match ncurses::def_prog_mode() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("def_prog_mode", rc))
    }
}

/// Save the current terminal mode as the “shell” mode, the mode when
/// the running program is not using NCurses. (Its counterpart is the
/// “program” mode, when the program is using NCurses capabilities.)
/// Subsequent calls to reset_shell_mode() will restore this mode.
pub fn def_shell_mode() -> result!(()) {
    match ncurses::def_shell_mode() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("def_shell_mode", rc))
    }
}

/// Permits an application to define keycodes with their corresponding
/// control strings, so that the NCurses library will interpret them
/// just as it would the predefined codes in the terminfo database.
///
/// If the given `definition` is `None`, any existing definition for
/// the keycode is removed. Similarly, if the given `KeyBinding::Unknown`
/// is negative or zero, any existing string for the given definition
/// is removed.
pub fn define_key<S: Into<String>>(definition: Option<S>, keycode: KeyBinding) -> result!(()) {
    let definition = definition.and_then(|str| Some(str.into().to_string()));

    match unsafe { ncurses::define_key(option_str_as_ptr!(definition), KeyBinding::into(keycode)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("define_key", rc))
    }
}

/// Insert an ms millisecond pause in output.
pub fn delay_output(ms: time::Duration) -> result!(()) {
    match ncurses::delay_output(i32::try_from(ms.as_millis())?) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("delay_output", rc))
    }
}

/// Equivalent of `wdelch()` using `stdscr()` as window `handle`.
pub fn delch() -> result!(()) {
    match ncurses::delch() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("delch", rc))
    }
}

/// Delete the line under the cursor. All following lines are moved up by one line.
pub fn deleteln() -> result!(()) {
    match ncurses::deleteln() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("deleteln", rc))
    }
}

/// The `delscreen()` routine frees storage associated with the `SCREEN`
/// data structure. The `endwin()` routine does not do this, so `delscreen()` should
/// be called after `endwin()` if a particular `SCREEN` is no longer needed.
pub fn delscreen(screen: SCREEN) {
    unsafe { ncurses::delscreen(screen) }
}

/// Deletes the named window, freeing all memory associated with it
/// (it does not actually erase the window's screen image). Sub-windows
/// must be deleted before the main window can be deleted.
pub fn delwin(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::delwin(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("delwin", rc))
    }
}

/// An abbreviation for “derive window”, `derwin()` is the same as calling `subwin()`,
/// except that `origin` are relative to the origin of the window, rather than
/// relative to the entire screen. Return a window object for the derived window.
pub fn derwin(orig: WINDOW, size: Size, origin: Origin) -> result!(WINDOW) {
    unsafe { ncurses::derwin(orig, size.lines, size.columns, origin.y, origin.x).ok_or(ncurses_function_error!("derwin")) }
}

/// Update the physical screen. The NCurses library keeps two data structures,
/// one representing the current physical screen contents and a virtual screen
/// representing the desired next state. The doupdate() ground updates the
/// physical screen to match the virtual screen.
///
/// The virtual screen may be updated by a `noutrefresh()` call after write
/// operations such as `addstr()` have been performed on a window. The normal
/// `refresh()` call is simply `noutrefresh()` followed by `doupdate()`; if
/// you have to update multiple windows, you can speed performance and perhaps
/// reduce screen flicker by issuing `noutrefresh()` calls on all windows,
/// followed by a single `doupdate()`.
pub fn doupdate() -> result!(()) {
    match ncurses::doupdate() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("doupdate", rc))
    }
}

/// Creates an exact duplicate of the window `handle`.
pub fn dupwin(handle: WINDOW) -> result!(WINDOW) {
    unsafe { ncurses::dupwin(handle).ok_or(ncurses_function_error!("dupwin")) }
}

/// Enter echo mode. In echo mode, each character input is echoed to the screen
/// as it is entered.
pub fn echo() -> result!(()) {
    match ncurses::echo() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("echo", rc))
    }
}

/// Equivalent of `wecho_wchar()` using `stdscr()` as window `handle`.
pub fn echo_wchar(wch: ComplexChar) -> result!(()) {
    match ncurses::echo_wchar(&ComplexChar::into(wch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("echo_wchar", rc))
    }
}

/// Equivalent of `wechochar()` using `stdscr()` as window `handle`.
pub fn echochar(ch: ChtypeChar) -> result!(()) {
    match ncurses::echochar(ChtypeChar::into(ch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("echochar", rc))
    }
}

/// De-initialize the library, and return terminal to normal status.
pub fn endwin() -> result!(()) {
    match ncurses::endwin() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("endwin", rc))
    }
}

/// Equivalent of `werase()` using `stdscr()` as window `handle`.
pub fn erase() -> result!(()) {
    match ncurses::erase() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("erase", rc))
    }
}

/// Return the user’s current erase character as a one-byte bytes object.
/// Under Unix operating systems this is a property of the controlling
/// tty of the NCurses program, and is not set by the NCurses library itself.
pub fn erasechar() -> result!(char) {
    let rc = ncurses::erasechar();

    if rc.is_negative() {
        Err(ncurses_function_error_with_rc!("erasechar", i32::from(rc)))
    } else {
        Ok(char::from(u8::try_from(rc)?))
    }
}

/// Returns the current erase character as a wide character.
pub fn erasewchar() -> result!(WideChar) {
    let mut wch: [wchar_t; 1] = [0];

    match unsafe { ncurses::erasewchar(wch.as_mut_ptr()) } {
        OK => Ok(WideChar::from(wch[0])),
        rc => Err(ncurses_function_error_with_rc!("erasewchar", rc))
    }
}

#[deprecated(since = "0.4.0", note = "Use extend::Color::rgb() or shims::ncurses::extended_color_content() instead")]
/// The extended color version of the `color_content()` routine.
pub fn extended_color_content(color_number: i32) -> result!(extend::RGB) {
    let mut r: [i32; 1] = [0];
    let mut g: [i32; 1] = [0];
    let mut b: [i32; 1] = [0];

    match unsafe { ncurses::extended_color_content(color_number, r.as_mut_ptr(), g.as_mut_ptr(), b.as_mut_ptr()) } {
        OK => Ok(extend::RGB::new(r[0], g[0], b[0])),
        rc => Err(ncurses_function_error_with_rc!("extended_color_content", rc))
    }
}

#[deprecated(since = "0.4.0", note = "Use extend::ColorPair::colors() or shims::ncurses::extended_pair_content() instead")]
/// The extended color version of the `pair_content()` routine.
pub fn extended_pair_content(color_pair: i32) -> result!(extend::Colors) {
    let mut fg: [i32; 1] = [0];
    let mut bg: [i32; 1] = [0];

    match unsafe { ncurses::extended_pair_content(color_pair, fg.as_mut_ptr(), bg.as_mut_ptr()) } {
        OK => Ok(extend::Colors::new(extend::Color::_from(None, extend::ColorPalette::_from(fg[0])), extend::Color::_from(None, extend::ColorPalette::_from(bg[0])))),
        rc => Err(ncurses_function_error_with_rc!("extended_pair_content", rc))
    }
}

/// The extended color version of the `slk_color()` routine.
pub fn extended_slk_color(color_pair: extend::ColorPair) -> result!(()) {
    match ncurses::extended_slk_color(color_pair.number()) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("extended_slk_color", rc))
    }
}

/// The `filter()` routine, if used, must be called before `initscr()` is
/// called. The effect is that, during those calls, `LINES` is set to 1;
/// the capabilities clear, cup, cud, cud1, cuu1, cuu, vpa are disabled;
/// and the home string is set to the value of cr. The effect is that the
/// cursor is confined to the current line, and so are screen updates.
/// This may be used for enabling character-at-a-time line editing without
/// touching the rest of the screen.
pub fn filter() {
    ncurses::filter()
}

/// Flash the screen. That is, change it to reverse-video and then change
/// it back in a short interval. Some people prefer such as ‘visible bell’
/// to the audible attention signal produced by `beep()`.
pub fn flash() -> result!(()) {
    match ncurses::flash() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("flash", rc))
    }
}

/// Flush all input buffers. This throws away any typeahead that has been
/// typed by the user and has not yet been processed by the program.
pub fn flushinp() -> result!(()) {
    match ncurses::flushinp() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("flushinp", rc))
    }
}

#[deprecated(since = "0.1.3", note = "use with caution as the specified color_pair must go out of scope before reuse of it's color pair number otherwise the color pair will default to terminal default foreground and backgound colors.")]
/// Marks the given color pair as unused, i.e., like color pair 0.
pub fn free_pair<P, T>(color_pair: P) -> result!(())
    where P:   ColorPairType<T>,
          i32: From<T>,
          T:   ColorAttributeTypes
{
    match ncurses::free_pair(i32::from(color_pair.number())) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("free_pair", rc))
    }
}

/// Returns the escape delay.
pub fn get_escdelay() -> result!(time::Duration) {
    Ok(time::Duration::from_millis(u64::try_from(ncurses::get_escdelay())?))
}

/// Equivalent of `wget_wch()` using `stdscr()` as window `handle`.
pub fn get_wch() -> result!(CharacterResult<WideChar>) {
    let mut wch: [wint_t; 1] = [0];

    match unsafe { ncurses::get_wch(wch.as_mut_ptr()) } {
        EINTR        => Err(NCurseswError::InterruptedCall),
        #[cfg(feature = "key_resize_as_error")]
        KEY_RESIZE   => Err(NCurseswError::KeyResize),
        KEY_CODE_YES => {
            match i32::try_from(wch[0])? {
                #[cfg(feature = "key_resize_as_error")]
                KEY_RESIZE => Err(NCurseswError::KeyResize),
                _          => Ok(CharacterResult::Key(KeyBinding::try_from(wch[0])?))
            }
        },
        rc           => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("get_wch", rc))
            } else {
                Ok(CharacterResult::Character(WideChar::from(wch[0])))
            }
        }
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use getn_wstr() instead")]
/// Equivalent of `wget_wstr()` using `stdscr()` as window `handle`.
pub fn get_wstr() -> result!(WideString) {
    let mut buf: [wint_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wint_t = buf.as_mut_ptr();

    match unsafe { ncurses::get_wstr(ptr) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("get_wstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}get_wstr() : ptr.is_null()", MODULE_PATH);

                let buf_as_bytes = unsafe { slice::from_raw_parts(ptr as *mut wchar_t, LINE_MAX) };

                for (idx, &byte) in buf_as_bytes.iter().enumerate() {
                    if byte == 0x00 {
                        return Ok(WideString::from(&buf_as_bytes[..idx]));
                    }
                }

                Ok(WideString::from(buf_as_bytes))
            }
        }
    }
}

/// Returns the same attribute data as `wattr_get()`. However, `getattrs()`
/// internally returns an integer (actually a chtype), while `wattr_get()`
/// returns the current color pair in a separate parameter. In the
/// wide-character library configuration, color pairs may not fit into
/// a chtype, so `wattr_get()` is the only way to obtain the color information.
pub fn getattrs(handle: WINDOW) -> normal::Attributes {
    normal::Attributes::_from(None, unsafe { ncurses::getattrs(handle) as attr_t })
}

/// Return a `x` of co-ordinates of upper-left corner.
pub fn getbegx(handle: WINDOW) -> result!(i32) {
    let x = unsafe { ncurses::getbegx(handle) };

    if x.is_negative() {
        Err(ncurses_function_error_with_rc!("getbegx", x))
    } else {
        Ok(x)
    }
}

/// Return a `y` of co-ordinates of upper-left corner.
pub fn getbegy(handle: WINDOW) -> result!(i32) {
    let y = unsafe { ncurses::getbegy(handle) };

    if y.is_negative() {
        Err(ncurses_function_error_with_rc!("getbegy", y))
    } else {
        Ok(y)
    }
}

/// Return a `origin` of co-ordinates of upper-left corner.
pub fn getbegyx(handle: WINDOW) -> result!(Origin) {
    let y = unsafe { ncurses::getbegy(handle) };
    let x = unsafe { ncurses::getbegx(handle) };

    if y.is_negative() {
        Err(ncurses_function_error_with_rc!("getbegyx (y)", y))
    } else if x.is_negative() {
        Err(ncurses_function_error_with_rc!("getbegyx (x)", x))
    } else {
        Ok(Origin { y, x })
    }
}

/// Return the given window’s current background character (with rendition).
pub fn getbkgd(handle: WINDOW) -> ChtypeChar {
    ChtypeChar::from(unsafe { ncurses::getbkgd(handle) })
}

/// Equivalent of `wgetbkgrnd()` using `stdscr()` as window `handle`.
pub fn getbkgrnd() -> result!(ComplexChar) {
    let mut wch: [cchar_t; 1] = unsafe { mem::zeroed() };

    match unsafe { ncurses::getbkgrnd(wch.as_mut_ptr()) } {
        OK => Ok(ComplexChar::from(wch[0])),
        rc => Err(ncurses_function_error_with_rc!("getbkgrnd", rc))
    }
}

/// Get a widecharacter string and rendition from a complex character.
pub fn getcchar(wcval: ComplexChar) -> result!(WideCharAndAttributes) {
    let mut wch: [wchar_t; bindings::CCHARW_MAX as usize] = [0; bindings::CCHARW_MAX as usize];
    let mut attrs: [attr_t; 1] = [0];
    let mut color_pair: [short_t; 1] = [0];
    let opts: *mut i32 = ptr::null_mut();

    let attribute_colorpair_set = |attrs: attr_t, color_pair: short_t, ext_color_pair: i32| -> AttributesColorPairSet {
        match ncurses_colortype() {
            NCursesColorType::Normal   => {
                AttributesColorPairSet::Normal(
                    normal::AttributesColorPair::new(
                        normal::Attributes::_from(None, attrs),
                        normal::ColorPair::_from(None, color_pair)
                    )
                )
            },
            NCursesColorType::Extend => {
                AttributesColorPairSet::Extend(
                    extend::AttributesColorPair::new(
                        extend::Attributes::_from(None, attrs),
                        extend::ColorPair::_from(None, ext_color_pair)
                    )
                )
            }
        }
    };

    match unsafe { ncurses::getcchar(&ComplexChar::into(wcval), wch.as_mut_ptr(), attrs.as_mut_ptr(), color_pair.as_mut_ptr(), opts) } {
        OK => {
            // TODO : get opts working correct so not to rely on bodge!
            //assert!(!opts.is_null(), "{}getcchar() : opts.is_null()", MODULE_PATH);
            //
            //Ok(WideCharAndAttributes::new(WideChar::from(wch[0]), attribute_colorpair_set(attrs[0], color_pair[0], unsafe { ptr::read(opts) })))

            let c: cchar_t = ComplexChar::into(wcval); // bodge to get extended color pair.

            Ok(WideCharAndAttributes::new(WideChar::from(wch[0]), attribute_colorpair_set(attrs[0], color_pair[0], c.ext_color)))
        },
        rc => Err(ncurses_function_error_with_rc!("getcchar", rc))
    }
}

/// Equivalent of `wgetch()` using `stdscr()` as window `handle`.
pub fn getch() -> result!(CharacterResult<char>) {
    match ncurses::getch() {
        EINTR      => Err(NCurseswError::InterruptedCall),
        #[cfg(feature = "key_resize_as_error")]
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("getch", rc))
            } else if (KEY_MIN..=KEY_MAX).contains(&rc) {
                Ok(CharacterResult::Key(KeyBinding::from(rc)))
            } else {
                Ok(CharacterResult::Character(char::from(u8::try_from(i8::try_from(rc)?)?)))
            }
        }
    }
}

/// Return the `x` coordinate of the current cursor position.
pub fn getcurx(handle: WINDOW) -> result!(i32) {
    let x = unsafe { ncurses::getcurx(handle) };

    if x.is_negative() {
        Err(ncurses_function_error_with_rc!("getcurx", x))
    } else {
        Ok(x)
    }
}

/// Return the `y` coordinate of the current cursor position.
pub fn getcury(handle: WINDOW) -> result!(i32) {
    let y = unsafe { ncurses::getcury(handle) };

    if y.is_negative() {
        Err(ncurses_function_error_with_rc!("getcury", y))
    } else {
        Ok(y)
    }
}

/// Return the `origin` coordinates of the current cursor position.
pub fn getcuryx(handle: WINDOW) -> result!(Origin) {
    Ok(Origin { y: getcury(handle)?, x: getcurx(handle)? })
}

/// Return the height of the window.
pub fn getmaxx(handle: WINDOW) -> result!(i32) {
    let x = unsafe { ncurses::getmaxx(handle) };

    if x.is_negative() {
        Err(ncurses_function_error_with_rc!("getmaxx", x))
    } else {
        Ok(x)
    }
}

/// Return the width of the window.
pub fn getmaxy(handle: WINDOW) -> result!(i32) {
    let y = unsafe { ncurses::getmaxy(handle) };

    if y.is_negative() {
        Err(ncurses_function_error_with_rc!("getmaxy", y))
    } else {
        Ok(y)
    }
}

/// Return the height and width of the window.
pub fn getmaxyx(handle: WINDOW) -> result!(Size) {
    Ok(Size { lines: getmaxy(handle)?, columns: getmaxx(handle)? })
}

/// Equivalent of `wgetn_wstr()` using `stdscr()` as window `handle`.
pub fn getn_wstr(number: i32) -> result!(WideString) {
    assert!(number <= LINE_MAX as i32, "{}getn_wstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [wint_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wint_t = buf.as_mut_ptr();

    match unsafe { ncurses::getn_wstr(ptr, number) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("getn_wstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}getn_wstr() : ptr.is_null()", MODULE_PATH);

                let buf_as_bytes = unsafe { slice::from_raw_parts(ptr as *mut wchar_t, LINE_MAX) };

                for (idx, &byte) in buf_as_bytes.iter().enumerate() {
                    if byte == 0x00 {
                        return Ok(WideString::from(&buf_as_bytes[..idx]));
                    }
                }

                Ok(WideString::from(buf_as_bytes))
            }
        }
    }
}

/// Equivalent of `wgetnstr()` using `stdscr()` as window `handle`.
pub fn getnstr(number: i32) -> result!(String) {
    assert!(number <= LINE_MAX as i32, "{}getnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    match unsafe { ncurses::getnstr(ptr, number) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("getnstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}getnstr() : ptr.is_null()", MODULE_PATH);

                Ok(unsafe { FromCStr::from_c_str(ptr) })
            }
        }
    }
}

/// Return the `x` coordinate of this window relative to its parent window.
pub fn getparx(handle: WINDOW) -> result!(i32) {
    let x = unsafe { ncurses::getparx(handle) };

    if x.is_negative() {
        Err(ncurses_function_error_with_rc!("getparx", x))
    } else {
        Ok(x)
    }
}

/// Return the `y` coordinate of this window relative to its parent window.
pub fn getpary(handle: WINDOW) -> result!(i32) {
    let y = unsafe { ncurses::getpary(handle) };

    if y.is_negative() {
        Err(ncurses_function_error_with_rc!("getpary", y))
    } else {
        Ok(y)
    }
}

/// Return the beginning coordinates of this window relative to its parent window.
pub fn getparyx(handle: WINDOW) -> result!(Origin) {
    Ok(Origin { y: getpary(handle)?, x: getparx(handle)? })
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use getnstr() instead")]
/// Equivalent of `wgetstr()` using `stdscr()` as window `handle`.
pub fn getstr() -> result!(String) {
    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    match unsafe { ncurses::getstr(ptr) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("getstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}getstr() : ptr.is_null()", MODULE_PATH);

                Ok(unsafe { FromCStr::from_c_str(ptr) })
            }
        }
    }
}

/// Return the current coordinates of the virtual screen cursor.
/// If `leaveok()` is currently `true`, then return `None`.
pub fn getsyx() -> result!(Option<Origin>) {
    if is_leaveok(newscr()) {
        Ok(None)
    } else {
        Ok(Some(getcuryx(newscr())?))
    }
}

/// Read window related data stored in the file by an earlier `putwin()` call.
/// The routine then creates and initializes a new window using that data,
/// returning the new window object.
pub fn getwin<I: AsRawFd + Read>(file: &I) -> result!(WINDOW) {
    unsafe { ncurses::getwin(fdopen(file, "r")?).ok_or(ncurses_function_error!("getwin")) }
}

/// Used for half-delay mode, which is similar to cbreak mode in that characters
/// typed by the user are immediately available to the program. However, after
/// blocking for tenths tenths of seconds, raise an exception if nothing has
/// been typed. The value of tenths must be a number between 1 and 255.
/// Use `nocbreak()` to leave half-delay mode.
pub fn halfdelay(tenths: time::Duration) -> result!(()) {
    match ncurses::halfdelay(i32::try_from(tenths.as_secs())? / 10) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("halfdelay", rc))
    }
}

/// Return `true` if the terminal can display colors; otherwise, return `false`.
pub fn has_colors() -> bool {
    ncurses::has_colors()
}

/// Return `true` if the terminal has insert- and delete-character capabilities.
/// This function is included for historical reasons only, as all modern
/// software terminal emulators have such capabilities.
pub fn has_ic() -> bool {
    ncurses::has_ic()
}

/// Return `true` if the terminal has insert- and delete-line capabilities,
/// or can simulate them using scrolling regions. This function is included
/// for historical reasons only, as all modern software terminal emulators
/// have such capabilities.
pub fn has_il() -> bool {
    ncurses::has_il()
}

/// Take a key value `ch`, and return `true` if the current terminal type
/// recognizes a key with that value.
pub fn has_key(ch: KeyBinding) -> bool {
    ncurses::has_key(KeyBinding::into(ch)) == TRUE
}

/// Equivalent of `whline()` using `stdscr()` as window `handle`.
pub fn hline(ch: ChtypeChar, number: i32) -> result!(()) {
    match ncurses::hline(ChtypeChar::into(ch), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("hline", rc))
    }
}

/// Equivalent of `whline_set()` using `stdscr()` as window `handle`.
pub fn hline_set(wch: ComplexChar, number: i32) -> result!(()) {
    match ncurses::hline_set(&ComplexChar::into(wch), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("hline_set", rc))
    }
}

/// If flag is `false`, NCurses no longer considers using the hardware
/// insert/delete character feature of the terminal; if flag is `true`, use
/// of character insertion and deletion is enabled. When NCurses is first
/// initialized, use of character insert/delete is enabled by default.
pub fn idcok(handle: WINDOW, flag: bool) {
    unsafe { ncurses::idcok(handle, flag) }
}

/// If flag is `true`, NCurses will try and use hardware line editing facilities.
/// Otherwise, line insertion/deletion are disabled.
pub fn idlok(handle: WINDOW, flag: bool) -> result!(()) {
    match unsafe { ncurses::idlok(handle, flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("idlok", rc))
    }
}

/// If flag is `true`, any change in the window image automatically causes the
/// window to be refreshed; you no longer have to call `refresh()` yourself.
/// However, it may degrade performance considerably, due to repeated calls
/// to wrefresh. This option is disabled by default.
pub fn immedok(handle: WINDOW, flag: bool) {
    unsafe { ncurses::immedok(handle, flag) }
}

/// Equivalent of `win_wch()` using `stdscr()` as window `handle`.
pub fn in_wch() -> result!(ComplexChar) {
    let mut wcval: [cchar_t; 1] = unsafe { mem::zeroed() };

    match unsafe { ncurses::in_wch(wcval.as_mut_ptr()) } {
        OK => Ok(ComplexChar::from(wcval[0])),
        rc => Err(ncurses_function_error_with_rc!("in_wch", rc))
    }
}

/// Equivalent of `win_wchnstr()` using `stdscr()` as window `handle`.
pub fn in_wchnstr(number: i32) -> result!(ComplexString) {
    assert!(number <= LINE_MAX as i32, "{}in_wchnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [cchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut cchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::in_wchnstr(ptr, number) } {
        OK => {
            assert!(!ptr.is_null(), "{}in_wchnstr() : ptr.is_null()", MODULE_PATH);

            Ok(ComplexString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(number)?) }))
        },
        rc => Err(ncurses_function_error_with_rc!("in_wchnstr", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use in_wchnstr() instead")]
/// Equivalent of `win_wchstr()` using `stdscr()` as window `handle`.
pub fn in_wchstr() -> result!(ComplexString) {
    let mut buf: [cchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut cchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::in_wchstr(ptr) } {
        OK => {
            assert!(!ptr.is_null(), "{}in_wchstr() : ptr.is_null()", MODULE_PATH);

            Ok(ComplexString::from(unsafe { slice::from_raw_parts(ptr, LINE_MAX) }))
        },
        rc => Err(ncurses_function_error_with_rc!("in_wchstr", rc))
    }
}

/// Equivalent of `winch()` using `stdscr()` as window `handle`.
pub fn inch() -> ChtypeChar {
    ChtypeChar::from(ncurses::inch())
}

/// Equivalent of `winchnstr()` using `stdscr()` as window `handle`.
pub fn inchnstr(number: i32) -> result!(ChtypeString) {
    assert!(number <= LINE_MAX as i32, "{}inchnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [chtype; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut chtype = buf.as_mut_ptr();

    let len = unsafe { ncurses::inchnstr(ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("inchnstr", len))
    } else {
        assert!(!ptr.is_null(), "{}inchnstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}inchnstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(ChtypeString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use inchnstr() instead")]
/// Equivalent of `winchstr()` using `stdscr()` as window `handle`.
pub fn inchstr() -> result!(ChtypeString) {
    let mut buf: [chtype; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut chtype = buf.as_mut_ptr();

    let len = unsafe { ncurses::inchstr(ptr) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("inchstr", len))
    } else {
        assert!(!ptr.is_null(), "{}inchstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}inchstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(ChtypeString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

#[deprecated(since = "0.4.0", note = "Use normal::Color::set_rgb() or shims::ncurses::init_color() instead")]
/// Change the definition of a color, taking the number of the color to be
/// changed followed by three RGB values (for the amounts of red, green,
/// and blue components). The value of color_number must be between 0 and
/// COLORS. Each of r, g, b, must be a value between 0 and 1000. When
/// `init_color()` is used, all occurrences of that color on the screen
/// immediately change to the new definition. This function is a no-op on
/// most terminals; it is active only if `can_change_color()` returns `true`.
pub fn init_color(color_number: short_t, rgb: normal::RGB) -> result!(()) {
    if i32::from(color_number) >= COLORS() {
        Err(NCurseswError::ColorLimit)
    } else {
        match ncurses::init_color(color_number, rgb.red(), rgb.green(), rgb.blue()) {
            OK => {
                set_ncurses_colortype(NCursesColorType::Normal);

                Ok(())
            },
            rc => Err(ncurses_function_error_with_rc!("init_color", rc))
        }
    }
}

#[deprecated(since = "0.4.0", note = "Use extend::Color::set_rgb() or shims::ncurses::init_extended_color() instead")]
/// The extended color version of the `init_color()` routine.
pub fn init_extended_color(color_number: i32, rgb: extend::RGB) -> result!(()) {
    if color_number >= COLORS() {
        Err(NCurseswError::ColorLimit)
    } else {
        match ncurses::init_extended_color(color_number, rgb.red(), rgb.green(), rgb.blue()) {
            OK => {
                set_ncurses_colortype(NCursesColorType::Extend);

                Ok(())
            },
            rc => Err(ncurses_function_error_with_rc!("init_extended_color", rc))
        }
    }
}

#[deprecated(since = "0.4.0", note = "Use extend::ColorPair::new() or shims::ncurses::init_extended_pair() instead")]
/// The extended color version of the `init_pair()` routine.
pub fn init_extended_pair(color_pair: i32, colors: extend::Colors) -> result!(extend::ColorPair) {
    if color_pair < 1 || color_pair >= COLOR_PAIRS() {
        Err(NCurseswError::ColorPairLimit)
    } else if colors.foreground().number() >= COLORS() || colors.background().number() >= COLORS() {
        Err(NCurseswError::ColorLimit)
    } else {
        match ncurses::init_extended_pair(color_pair, colors.foreground().number(), colors.background().number()) {
            OK => Ok(extend::ColorPair::_from(None, color_pair)),
            rc => Err(ncurses_function_error_with_rc!("init_extended_pair", rc))
        }
    }
}

#[deprecated(since = "0.4.0", note = "Use normal::ColorPair::new() or shims::ncurses::init_pair() instead")]
/// Change the definition of a color-pair. It takes two arguments: the number
/// of the color-pair to be changed, and the foreground and background colors.
/// The value of color_pair must be between 1 and COLOR_PAIRS - 1 (the 0 color
/// pair is wired to white on black and cannot be changed).
/// If the color-pair was previously initialized, the screen is refreshed and
/// all occurrences of that color-pair are changed to the new definition.
pub fn init_pair(color_pair: short_t, colors: normal::Colors) -> result!(normal::ColorPair) {
    if color_pair < 1 || i32::from(color_pair) >= COLOR_PAIRS() {
        Err(NCurseswError::ColorPairLimit)
    } else if colors.foreground().number() >= COLORS() || colors.background().number() >= COLORS() {
        Err(NCurseswError::ColorLimit)
    } else {
        match ncurses::init_pair(color_pair, short_t::try_from(colors.foreground().number())?, short_t::try_from(colors.background().number())?) {
            OK => Ok(normal::ColorPair::_from(None, color_pair)),
            rc => Err(ncurses_function_error_with_rc!("init_pair", rc))
        }
    }
}

/// Initialize the NCurses data structures and return the standard screen.
///
/// `initscr()` is normally the first NCurses routine to call when initializing
/// a program. A few special routines sometimes need to be called before it; these
/// are `slk_init()`, `filter()`, `ripoffline()`, `use_env()`.  For multiple-terminal
/// applications, `newterm()` may be called before `initscr()`.
///
/// The `initscr()` code determines the terminal type and initializes all NCurses data
/// structures. `initscr()` also causes the first call to `refresh()` to clear the
/// screen. If errors occur, `initscr()` writes an appropriate error message to
/// standard error and exits; otherwise, a pointer is returned to `stdscr()`.
pub fn initscr() -> result!(WINDOW) {
    unsafe { ncurses::initscr().ok_or(ncurses_function_error!("initscr")) }
}

/// Equivalent of `winnstr()` using `stdscr()` as window `handle`.
pub fn innstr(number: i32) -> result!(String) {
    assert!(number <= LINE_MAX as i32, "{}innstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    let len = unsafe { ncurses::innstr(ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("innstr", len))
    } else {
        assert!(!ptr.is_null(), "{}innstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}innstr() : len={}, LINEMAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(unsafe { FromCStr::from_c_str(ptr) })
    }
}

/// Equivalent of `winnwstr()` using `stdscr()` as window `handle`.
pub fn innwstr(number: i32) -> result!(WideString) {
    assert!(number <= LINE_MAX as i32, "{}innwstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [wchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wchar_t = buf.as_mut_ptr();

    let len = unsafe { ncurses::innwstr(ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("innwstr", len))
    } else {
        assert!(!ptr.is_null(), "{}innwstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}innwstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(WideString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

/// Equivalent of `ins_nwstr()` using `stdscr()` as window `handle`.
pub fn ins_nwstr(wstr: &WideString, number: i32) -> result!(()) {
    match ncurses::ins_nwstr(raw_with_nul_as_slice!(wstr), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("ins_nwstr", rc))
    }
}

/// Equivalent of `ins_wch()` using `stdscr()` as window `handle`.
pub fn ins_wch(wch: ComplexChar) -> result!(()) {
    match ncurses::ins_wch(&ComplexChar::into(wch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("ins_wch", rc))
    }
}

/// Equivalent of `ins_wstr()` using `stdscr()` as window `handle`.
pub fn ins_wstr(wstr: &WideString) -> result!(()) {
    match ncurses::ins_wstr(raw_with_nul_as_slice!(wstr)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("ins_wstr", rc))
    }
}

/// Equivalent of `insch()` using `stdscr()` as window `handle`.
pub fn insch(ch: ChtypeChar) -> result!(()) {
    match ncurses::insch(ChtypeChar::into(ch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("insch", rc))
    }
}

/// Equivalent of `insdelln()` using `stdscr()` as window `handle`.
pub fn insdelln(n: i32) -> result!(()) {
    match ncurses::insdelln(n) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("insdelln", rc))
    }
}

/// Equivalent of `insertln()` using `stdscr()` as window `handle`.
pub fn insertln() -> result!(()) {
    match ncurses::insertln() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("insertln", rc))
    }
}

/// Equivalent of `insnstr()` using `stdscr()` as window `handle`.
pub fn insnstr<S: Into<String>>(str: S, number: i32) -> result!(()) {
    let str = str.into().to_string();

    match ncurses::insnstr(unsafe { c_str_with_nul!(str) }, number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("insnstr", rc))
    }
}

/// Equivalent of `insstr()` using `stdscr()` as window `handle`.
pub fn insstr<S: Into<String>>(str: S) -> result!(()) {
    let str = str.into().to_string();

    match ncurses::insstr(unsafe { c_str_with_nul!(str) }) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("insstr", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use innstr() instead")]
/// Equivalent of `instr()` using `stdscr()` as window `handle`.
pub fn instr() -> result!(String) {
    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    let len = unsafe { ncurses::instr(ptr) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("instr", len))
    } else {
        assert!(!ptr.is_null(), "{}instr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}instr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(unsafe { FromCStr::from_c_str(ptr) })
    }
}

/// If the `intrflush()` option is enabled (`flag` is `true`), and an interrupt
/// key is pressed on the keyboard (interrupt, break, quit), all output in the
/// tty driver queue will be flushed, giving the effect of faster response to
/// the interrupt, but causing NCurses to have the wrong idea of what is on the
/// screen. Disabling the option (`flag` is `false`) prevents the flush.
/// The default for the option is inherited from the tty driver settings.
pub fn intrflush(flag: bool) -> result!(()) {
    match unsafe { ncurses::intrflush(ptr::null_mut(), flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("intrflush", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use innwstr() instead")]
/// Equivalent of `inwstr()` using `stdscr()` as window `handle`.
pub fn inwstr() -> result!(WideString) {
    let mut buf: [wchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::inwstr(ptr) } {
        OK => {
            assert!(!ptr.is_null(), "{}inwstr() : ptr.is_null()", MODULE_PATH);

            Ok(WideString::from(unsafe { slice::from_raw_parts(ptr, LINE_MAX) }))
        },
        rc => Err(ncurses_function_error_with_rc!("inwstr", rc))
    }
}

/// Returns the value set in `clearok()`.
pub fn is_cleared(handle: WINDOW) -> bool {
    unsafe { ncurses::is_cleared(handle) }
}

/// Returns the value set in `idcok()`.
pub fn is_idcok(handle: WINDOW) -> bool {
    unsafe { ncurses::is_idcok(handle) }
}

/// Returns the value set in `idlok()`.
pub fn is_idlok(handle: WINDOW) -> bool {
    unsafe { ncurses::is_idlok(handle) }
}

/// Returns the value set in `immedok()`.
pub fn is_immedok(handle: WINDOW) -> bool {
    unsafe { ncurses::is_immedok(handle) }
}

/// Returns the value set in `keypad()`.
pub fn is_keypad(handle: WINDOW) -> bool {
    unsafe { ncurses::is_keypad(handle) }
}

/// Returns the value set in `leaveok()`.
pub fn is_leaveok(handle: WINDOW) -> bool {
    unsafe { ncurses::is_leaveok(handle) }
}

/// Return `true` if the specified line was modified since the last call to
/// `refresh()`; otherwise return `false`.
pub fn is_linetouched(handle: WINDOW, line: i32) -> bool {
    unsafe { ncurses::is_linetouched(handle, line) }
}

/// Returns the value set in `nodelay()`.
pub fn is_nodelay(handle: WINDOW) -> bool {
    unsafe { ncurses::is_nodelay(handle) }
}

/// Returns the value set in `notimeout()`.
pub fn is_notimeout(handle: WINDOW) -> bool {
    unsafe { ncurses::is_notimeout(handle) }
}

/// Returns `true` if the window is a pad i.e., created by `newpad()`.
pub fn is_pad(handle: WINDOW) -> bool {
    unsafe { ncurses::is_pad(handle) }
}

/// Returns the value set in `scrollok()`.
pub fn is_scrollok(handle: WINDOW) -> bool {
    unsafe { ncurses::is_scrollok(handle) }
}

/// Returns `true` if the window is a sub-window, i.e., created by
/// `subwin()` or `derwin()`.
pub fn is_subwin(handle: WINDOW) -> bool {
    unsafe { ncurses::is_subwin(handle) }
}

/// Returns the value set in `syncok()`.
pub fn is_syncok(handle: WINDOW) -> bool {
    unsafe { ncurses::is_syncok(handle) }
}

/// Return `true` if `resize_term()` would modify the window structure,
/// `false` otherwise.
pub fn is_term_resized(size: Size) -> bool {
    ncurses::is_term_resized(size.lines, size.columns)
}

/// Return `true` if the specified window was modified since the last call
/// to `refresh()`; otherwise return `false`.
pub fn is_wintouched(handle: WINDOW) -> bool {
    unsafe { ncurses::is_wintouched(handle) }
}

/// Return `true` if `endwin()` has been called (that is, the
/// NCurses library has been deinitialized).
pub fn isendwin() -> bool {
    ncurses::isendwin()
}

/// Permits an application to determine if a string represented
/// as individual bytes is currently bound to any `KeyBindind`.
pub fn key_defined<S: Into<String>>(definition: S) -> result!(Option<KeyBinding>) {
    let definition = definition.into().to_string();

    let rc = ncurses::key_defined(unsafe { c_str_with_nul!(definition) });

    if rc.is_negative() {
        Err(ncurses_function_error_with_rc!("key_defined", rc))
    } else if rc == 0 {
        Ok(None)
    } else {
        Ok(Some(KeyBinding::from(rc)))
    }
}

/// Returns a string corresponding to a given `KeyBinding`.
pub fn key_name(wch: WideChar) -> Option<String> {
    ncurses::key_name(WideChar::into(wch))
}

/// Permits an application to determine the string which is defined
/// in the terminfo for specific keycodes.
pub fn keybound(keycode: KeyBinding, count: i32) -> Option<String> {
    ncurses::keybound(KeyBinding::into(keycode), count)
}

/// Return the name of the key binding c. The name of a key generating
/// printable ASCII character is the key’s character. The name of a
/// control-key combination is a two-byte bytes object consisting of a
/// caret (b'^') followed by the corresponding printable ASCII character.
/// The name of an alt-key combination (128–255) is a bytes object
/// consisting of the prefix b'M-' followed by the name of the
/// corresponding ASCII character.
pub fn keyname(c: KeyBinding) -> result!(String) {
    ncurses::keyname(KeyBinding::into(c)).ok_or(ncurses_function_error!("keyname"))
}

/// Permits an application to disable specific `KeyBinding`, rather than use
/// the keypad function to disable all keycodes. Keys that have been disabled
/// can be re-enabled.
pub fn keyok(keycode: KeyBinding, enable: bool) -> result!(()) {
    match ncurses::keyok(KeyBinding::into(keycode), enable) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("keyok", rc))
    }
}

/// If flag is `true`, escape sequences generated by some keys (keypad, function keys)
/// will be interpreted by NCurses. If flag is `false`, escape sequences will be left
/// as is in the input stream.
pub fn keypad(handle: WINDOW, flag: bool) -> result!(()) {
    match unsafe { ncurses::keypad(handle, flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("keypad", rc))
    }
}

/// Return the user’s current line kill character. Under Unix operating
/// systems this is a property of the controlling tty of the NCurses
/// program, and is not set by the NCurses library itself.
pub fn killchar() -> result!(char) {
    let rc = ncurses::killchar();

    if rc.is_negative() {
        Err(ncurses_function_error_with_rc!("killchar", i32::from(rc)))
    } else {
        Ok(char::from(u8::try_from(rc)?))
    }
}

/// Return the user’s current line kill character as a wide character.
/// Under Unix operating systems this is a property of the controlling
/// tty of the NCurses program, and is not set by the NCurses library itself.
pub fn killwchar() -> result!(WideChar) {
    let mut wch: [wchar_t; 1] = [0];

    match unsafe { ncurses::killwchar(wch.as_mut_ptr()) } {
        OK => Ok(WideChar::from(wch[0])),
        rc => Err(ncurses_function_error_with_rc!("killwchar", rc))
    }
}

/// If flag is `true`, cursor is left where it is on update, instead of being
/// at “cursor position.” This reduces cursor movement where possible.
/// If possible the cursor will be made invisible.
///
/// If flag is `false`, cursor will always be at “cursor position” after an update.
pub fn leaveok(handle: WINDOW, flag: bool) -> result!(()) {
    match unsafe { ncurses::leaveok(handle, flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("leaveok", rc))
    }
}

/// Return the terminfo long name field describing the current terminal.
/// The maximum length of a verbose description is 128 characters.
/// It is defined only after the call to `initscr()`.
pub fn longname() -> result!(String) {
    ncurses::longname().ok_or(ncurses_function_error!("longname"))
}

/// Ship binary data to printer. Returns the number of characters
/// actually sent to the printer.
///
/// This function uses the mc5p or mc4 and mc5 capabilities, if they are
/// present, to ship given data to a printer attached to the terminal.
///
/// Note that the `mcprint()` code has no way to do flow control with the
/// printer or to know how much buffering it has. Your application is
/// responsible for keeping the rate of writes to the printer below its
/// continuous throughput rate (typically about half of its nominal cps
/// rating). Dot-matrix printers and 6-page-per-minute lasers can typically
/// handle 80cps, so a good conservative rule of thumb is to sleep for a
/// second after shipping each 80-character line.
pub fn mcprint(data: &[i8], len: i32) -> result!(i32) {
    match unsafe { ncurses::mcprint(data.as_ptr() as *mut i8, len) } {
        ERR => Err(ncurses_os_error!("mcprint")),
        rc  => Ok(rc)
    }
}

/// If flag is `true`, allow 8-bit characters to be input. If flag is
/// `false`, allow only 7-bit chars.
pub fn meta(handle: WINDOW, flag: bool) -> result!(()) {
    match unsafe { ncurses::meta(handle, flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("meta", rc))
    }
}

/// Equivalent of `wmove()` using `stdscr()` as window `handle`.
pub fn r#move(origin: Origin) -> result!(()) {
    match ncurses::r#move(origin.y, origin.x) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("move", rc))
    }
}

/// Equivalent of `mvwadd_wch()` using `stdscr()` as window `handle`.
pub fn mvadd_wch(origin: Origin, wch: ComplexChar) -> result!(()) {
    match ncurses::mvadd_wch(origin.y, origin.x, &ComplexChar::into(wch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvadd_wch", rc))
    }
}

/// Equivalent of `mvwadd_wchnstr()` using `stdscr()` as window `handle`.
pub fn mvadd_wchnstr(origin: Origin, wchstr: &ComplexString, number: i32) -> result!(()) {
    match ncurses::mvadd_wchnstr(origin.y, origin.x, raw_with_nul_as_slice!(wchstr), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvadd_wchnstr", rc))
    }
}

/// Equivalent of `mvwadd_wchstr()` using `stdscr()` as window `handle`.
pub fn mvadd_wchstr(origin: Origin, wchstr: &ComplexString) -> result!(()) {
    match ncurses::mvadd_wchstr(origin.y, origin.x, raw_with_nul_as_slice!(wchstr)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvadd_wchstr", rc))
    }
}

/// Equivalent of `mvwaddch()` using `stdscr()` as window `handle`.
pub fn mvaddch(origin: Origin, ch: ChtypeChar) -> result!(()) {
    match ncurses::mvaddch(origin.y, origin.x, ChtypeChar::into(ch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvaddch", rc))
    }
}

/// Equivalent of `mvwaddchnstr()` using `stdscr()` as window `handle`.
pub fn mvaddchnstr(origin: Origin, chstr: &ChtypeString, number: i32) -> result!(()) {
    match ncurses::mvaddchnstr(origin.y, origin.x, raw_with_nul_as_slice!(chstr), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvaddchnstr", rc))
    }
}

/// Equivalent of `mvwaddchstr()` using `stdscr()` as window `handle`.
pub fn mvaddchstr(origin: Origin, chstr: &ChtypeString) -> result!(()) {
    match ncurses::mvaddchstr(origin.y, origin.x, raw_with_nul_as_slice!(chstr)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvaddchstr", rc))
    }
}

/// Equivalent of `mvwaddnstr()` using `stdscr()` as window `handle`.
pub fn mvaddnstr<S: Into<String>>(origin: Origin, str: S, number: i32) -> result!(()) {
    let str = str.into().to_string();

    match ncurses::mvaddnstr(origin.y, origin.x, unsafe { c_str_with_nul!(str) }, number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvaddnstr", rc))
    }
}

/// Equivalent of `mvwaddnwstr()` using `stdscr()` as window `handle`.
pub fn mvaddnwstr(origin: Origin, wstr: &WideString, number: i32) -> result!(()) {
    match ncurses::mvaddnwstr(origin.y, origin.x, raw_with_nul_as_slice!(wstr), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvaddnwstr", rc))
    }
}

/// Equivalent of `mvwaddstr()` using `stdscr()` as window `handle`.
pub fn mvaddstr<S: Into<String>>(origin: Origin, str: S) -> result!(()) {
    let str = str.into().to_string();

    match ncurses::mvaddstr(origin.y, origin.x, unsafe { c_str_with_nul!(str) }) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvaddstr", rc))
    }
}

/// Equivalent of `mvwaddwstr()` using `stdscr()` as window `handle`.
pub fn mvaddwstr(origin: Origin, wstr: &WideString) -> result!(()) {
    match ncurses::mvaddwstr(origin.y, origin.x, raw_with_nul_as_slice!(wstr)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvaddwstr", rc))
    }
}

/// Equivalent of `mvwchgat()` using `stdscr()` as window `handle`.
pub fn mvchgat<A, P, T>(origin: Origin, number: i32, attrs: A, color_pair: P) -> result!(())
    where A: AttributesType<T>,
          P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::mvchgat(origin.y, origin.x, number, attrs.as_attr_t(), color_pair.as_short_t(), color_pair.as_const_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvchgat", rc))
    }
}

/// The `mvcur()` routine provides low-level cursor motion.
/// It takes effect immediately (rather than at the next refresh).
pub fn mvcur(old: Origin, new: Origin) -> result!(()) {
    match ncurses::mvcur(old.y, old.x, new.y, new.x) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvcur", rc))
    }
}

/// Delete any character at origin.
pub fn mvdelch(origin: Origin) -> result!(()) {
    match ncurses::mvdelch(origin.y, origin.x) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvdelch", rc))
    }
}

/// Move the window inside its parent window. The screen-relative parameters
/// of the window are not changed. This routine is used to display different
/// parts of the parent window at the same physical position on the screen.
pub fn mvderwin(handle: WINDOW, origin: Origin) -> result!(()) {
    match unsafe { ncurses::mvderwin(handle, origin.y, origin.x) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvderwin", rc))
    }
}

/// Equivalent of `mvwget_wch()` using `stdscr()` as window `handle`.
pub fn mvget_wch(origin: Origin) -> result!(CharacterResult<WideChar>) {
    let mut wch: [wint_t; 1] = [0];

    match unsafe { ncurses::mvget_wch(origin.y, origin.x, wch.as_mut_ptr()) } {
        EINTR        => Err(NCurseswError::InterruptedCall),
        #[cfg(feature = "key_resize_as_error")]
        KEY_RESIZE   => Err(NCurseswError::KeyResize),
        KEY_CODE_YES => {
            match i32::try_from(wch[0])? {
                #[cfg(feature = "key_resize_as_error")]
                KEY_RESIZE => Err(NCurseswError::KeyResize),
                _          => Ok(CharacterResult::Key(KeyBinding::try_from(wch[0])?))
            }
        },
        rc           => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvget_wch", rc))
            } else {
                Ok(CharacterResult::Character(WideChar::from(wch[0])))
            }
        }
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvgetn_wstr() instead")]
/// Equivalent of `mvwget_wstr()` using `stdscr()` as window `handle`.
pub fn mvget_wstr(origin: Origin) -> result!(WideString) {
    let mut buf: [wint_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wint_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvget_wstr(origin.y, origin.x, ptr) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvget_wstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}mvget_wstr() : ptr.is_null()", MODULE_PATH);

                let buf_as_bytes = unsafe { slice::from_raw_parts(ptr as *mut wchar_t, LINE_MAX) };

                for (idx, &byte) in buf_as_bytes.iter().enumerate() {
                    if byte == 0x00 {
                        return Ok(WideString::from(&buf_as_bytes[..idx]));
                    }
                }

                Ok(WideString::from(buf_as_bytes))
            }
        }
    }
}

/// Equivalent of `mvwgetch()` using `stdscr()` as window `handle`.
pub fn mvgetch(origin: Origin) -> result!(CharacterResult<char>) {
    match ncurses::mvgetch(origin.y, origin.x) {
        EINTR      => Err(NCurseswError::InterruptedCall),
        #[cfg(feature = "key_resize_as_error")]
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvgetch", rc))
            } else if (KEY_MIN..=KEY_MAX).contains(&rc) {
                Ok(CharacterResult::Key(KeyBinding::from(rc)))
            } else {
                Ok(CharacterResult::Character(char::from(u8::try_from(i8::try_from(rc)?)?)))
            }
        }
    }
}

/// Equivalent of `mvwgetn_wstr()` using `stdscr()` as window `handle`.
pub fn mvgetn_wstr(origin: Origin, number: i32) -> result!(WideString) {
    assert!(number <= LINE_MAX as i32, "{}mvgetn_wstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [wint_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wint_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvgetn_wstr(origin.y, origin.x, ptr, number) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvgetn_wstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}mvgetn_wstr() : ptr.is_null()", MODULE_PATH);

                let buf_as_bytes = unsafe { slice::from_raw_parts(ptr as *mut wchar_t, LINE_MAX) };

                for (idx, &byte) in buf_as_bytes.iter().enumerate() {
                    if byte == 0x00 {
                        return Ok(WideString::from(&buf_as_bytes[..idx]));
                    }
                }

                Ok(WideString::from(buf_as_bytes))
            }
        }
    }
}

/// Equivalent of `mvwgetnstr()` using `stdscr()` as window `handle`.
pub fn mvgetnstr(origin: Origin, number: i32) -> result!(String) {
    assert!(number <= LINE_MAX as i32, "{}mvgetnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    match unsafe { ncurses::mvgetnstr(origin.y, origin.x, ptr, number) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvgetnstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}mvgetnstr() : ptr.is_null()", MODULE_PATH);

                Ok(unsafe { FromCStr::from_c_str(ptr) })
            }
        }
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvgetnstr() instead")]
/// Equivalent of `mvwgetstr()` using `stdscr()` as window `handle`.
pub fn mvgetstr(origin: Origin) -> result!(String) {
    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    match unsafe { ncurses::mvgetstr(origin.y, origin.x, ptr) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvgetstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}mvgetstr() : ptr.is_null()", MODULE_PATH);

                Ok(unsafe { FromCStr::from_c_str(ptr) })
            }
        }
    }
}

/// Equivalent of `mvwhline()` using `stdscr()` as window `handle`.
pub fn mvhline(origin: Origin, ch: ChtypeChar, number: i32) -> result!(()) {
    match ncurses::mvhline(origin.y, origin.x, ChtypeChar::into(ch), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvhline", rc))
    }
}

/// Equivalent of `mvwhline_set()` using `stdscr()` as window `handle`.
pub fn mvhline_set(origin: Origin, wch: ComplexChar, number: i32) -> result!(()) {
    match ncurses::mvhline_set(origin.y, origin.x, &ComplexChar::into(wch), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvhline_set", rc))
    }
}

/// Equivalent of `mvwin_wch()` using `stdscr()` as window `handle`.
pub fn mvin_wch(origin: Origin) -> result!(ComplexChar) {
    let mut wcval: [cchar_t; 1] = unsafe { mem::zeroed() };

    match unsafe { ncurses::mvin_wch(origin.y, origin.x, wcval.as_mut_ptr()) } {
        OK => Ok(ComplexChar::from(wcval[0])),
        rc => Err(ncurses_function_error_with_rc!("mvin_wch", rc))
    }
}

/// Equivalent of `mvwin_wchnstr()` using `stdscr()` as window `handle`.
pub fn mvin_wchnstr(origin: Origin, number: i32) -> result!(ComplexString) {
    assert!(number <= LINE_MAX as i32, "{}mvin_wchnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [cchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut cchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvin_wchnstr(origin.y, origin.x, ptr, number) } {
        OK => {
            assert!(!ptr.is_null(), "{}mvin_wchnstr() : ptr.is_null()", MODULE_PATH);

            Ok(ComplexString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(number)?) }))
        },
        rc => Err(ncurses_function_error_with_rc!("mvin_wchnstr", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvin_wchnstr() instead")]
/// Equivalent of `mvwin_wchstr()` using `stdscr()` as window `handle`.
pub fn mvin_wchstr(origin: Origin) -> result!(ComplexString) {
    let mut buf: [cchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut cchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvin_wchstr(origin.y, origin.x, ptr) } {
        OK => {
            assert!(!ptr.is_null(), "{}mvin_wchstr() : ptr.is_null()", MODULE_PATH);

            Ok(ComplexString::from(unsafe { slice::from_raw_parts(ptr, LINE_MAX) }))
        },
        rc => Err(ncurses_function_error_with_rc!("mvin_wchstr", rc))
    }
}

/// Equivalent of `mvwinch()` using `stdscr()` as window `handle`.
pub fn mvinch(origin: Origin) -> ChtypeChar {
    ChtypeChar::from(ncurses::mvinch(origin.y, origin.x))
}

/// Equivalent of `mvwinchnstr()` using `stdscr()` as window `handle`.
pub fn mvinchnstr(origin: Origin, number: i32) -> result!(ChtypeString) {
    assert!(number <= LINE_MAX as i32, "{}mvinchnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [chtype; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut chtype = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvinchnstr(origin.y, origin.x, ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvinchnstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvinchnstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvinchnstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(ChtypeString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvinchnstr() instead")]
/// Equivalent of `mvwinchstr()` using `stdscr()` as window `handle`.
pub fn mvinchstr(origin: Origin) -> result!(ChtypeString) {
    let mut buf: [chtype; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut chtype = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvinchstr(origin.y, origin.x, ptr) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvinchstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvinchstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvinchstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(ChtypeString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

/// Equivalent of `mvwinnstr()` using `stdscr()` as window `handle`.
pub fn mvinnstr(origin: Origin, number: i32) -> result!(String) {
    assert!(number <= LINE_MAX as i32, "{}mvinnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvinnstr(origin.y, origin.x, ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvinnstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvinnstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvinnstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(unsafe { FromCStr::from_c_str(ptr) })
    }
}

/// Equivalent of `mvwinnwstr()` using `stdscr()` as window `handle`.
pub fn mvinnwstr(origin: Origin, number: i32) -> result!(WideString) {
    assert!(number <= LINE_MAX as i32, "{}mvinnwstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [wchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wchar_t = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvinnwstr(origin.y, origin.x, ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvinnwstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvinnwstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvinnwstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(WideString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

/// Equivalent of `mvwins_nwstr()` using `stdscr()` as window `handle`.
pub fn mvins_nwstr(origin: Origin, wstr: &WideString, number: i32) -> result!(()) {
    match ncurses::mvins_nwstr(origin.y, origin.x, raw_with_nul_as_slice!(wstr), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvins_nwstr", rc))
    }
}

/// Equivalent of `mvwins_wch()` using `stdscr()` as window `handle`.
pub fn mvins_wch(origin: Origin, wch: ComplexChar) -> result!(()) {
    match ncurses::mvins_wch(origin.y, origin.x, &ComplexChar::into(wch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvins_wch", rc))
    }
}

/// Equivalent of `mvwins_wstr()` using `stdscr()` as window `handle`.
pub fn mvins_wstr(origin: Origin, wstr: &WideString) -> result!(()) {
    match ncurses::mvins_wstr(origin.y, origin.x, raw_with_nul_as_slice!(wstr)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvins_wstr", rc))
    }
}

/// Equivalent of `mvwinsch()` using `stdscr()` as window `handle`.
pub fn mvinsch(origin: Origin, ch: ChtypeChar) -> result!(()) {
    match ncurses::mvinsch(origin.y, origin.x, ChtypeChar::into(ch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvinsch", rc))
    }
}

/// Equivalent of `mvwinsnstr()` using `stdscr()` as window `handle`.
pub fn mvinsnstr<S: Into<String>>(origin: Origin, str: S, number: i32) -> result!(()) {
    let str = str.into().to_string();

    match ncurses::mvinsnstr(origin.y, origin.x, unsafe { c_str_with_nul!(str) }, number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvinsnstr", rc))
    }
}

/// Equivalent of `mvwinsstr()` using `stdscr()` as window `handle`.
pub fn mvinsstr<S: Into<String>>(origin: Origin, str: S) -> result!(()) {
    let str = str.into().to_string();

    match ncurses::mvinsstr(origin.y, origin.x, unsafe { c_str_with_nul!(str) }) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvinsstr", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvinnstr() instead")]
/// Equivalent of `mvwinstr()` using `stdscr()` as window `handle`.
pub fn mvinstr(origin: Origin) -> result!(String) {
    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvinstr(origin.y, origin.x, ptr) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvinstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvinstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvinstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(unsafe { FromCStr::from_c_str(ptr) })
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvinnwstr() instead")]
/// Equivalent of `mvwinwstr()` using `stdscr()` as window `handle`.
pub fn mvinwstr(origin: Origin) -> result!(WideString) {
    let mut buf: [wchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvinwstr(origin.y, origin.x, ptr) } {
        OK => {
            assert!(!ptr.is_null(), "{}mvinwstr() : ptr.is_null()", MODULE_PATH);

            Ok(WideString::from(unsafe { slice::from_raw_parts(ptr, LINE_MAX) }))
        },
        rc => Err(ncurses_function_error_with_rc!("mvinwstr", rc))
    }
}

/// Equivalent of `mvwvline()` using `stdscr()` as window `handle`.
pub fn mvvline(origin: Origin, ch: ChtypeChar, number: i32) -> result!(()) {
    match ncurses::mvvline(origin.y, origin.x, ChtypeChar::into(ch), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvvline", rc))
    }
}

/// Equivalent of `mvwvline_set()` using `stdscr()` as window `handle`.
pub fn mvvline_set(origin: Origin, wch: ComplexChar, number: i32) -> result!(()) {
    match ncurses::mvvline_set(origin.y, origin.x, &ComplexChar::into(wch), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvvline_set", rc))
    }
}

/// Paint a complex character `wch` at `origin`, overwriting any character
/// previously painted at that location.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwadd_wch(handle: WINDOW, origin: Origin, wch: ComplexChar) -> result!(()) {
    match unsafe { ncurses::mvwadd_wch(handle, origin.y, origin.x, &ComplexChar::into(wch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwadd_wch", rc))
    }
}

/// Paint a complex character string of at most `number` characters of `wchstr`
/// at `origin`, overwriting anything previously on the window.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwadd_wchnstr(handle: WINDOW, origin: Origin, wchstr: &ComplexString, number: i32) -> result!(()) {
    match unsafe { ncurses::mvwadd_wchnstr(handle, origin.y, origin.x, raw_with_nul_as_slice!(wchstr), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwadd_wchnstr", rc))
    }
}

/// Paint a complex character string of `wchstr` at `origin`,
/// overwriting anything previously on the window.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwadd_wchstr(handle: WINDOW, origin: Origin, wchstr: &ComplexString) -> result!(()) {
    match unsafe { ncurses::mvwadd_wchstr(handle, origin.y, origin.x, raw_with_nul_as_slice!(wchstr)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwadd_wchstr", rc))
    }
}

/// Paint character `ch` at `origin`, overwriting any character previously
/// painted at that location.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwaddch(handle: WINDOW, origin: Origin, ch: ChtypeChar) -> result!(()) {
    match unsafe { ncurses::mvwaddch(handle, origin.y, origin.x, ChtypeChar::into(ch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwaddch", rc))
    }
}

/// Paint a character string (with rendition) of `chstr` of at most `number`
/// characters at `origin`, overwriting anything previously on the window.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwaddchnstr(handle: WINDOW, origin: Origin, chstr: &ChtypeString, number: i32) -> result!(()) {
    match unsafe { ncurses::mvwaddchnstr(handle, origin.y, origin.x, raw_with_nul_as_slice!(chstr), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwaddchnstr", rc))
    }
}

/// Paint a character string (with rendition) of `chstr` at `origin`,
/// overwriting anything previously on the window.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwaddchstr(handle: WINDOW, origin: Origin, chstr: &ChtypeString) -> result!(()) {
    match unsafe { ncurses::mvwaddchstr(handle, origin.y, origin.x, raw_with_nul_as_slice!(chstr)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwaddchstr", rc))
    }
}

/// Paint a string of `str` with at most `number` characters` at `origin`,
/// overwriting anything previously on the window.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwaddnstr<S: Into<String>>(handle: WINDOW, origin: Origin, str: S, number: i32) -> result!(()) {
    let str = str.into().to_string();

    match unsafe { ncurses::mvwaddnstr(handle, origin.y, origin.x, c_str_with_nul!(str), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwaddnstr", rc))
    }
}

/// Paint a wide string of `wstr` with at most `number` characters at `origin`,
/// overwriting anything previously on the window.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwaddnwstr(handle: WINDOW, origin: Origin, wstr: &WideString, number: i32) -> result!(()) {
    match unsafe { ncurses::mvwaddnwstr(handle, origin.y, origin.x, raw_with_nul_as_slice!(wstr), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwaddnwstr", rc))
    }
}

/// Paint a string of `str` at `origin`, overwriting anything previously
/// on the window.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwaddstr<S: Into<String>>(handle: WINDOW, origin: Origin, str: S) -> result!(()) {
    let str = str.into().to_string();

    match unsafe { ncurses::mvwaddstr(handle, origin.y, origin.x, c_str_with_nul!(str)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwaddstr", rc))
    }
}

/// Paint a wide string of `wstr` at `origin`, overwriting anything previously
/// on the window.
///
/// Writing outside the window, sub-window, or pad raises a `NCurseswError`.
/// Attempting to write to the lower right corner of a window, sub-window,
/// or pad will cause an `NCurseswError` to be raised after the character
/// is printed.
pub fn mvwaddwstr(handle: WINDOW, origin: Origin, wstr: &WideString) -> result!(()) {
    match unsafe { ncurses::mvwaddwstr(handle, origin.y, origin.x, raw_with_nul_as_slice!(wstr)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwaddwstr", rc))
    }
}

/// Set the attributes of `number` characters at the position `origin`.
/// This routine moves cursor to position `origin`. The changed line
/// will be touched using the `touchline()` method so that the contents
/// will be redisplayed by the next window `refresh()`.
pub fn mvwchgat<A, P, T>(handle: WINDOW, origin: Origin, number: i32, attrs: A, color_pair: P) -> result!(())
    where A: AttributesType<T>,
          P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::mvwchgat(handle, origin.y, origin.x, number, attrs.as_attr_t(), color_pair.as_short_t(), color_pair.as_const_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwchgat", rc))
    }
}

/// Delete any character at `origin` on window.
pub fn mvwdelch(handle: WINDOW, origin: Origin) -> result!(()) {
    match unsafe { ncurses::mvwdelch(handle, origin.y, origin.x) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwdelch", rc))
    }
}

/// Return an enum of `CharacterResult::Character(WideChar)` for most keys, or
/// a `CharacterResult::Key(KeyBinding)` for function keys, keypad keys, and
/// other special keys. In no-delay mode, raise a `NCurseswError` if there is
/// no input.
///
/// If the `keypad()` function has been called with a `flag` of `true` the
/// NCurses library will interpret some keys such as function keys, keypad
/// keys and other special keys (this may also include such things as mouse
/// and resizing events) and return these wrapped in the enum `CharacterResult::Key()`
/// or a `CharacterResult::Character()` for non-interpreted keys.
pub fn mvwget_wch(handle: WINDOW, origin: Origin) -> result!(CharacterResult<WideChar>) {
    let mut wch: [wint_t; 1] = [0];

    match unsafe { ncurses::mvwget_wch(handle, origin.y, origin.x, wch.as_mut_ptr()) } {
        EINTR        => Err(NCurseswError::InterruptedCall),
        #[cfg(feature = "key_resize_as_error")]
        KEY_RESIZE   => Err(NCurseswError::KeyResize),
        KEY_CODE_YES => {
            match i32::try_from(wch[0])? {
                #[cfg(feature = "key_resize_as_error")]
                KEY_RESIZE => Err(NCurseswError::KeyResize),
                _          => Ok(CharacterResult::Key(KeyBinding::try_from(wch[0])?))
            }
        },
        rc           => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvwget_wch", rc))
            } else {
                Ok(CharacterResult::Character(WideChar::from(wch[0])))
            }
        }
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvwgetn_wstr() instead")]
/// Read a wide string from the user at `origin`, with primitive line editing capacity.
pub fn mvwget_wstr(handle: WINDOW, origin: Origin) -> result!(WideString) {
    let mut buf: [wint_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wint_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvwget_wstr(handle, origin.y, origin.y, ptr) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvwget_wstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}mvwget_wstr() : ptr.is_null()", MODULE_PATH);

                let buf_as_bytes = unsafe { slice::from_raw_parts(ptr as *mut wchar_t, LINE_MAX) };

                for (idx, &byte) in buf_as_bytes.iter().enumerate() {
                    if byte == 0x00 {
                        return Ok(WideString::from(&buf_as_bytes[..idx]));
                    }
                }

                Ok(WideString::from(buf_as_bytes))
            }
        }
    }
}

/// Return an enum of `CharacterResult::Character(char)` for most keys, or a
/// `CharacterResult::Key(KeyBinding)` for function keys, keypad keys, and
/// other special keys. In no-delay mode, raise a `NCurseswError` if there is
/// no input.
///
/// If the `keypad()` function has been called with a `flag` of `true` the
/// NCurses library will interpret some keys such as function keys, keypad
/// keys and other special keys (this may also include such things as mouse
/// and resizing events) and return these wrapped in the enum `CharacterResult::Key()`
/// or a `CharacterResult::Character()` for non-interpreted keys.
pub fn mvwgetch(handle: WINDOW, origin: Origin) -> result!(CharacterResult<char>) {
    match unsafe { ncurses::mvwgetch(handle, origin.y, origin.x) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        #[cfg(feature = "key_resize_as_error")]
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvwgetch", rc))
            } else if (KEY_MIN..=KEY_MAX).contains(&rc) {
                Ok(CharacterResult::Key(KeyBinding::from(rc)))
            } else {
                Ok(CharacterResult::Character(char::from(u8::try_from(i8::try_from(rc)?)?)))
            }
        }
    }
}

/// Read a wide string of at most `number` characters from the user at
/// `origin`, with primitive line editing capacity.
pub fn mvwgetn_wstr(handle: WINDOW, origin: Origin, number: i32) -> result!(WideString) {
    assert!(number <= LINE_MAX as i32, "{}mvwgetn_wstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [wint_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wint_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvwgetn_wstr(handle, origin.y, origin.x, ptr, number) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvwgetn_wstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}mvwgetn_wstr() : ptr.is_null()", MODULE_PATH);

                let buf_as_bytes = unsafe { slice::from_raw_parts(ptr as *mut wchar_t, LINE_MAX) };

                for (idx, &byte) in buf_as_bytes.iter().enumerate() {
                    if byte == 0x00 {
                        return Ok(WideString::from(&buf_as_bytes[..idx]));
                    }
                }

                Ok(WideString::from(buf_as_bytes))
            }
        }
    }
}

/// Read a string of at most `number` characters from the user at `origin`,
/// with primitive line editing capacity.
pub fn mvwgetnstr(handle: WINDOW, origin: Origin, number: i32) -> result!(String) {
    assert!(number <= LINE_MAX as i32, "{}mvwgetnstr() : number={}, LINE_MAX{}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    match unsafe { ncurses::mvwgetnstr(handle, origin.y, origin.x, ptr, number) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvwgetnstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}mvwgetnstr() : ptr.is_null()", MODULE_PATH);

                Ok(unsafe { FromCStr::from_c_str(ptr) })
            }
        }
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvwgetnstr() instead")]
/// Read a string from the user at `origin`, with primitive line editing capacity.
pub fn mvwgetstr(handle: WINDOW, origin: Origin) -> result!(String) {
    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    match unsafe { ncurses::mvwgetstr(handle, origin.y, origin.x, ptr) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("mvwgetstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}mvwgetstr() : ptr.is_null()", MODULE_PATH);

                Ok(unsafe { FromCStr::from_c_str(ptr) })
            }
        }
    }
}

/// Display a horizontal line with length `number` consisting of the
/// character `ch` at `origin`.
pub fn mvwhline(handle: WINDOW, origin: Origin, ch: ChtypeChar, number: i32) -> result!(()) {
    match unsafe { ncurses::mvwhline(handle, origin.y, origin.x, ChtypeChar::into(ch), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwhline", rc))
    }
}

/// Display a horizontal line with length `number` consisting of the
/// character `wch` at `origin`.
pub fn mvwhline_set(handle: WINDOW, origin: Origin, wch: ComplexChar, number: i32) -> result!(()) {
    match unsafe { ncurses::mvwhline_set(handle, origin.y, origin.x, &ComplexChar::into(wch), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwhline_set", rc))
    }
}

/// Move the window so its upper-left corner is at `origin`.
///
/// If the move would cause the window to be off the screen, it is an error
/// and the window is not moved. Moving sub-windows is allowed, but should
/// be avoided.
pub fn mvwin(handle: WINDOW, origin: Origin) -> result!(()) {
    match unsafe { ncurses::mvwin(handle, origin.y, origin.x) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwin", rc))
    }
}

/// Return the complex character at the given `origin` in the window.
pub fn mvwin_wch(handle: WINDOW, origin: Origin) -> result!(ComplexChar) {
    let mut wcval: [cchar_t; 1] = unsafe { mem::zeroed() };

    match unsafe { ncurses::mvwin_wch(handle, origin.y, origin.x, wcval.as_mut_ptr()) } {
        OK => Ok(ComplexChar::from(wcval[0])),
        rc => Err(ncurses_function_error_with_rc!("mvwin_wch", rc))
    }
}

/// Return the complex character string of length `number` at the
/// given `origin` in the window.
pub fn mvwin_wchnstr(handle: WINDOW, origin: Origin, number: i32) -> result!(ComplexString) {
    assert!(number <= LINE_MAX as i32, "{}mvwin_wchnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [cchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut cchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvwin_wchnstr(handle, origin.y, origin.x, ptr, number) } {
        OK => {
            assert!(!ptr.is_null(), "{}mvwin_wchnstr() : ptr.is_null()", MODULE_PATH);

            Ok(ComplexString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(number)?) }))
        },
        rc => Err(ncurses_function_error_with_rc!("mvwin_wchnstr", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvwin_wchnstr() instead")]
/// Return the complex character string given `origin` in the window.
pub fn mvwin_wchstr(handle: WINDOW, origin: Origin) -> result!(ComplexString) {
    let mut buf: [cchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut cchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvwin_wchstr(handle, origin.y, origin.x, ptr) } {
        OK => {
            assert!(!ptr.is_null(), "{}mvwin_wchstr() : ptr.is_null()", MODULE_PATH);

            Ok(ComplexString::from(unsafe { slice::from_raw_parts(ptr, LINE_MAX) }))
        },
        rc => Err(ncurses_function_error_with_rc!("mvwin_wchstr", rc))
    }
}

/// Return the character and rendition at the given `origin` in the window.
pub fn mvwinch(handle: WINDOW, origin: Origin) -> ChtypeChar {
    ChtypeChar::from(unsafe { ncurses::mvwinch(handle, origin.y, origin.x) })
}

/// Return the character string and rendition of length `number` at the
/// given `origin` in the window.
pub fn mvwinchnstr(handle: WINDOW, origin: Origin, number: i32) -> result!(ChtypeString) {
    assert!(number <= LINE_MAX as i32, "{}mvwinchnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [chtype; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut chtype = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvwinchnstr(handle, origin.y, origin.x, ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvwinchnstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvwinchnstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvwinchnstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(ChtypeString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvwinchnstr() instead")]
/// Return the character string and rendion at the given `origin` in the window.
pub fn mvwinchstr(handle: WINDOW, origin: Origin) -> result!(ChtypeString) {
    let mut buf: [chtype; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut chtype = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvwinchstr(handle, origin.y, origin.x, ptr) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvwinchstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvwinchstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvwinchstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(ChtypeString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

/// Return the character string of length `number` at the given `origin` in the window.
pub fn mvwinnstr(handle: WINDOW, origin: Origin, number: i32) -> result!(String) {
    assert!(number <= LINE_MAX as i32, "{}mvwinnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvwinnstr(handle, origin.y, origin.x, ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvwinnstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvwinnstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvwinnstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(unsafe { FromCStr::from_c_str(ptr) })
    }
}

/// Return the wide character string of length `number` at the given `origin` in the window.
pub fn mvwinnwstr(handle: WINDOW, origin: Origin, number: i32) -> result!(WideString) {
    assert!(number <= LINE_MAX as i32, "{}mvwinnwstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [wchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wchar_t = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvwinnwstr(handle, origin.y, origin.x, ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvwinnwstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvwinnwstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvwinnwstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(WideString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

/// Insert a wide string (as many characters as will fit on the line) before the
/// character at `origin`, up to `number` characters. If `number` is zero or
/// negative, the entire string is inserted. All characters to the right of
/// the cursor are shifted right, with the rightmost characters on the line
/// being lost. The cursor position does not change (after moving to `origin`).
pub fn mvwins_nwstr(handle: WINDOW, origin: Origin, wstr: &WideString, number: i32) -> result!(()) {
    match unsafe { ncurses::mvwins_nwstr(handle, origin.y, origin.x, raw_with_nul_as_slice!(wstr), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwins_nwstr", rc))
    }
}

/// Insert the complex character `wch` at `origin`, moving the cursor position from
/// `origin.x` right by one character.
pub fn mvwins_wch(handle: WINDOW, origin: Origin, wch: ComplexChar) -> result!(()) {
    match unsafe { ncurses::mvwins_wch(handle, origin.y, origin.x, &ComplexChar::into(wch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwins_wch", rc))
    }
}

/// Insert a wide string (as many characters as will fit on the line) before the
/// character at `origin`. All characters to the right of the cursor are shifted
/// right, with the rightmost characters on the line being lost. The cursor
/// position does not change (after moving to `origin`).
pub fn mvwins_wstr(handle: WINDOW, origin: Origin, wstr: &WideString) -> result!(()) {
    match unsafe { ncurses::mvwins_wstr(handle, origin.y, origin.x, raw_with_nul_as_slice!(wstr)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwins_wstr", rc))
    }
}

/// Insert character `ch` at `origin`, moving the cursor position from
/// `origin.x` right by one character.
pub fn mvwinsch(handle: WINDOW, origin: Origin, ch: ChtypeChar) -> result!(()) {
    match unsafe { ncurses::mvwinsch(handle, origin.y, origin.x, ChtypeChar::into(ch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwinsch", rc))
    }
}

/// Insert a string (as many characters as will fit on the line) before the
/// character at `origin`, up to `number` characters. If `number` is zero or
/// negative, the entire string is inserted. All characters to the right of
/// the cursor are shifted right, with the rightmost characters on the line
/// being lost. The cursor position does not change (after moving to `origin`).
pub fn mvwinsnstr<S: Into<String>>(handle: WINDOW, origin: Origin, str: S, number: i32) -> result!(()) {
    let str = str.into().to_string();

    match unsafe { ncurses::mvwinsnstr(handle, origin.y, origin.x, c_str_with_nul!(str), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwinsnstr", rc))
    }
}

/// Insert a string (as many characters as will fit on the line) before the
/// character at `origin`. All characters to the right of the cursor are shifted
/// right, with the rightmost characters on the line being lost. The cursor
/// position does not change (after moving to `origin`).
pub fn mvwinsstr<S: Into<String>>(handle: WINDOW, origin: Origin, str: S) -> result!(()) {
    let str = str.into().to_string();

    match unsafe { ncurses::mvwinsstr(handle, origin.y, origin.x, c_str_with_nul!(str)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwinsstr", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvwinnstr() instead")]
/// Return the string at the given `origin` in the window.
pub fn mvwinstr(handle: WINDOW, origin: Origin) -> result!(String) {
    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    let len = unsafe { ncurses::mvwinstr(handle, origin.y, origin.x, ptr) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("mvwinstr", len))
    } else {
        assert!(!ptr.is_null(), "{}mvwinstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}mvwinstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(unsafe { FromCStr::from_c_str(ptr) })
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use mvwinnwstr() instead")]
/// Return the wide string at the given `origin` in the window.
pub fn mvwinwstr(handle: WINDOW, origin: Origin) -> result!(WideString) {
    let mut buf: [wchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::mvwinwstr(handle, origin.y, origin.x, ptr) } {
        OK => {
            assert!(!ptr.is_null(), "{}mvwinwstr() : ptr.is_null()", MODULE_PATH);

            Ok(WideString::from(unsafe { slice::from_raw_parts(ptr, LINE_MAX) }))
        },
        rc => Err(ncurses_function_error_with_rc!("mvwinwstr", rc))
    }
}

/// Display a vertical line with length `number` consisting of the character `ch`.
pub fn mvwvline(handle: WINDOW, origin: Origin, ch: ChtypeChar, number: i32) -> result!(()) {
    match unsafe { ncurses::mvwvline(handle, origin.y, origin.x, ChtypeChar::into(ch), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwvline", rc))
    }
}

/// Display a vertical line with length `number` consisting of the character `wch`.
pub fn mvwvline_set(handle: WINDOW, origin: Origin, wch: ComplexChar, number: i32) -> result!(()) {
    match unsafe { ncurses::mvwvline_set(handle, origin.y, origin.x, &ComplexChar::into(wch), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvwvline_set", rc))
    }
}

#[deprecated(since = "0.3.2", note = "ncurses library call superseeded by native rust call. Use std::thread::sleep(dur: std::time::Duration) instead")]
/// Sleep for ms milliseconds.
pub fn napms(ms: time::Duration) -> result!(()) {
    match ncurses::napms(i32::try_from(ms.as_millis())?) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("napms", rc))
    }
}

/// The `newpad()` routine creates and returns a pointer to a new pad data
/// structure with the given `size`. A pad is like a window, except that it
/// is not restricted by the screen size, and is not necessarily associated
/// with a particular part of the screen. Pads can be used when a large
/// window is needed, and only a part of the window will be on the screen at
/// one time. Automatic refreshes of pads (e.g., from scrolling or echoing
/// of input) do not occur.
///
/// It is not legal to call `wrefresh()` with a pad as an argument; the
/// routines `prefresh()` or `pnoutrefresh()` should be called instead.
/// Note that these routines require additional parameters to specify the
/// part of the pad to be displayed and the location on the screen to be
/// used for the display.
pub fn newpad(size: Size) -> result!(WINDOW) {
    unsafe { ncurses::newpad(size.lines, size.columns).ok_or(ncurses_function_error!("newpad")) }
}

/// A program that outputs to more than one terminal should use the `newterm()`
/// routine for each terminal instead of `initscr()`. A program that needs to
/// inspect capabilities, so it can continue to run in a line-oriented mode
/// if the terminal cannot support a screen-oriented program, would also use
/// `newterm()`. The routine `newterm()` should be called once for each terminal.
/// It returns a pointer of type SCREEN which should be saved as a reference
/// to that terminal. newterm's arguments are:
///
/// - the type of the terminal to be used in place of $TERM,
/// - a file descriptor for output to the terminal, and...
/// - another file descriptor for input from the terminal
///
/// If the `term_type` parameter is `None`, $TERM will be used.
pub fn newterm<S, O, I>(term: Option<S>, output: &O, input: &I) -> result!(SCREEN)
    where S: Into<String>,
          O: AsRawFd + Write,
          I: AsRawFd + Read
{
    let term = term.and_then(|str| Some(str.into().to_string()));

    unsafe {
        ncurses::newterm(
            option_str_as_ptr!(term),
            fdopen(output, "wb+")?,
            fdopen(input, "rb+")?
        ).ok_or(ncurses_function_error!("newterm"))
    }
}

/// Return a new window, whose left-upper corner is at origin,
/// and whose height/width is size.
pub fn newwin(size: Size, origin: Origin) -> result!(WINDOW) {
    unsafe { ncurses::newwin(size.lines, size.columns, origin.y, origin.x).ok_or(ncurses_function_error!("newwin")) }
}

/// Enter newline mode. This mode translates the return key into newline on
/// input, and translates newline into return and line-feed on output.
/// Newline mode is initially on.
pub fn nl() -> result!(()) {
    match ncurses::nl() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("nl", rc))
    }
}

/// Leave cbreak mode. Return to normal “cooked” mode with line buffering.
pub fn nocbreak() -> result!(()) {
    match ncurses::nocbreak() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("nocbreak", rc))
    }
}

/// If flag is `true`, `getch()` will be non-blocking.
pub fn nodelay(handle: WINDOW, flag: bool) -> result!(()) {
    match unsafe { ncurses::nodelay(handle, flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("nodelay", rc))
    }
}

/// Leave echo mode. Echoing of input characters is turned off.
pub fn noecho() -> result!(()) {
    match ncurses::noecho() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("noecho", rc))
    }
}

/// The `nofilter()` routine cancels the effect of a preceding `filter()` call.
/// That allows the caller to initialize a screen on a different device, using
/// a different value of $TERM. The limitation arises because the `filter()`
/// routine modifies the in-memory copy of the terminal information.
pub fn nofilter() {
    ncurses::nofilter()
}

/// Leave newline mode. Disable translation of return into newline on input,
/// and disable low-level translation of newline into newline/return on output
/// (but this does not change the behavior of `addch('\n')`, which always does
/// the equivalent of return and line feed on the virtual screen).
/// With translation off, NCurses can sometimes speed up vertical motion a
/// little; also, it will be able to detect the return key on input.
pub fn nonl() -> result!(()) {
    match ncurses::nonl() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("nonl", rc))
    }
}

/// When the `noqiflush()` routine is used, normal flush of input and output
/// queues associated with the INTR, QUIT and SUSP characters will not be done.
/// You may want to call `noqiflush()` in a signal handler if you want output
/// to continue as though the interrupt had not occurred, after the handler exits.
pub fn noqiflush() {
    ncurses::noqiflush()
}

/// Leave raw mode. Return to normal “cooked” mode with line buffering.
pub fn noraw() -> result!(()) {
    match ncurses::noraw() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("noraw", rc))
    }
}

/// If flag is `true`, escape sequences will not be timed out.
///
/// If flag is `false`, after a few milliseconds, an escape sequence will not be
/// interpreted, and will be left in the input stream as is.
pub fn notimeout(handle: WINDOW, flag: bool) -> result!(()) {
    match unsafe { ncurses::notimeout(handle, flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("notimeout", rc))
    }
}

/// Overlay the window on top of `destwin`. The windows need not be the same size,
/// only the overlapping region is copied. This copy is non-destructive, which
/// means that the current background character does not overwrite the old
/// contents of destwin.
///
/// To get fine-grained control over the copied region, the second form of
/// `overlay()` can be used. sminrow and smincol are the upper-left coordinates
/// of the source window, and the other variables mark a rectangle in the
/// destination window.
pub fn overlay(src_handle: WINDOW, dst_handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::overlay(src_handle, dst_handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("overlay", rc))
    }
}

/// Overlay the window on top of `destwin` in the same way as `overlay()`
/// but in a destructive manner.
pub fn overwrite(src_handle: WINDOW, dst_handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::overwrite(src_handle, dst_handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("overwrite", rc))
    }
}

#[deprecated(since = "0.4.0", note = "Use normal::ColorPair::colors() or shims::ncurses::pair_content() instead")]
/// Return a structure containing the colors for the requested color pair.
/// The value of `color_pair` must be between 1 and COLOR_PAIRS - 1.
pub fn pair_content(color_pair: short_t) -> result!(normal::Colors) {
    let mut fg: [short_t; 1] = [0];
    let mut bg: [short_t; 1] = [0];

    match unsafe { ncurses::pair_content(color_pair, fg.as_mut_ptr(), bg.as_mut_ptr()) } {
        OK => Ok(normal::Colors::new(normal::Color::_from(None, normal::ColorPalette::_from(fg[0])), normal::Color::_from(None, normal::ColorPalette::_from(bg[0])))),
        rc => Err(ncurses_function_error_with_rc!("pair_content", rc))
    }
}

/// The `pechochar()` routine is functionally equivalent to a call to `addch()`
/// followed by a call to `refresh()`, a call to `waddch()` followed by a call
/// to `wrefresh()`, or a call to `waddch()` followed by a call to `prefresh()`.
/// The knowledge that only a single character is being output is taken into
/// consideration and, for non-control characters, a considerable performance
/// gain might be seen by using these routines instead of their equivalents.
/// In the case of `pechochar()`, the last location of the pad on the screen
/// is reused for the arguments to `prefresh()`.
pub fn pechochar(pad: WINDOW, ch: ChtypeChar) -> result!(()) {
    match unsafe { ncurses::pechochar(pad, ChtypeChar::into(ch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("pechochar", rc))
    }
}

/// The `pecho_wchar()` function is the analogous wide-character form of `pechochar()`.
/// It outputs one character to a pad and immediately refreshes the pad. It does this
/// by a call to `wadd_wch()` followed by a call to `prefresh()`.
pub fn pecho_wchar(pad: WINDOW, wch: ComplexChar) -> result!(()) {
    match unsafe { ncurses::pecho_wchar(pad, &ComplexChar::into(wch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("pecho_wchar", rc))
    }
}

/// The `pnoutrefresh()` routine is analogous to `wnoutrefresh()` except that they relate
/// to pads instead of windows. The additional parameters are needed to indicate what part
/// of the pad and screen are involved.
///
/// - The `pmin.y`, `pmin.x` parameters specify the upper left-hand corner of the rectangle
///   to be displayed in the pad.
/// - The `smin.y`, `smin.y`, `smax.y`, and `smax.x` parameters specify the edges of the
///   rectangle to be displayed on the screen.
///
/// The lower right-hand corner of the rectangle to be displayed in the pad is calculated
/// from the screen coordinates, since the rectangles must be the same size. Both rectangles
/// must be entirely contained within their respective structures. Negative values of
/// pmin.{y,x}, smin.{y,x} are treated as if they were zero.
pub fn pnoutrefresh(pad: WINDOW, pmin: Origin, smin: Origin, smax: Origin) -> result!(()) {
    match unsafe { ncurses::pnoutrefresh(pad, pmin.y, pmin.x, smin.y, smin.x, smax.y, smax.x) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("pnoutrefresh", rc))
    }
}

/// The `prefresh()` routine is analogous to `wrefresh()` except that they relate to pads
/// instead of windows. The additional parameters are needed to indicate what part of the
/// pad and screen are involved.
///
/// - The `pmin.y`, `pmin.x` parameters specify the upper left-hand corner of the rectangle
///   to be displayed in the pad.
/// - The `smin.y`, `smin.y`, `smax.y`, and `smax.x` parameters specify the edges of the
///   rectangle to be displayed on the screen.
///
/// The lower right-hand corner of the rectangle to be displayed in the pad is calculated
/// from the screen coordinates, since the rectangles must be the same size. Both rectangles
/// must be entirely contained within their respective structures. Negative values of
/// pmin.{y,x}, smin.{y,x} are treated as if they were zero.
pub fn prefresh(pad: WINDOW, pmin: Origin, smin: Origin, smax: Origin) -> result!(()) {
    match unsafe { ncurses::prefresh(pad, pmin.y, pmin.x, smin.y, smin.x, smax.y, smax.x) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("prefresh", rc))
    }
}

/// At present this function is unimplemented.
pub fn putp<S: Into<String>>(_str: S) -> i32 {
    unimplemented!();
}

/// Write all data associated with the window into the provided file.
/// This information can be later retrieved using the `getwin()` function.
pub fn putwin<O: AsRawFd + Write>(handle: WINDOW, file: &O) -> result!(()) {
    match unsafe { ncurses::putwin(handle, fdopen(file, "w")?) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("putwin", rc))
    }
}

/// When the `noqiflush()` routine is used, normal flush of input and output
/// queues associated with the INTR, QUIT and SUSP characters will be done.
pub fn qiflush() {
    ncurses::qiflush()
}

/// Enter raw mode. In raw mode, normal line buffering and processing of
/// interrupt, quit, suspend, and flow control keys are turned off;
/// characters are presented to NCurses input functions one by one.
pub fn raw() -> result!(()) {
    match ncurses::raw() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("raw", rc))
    }
}

/// Touch the entire window, causing it to be completely redrawn on the
/// next call to `refresh()`.
pub fn redrawwin(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::redrawwin(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("redrawwin", rc))
    }
}

/// Update the display immediately (sync actual screen with previous
/// drawing/deleting methods).
pub fn refresh() -> result!(()) {
    match ncurses::refresh() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("refresh", rc))
    }
}

#[deprecated(since = "0.5.0", note = "use with caution as this routine will reset all color pairs potentially before they go out of scope and the color pairs will default to terminal default foreground and backgound colors.")]
/// Reset all defined color pairs.
pub fn reset_color_pairs() {
    ncurses::reset_color_pairs()
}

/// Restore the terminal to “program” mode, as previously saved by `def_prog_mode()`.
pub fn reset_prog_mode() -> result!(()) {
    match ncurses::reset_prog_mode() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("reset_prog_mode", rc))
    }
}

/// Restore the terminal to “shell” mode, as previously saved by `def_shell_mode()`.
pub fn reset_shell_mode() -> result!(()) {
    match ncurses::reset_shell_mode() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("reset_shell_mode", rc))
    }
}

/// Restore the state of the terminal modes to what it was at the last call to `savetty()`.
pub fn resetty() -> result!(()) {
    match ncurses::resetty() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("resetty", rc))
    }
}

/// Backend function used by `resizeterm()`, performing most of the work; when
/// resizing the windows, `resize_term()` blank-fills the areas that are extended.
/// The calling application should fill in these areas with appropriate data.
/// The `resize_term()` function attempts to resize all windows. However, due to
/// the calling convention of pads, it is not possible to resize these without
/// additional interaction with the application.
pub fn resize_term(size: Size) -> result!(()) {
    match ncurses::resize_term(size.lines, size.columns) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("resize_term", rc))
    }
}

/// Resize the standard and current windows to the specified dimensions, and
/// adjusts other bookkeeping data used by the NCurses library that record the
/// window dimensions (in particular the SIGWINCH handler).
pub fn resizeterm(size: Size) -> result!(()) {
    match ncurses::resizeterm(size.lines, size.columns) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("resizeterm", rc))
    }
}

/// The `ripoffline()` routine provides access to the same facility that `slk_init()`
/// uses to reduce the size of the screen. `ripoffline()` must be called before
/// `initscr()` or `newterm()` is called.
///
/// When the resulting initialization is done inside `initscr()`, the routine init
/// (supplied by the user) is called with two arguments:
/// - a window pointer to the one-line window that has been allocated and
/// - an `i32` with the number of columns in the window.
///
/// Inside this initialization routine, the `i32` variables `LINE`S and `COLS` are
/// not guaranteed to be accurate and `wrefresh()` or `doupdate()` must not be called.
/// It is allowable to call `wnoutrefresh()` during the initialization routine.
///
/// `ripoffline()` can be called up to five times before calling `initscr()` or `newterm()`.
pub fn ripoffline(line: Orientation, init: RipoffInit) -> result!(()) {
    match ncurses::ripoffline(line.value(), init) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("ripoffline", rc))
    }
}

/// Save the current state of the terminal modes in a buffer, usable by `resetty()`.
pub fn savetty() -> result!(()) {
    match ncurses::savetty() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("savetty", rc))
    }
}

/// The `scr_dump()` routine dumps the current contents of the virtual screen
/// to the file specificed by `path`.
pub fn scr_dump<P: AsRef<Path>>(path: P) -> result!(()) {
    match unsafe { ncurses::scr_dump(path_to_cstring_as_slice!(path)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scr_dump", rc))
    }
}

/// The `scr_init()` routine reads in the contents of `path` and uses them to
/// initialize the curses data structures about what the terminal currently has
/// on its screen. If the data is determined to be valid, curses bases its next
/// update of the screen on this information rather than clearing the screen
/// and starting from scratch.
pub fn scr_init<P: AsRef<Path>>(path: P) -> result!(()) {
    match unsafe { ncurses::scr_init(path_to_cstring_as_slice!(path)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scr_init", rc))
    }
}

/// The `scr_restore()` routine sets the virtual screen to the contents of the file
/// specificed by `path`, which must have been written using `scr_dump()`. The next call
/// to `doupdate()` restores the physical screen to the way it looked in the
/// dump file.
pub fn scr_restore<P: AsRef<Path>>(path: P) -> result!(()) {
    match unsafe { ncurses::scr_restore(path_to_cstring_as_slice!(path)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scr_restore", rc))
    }
}

/// The `scr_set()` routine is a combination of `scr_restore()` and `scr_init()`.
/// It tells the program that the information in `path` is what is currently
/// on the screen, and also what the program wants on the screen. This can be
/// thought of as a screen inheritance function.
pub fn scr_set<P: AsRef<Path>>(path: P) -> result!(()) {
    match unsafe { ncurses::scr_set(path_to_cstring_as_slice!(path)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scr_set", rc))
    }
}

/// For positive n, the `scrl()` routine scroll the window up `n` lines
/// (line i+n becomes i); otherwise scroll the window down `n` lines.
/// This involves moving the lines in the window character image structure.
/// The current cursor position is not changed.
///
/// For these functions to work, scrolling must be enabled via `scrollok()`.
pub fn scrl(n: i32) -> result!(()) {
    match ncurses::scrl(n) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scrl", rc))
    }
}

/// Scroll the screen upward by 1 lines.
pub fn scroll(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::scroll(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scroll", rc))
    }
}

/// Control what happens when the cursor of a window is moved off the edge of the
/// window or scrolling region, either as a result of a newline action on the
/// bottom line, or typing the last character of the last line. If flag is `false`,
/// the cursor is left on the bottom line. If flag is `true`, the window is scrolled
/// up one line. Note that in order to get the physical scrolling effect on the
/// terminal, it is also necessary to call `idlok()`.
pub fn scrollok(handle: WINDOW, flag: bool) -> result!(()) {
    match unsafe { ncurses::scrollok(handle, flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scrollok", rc))
    }
}

/// Sets the escape delay delay.
pub fn set_escdelay(ms: time::Duration) -> result!(()) {
    match ncurses::set_escdelay(i32::try_from(ms.as_millis())?) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("set_escdelay", rc))
    }
}

/// Sets the tab size.
pub fn set_tabsize(size: i32) -> result!(()) {
    match ncurses::set_tabsize(size) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("set_tabsize", rc))
    }
}

/// The `set_term()` routine is used to switch between different terminals.
/// The screen reference new becomes the new current terminal. The previous
/// terminal is returned by the routine. This is the only routine which
/// manipulates SCREEN pointers; all other routines affect only the current
/// terminal.
pub fn set_term(screen: SCREEN) -> result!(SCREEN) {
    unsafe { ncurses::set_term(screen) }.ok_or(ncurses_function_error!("set_term"))
}

/// Sets a complex character from a character and rendition.
pub fn setcchar<A, P, T>(ch: char, attrs: &A, color_pair: &P) -> result!(ComplexChar)
    where A: AttributesType<T>,
          P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    let mut cchar_buf: [cchar_t; 1] = unsafe { mem::zeroed() };
    let wchar_buf: [wchar_t; 2] = [wchar_t::try_from(u32::from(ch))?, 0x00];

    let cchar_ptr: *mut cchar_t = cchar_buf.as_mut_ptr();

    match unsafe { ncurses::setcchar(cchar_ptr, wchar_buf.as_ptr(), attrs.as_attr_t(), color_pair.as_short_t(), color_pair.as_mut_ptr()) } {
        OK => {
            assert!(!cchar_ptr.is_null(), "{}setcchar() : cchar_ptr.is_null()", MODULE_PATH);

            Ok(ComplexChar::from(unsafe { slice::from_raw_parts(cchar_ptr, 1)[0] }))
        },
        rc => Err(ncurses_function_error_with_rc!("setcchar", rc))
    }
}

/// Set the scrolling region ro `region`. All scrolling actions will take place in this region.
pub fn setscrreg(region: Region) -> result!(()) {
    match ncurses::setscrreg(region.top, region.bottom) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("setscrreg", rc))
    }
}

/// Set the virtual screen cursor to `origin`. If `None` then `leaveok()` is set `true`.
pub fn setsyx(origin: Option<Origin>) -> result!(()) {
    if let Some(origin) = origin {
        leaveok(newscr(), false)?;
        wmove(newscr(), origin)
    } else {
        leaveok(newscr(), true)
    }
}

/// Retrieve attributes of soft label.
pub fn slk_attr() -> normal::Attributes {
    normal::Attributes::_from(None, ncurses::slk_attr())
}

/// Turn off soft label attributes, without affecting other attributes.
pub fn slk_attr_off<A, T>(attrs: A) -> result!(())
    where A: AttributesType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::slk_attr_off(attrs.as_attr_t(), ptr::null_mut()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attr_off", rc))
    }
}

/// Turn on soft label attributes, without affecting other attributes.
pub fn slk_attr_on<A, T>(attrs: A) -> result!(())
    where A: AttributesType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::slk_attr_on(attrs.as_attr_t(), ptr::null_mut()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attr_on", rc))
    }
}

/// Sets the soft label attributes to `attrs`, with color specified by `color_pair`.
pub fn slk_attr_set<A, P, T>(attrs: A, color_pair: P) -> result!(())
    where A: AttributesType<T>,
          P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::slk_attr_set(attrs.as_attr_t(), color_pair.as_short_t(), color_pair.as_mut_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attr_set", rc))
    }
}

/// Turn off attribute `attrs` of the soft labels.
pub fn slk_attroff(attrs: normal::Attributes) -> result!(()) {
    match ncurses::slk_attroff(normal::Attributes::into(attrs)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attroff", rc))
    }
}

/// Turn on attribute `attrs` of the soft labels.
pub fn slk_attron(attrs: normal::Attributes) -> result!(()) {
    match ncurses::slk_attron(normal::Attributes::into(attrs)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attron", rc))
    }
}

/// Sets attribute `attrs` of the soft labels.
pub fn slk_attrset(attrs: normal::Attributes) -> result!(()) {
    match ncurses::slk_attrset(normal::Attributes::into(attrs)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attrset", rc))
    }
}

/// Clears the soft labels from the screen.
pub fn slk_clear() -> result!(()) {
    match ncurses::slk_clear() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_clear", rc))
    }
}

/// Corresponds to `color_set()` routine. It has an effect only if
/// soft labels are simulated on the bottom line of the screen.
pub fn slk_color(color_pair: normal::ColorPair) -> result!(()) {
    match ncurses::slk_color(color_pair.number()) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_color", rc))
    }
}

/// The `slk_init()` routine must be called before `initscr()` or `newterm()`
/// is called. `initscr()` eventually uses a line from `stdscr()` to emulate
/// the soft labels, then `fmt` determines how the labels are arranged on
/// the screen.
pub fn slk_init(fmt: SoftLabelType) -> result!(()) {
    match ncurses::slk_init(fmt.value()) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_init", rc))
    }
}

/// Returns the current label for label number `labnum`, with leading and
/// trailing blanks stripped.
pub fn slk_label(labnum: i32) -> Option<String> {
    ncurses::slk_label(labnum)
}

/// Mark for refresh but wait. This function updates the data structure representing
/// the desired state of the soft labels, but does not force an update of
/// the physical screen. To accomplish that, call `doupdate()`.
pub fn slk_noutrefresh() -> result!(()) {
    match ncurses::slk_noutrefresh() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_noutrefresh", rc))
    }
}

/// Update the soft labels immediately.
pub fn slk_refresh() -> result!(()) {
    match ncurses::slk_refresh() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_refresh", rc))
    }
}

/// Restores the soft labels to the screen after a `slk_clear()` has
/// been performed.
pub fn slk_restore() -> result!(()) {
    match ncurses::slk_restore() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_restore", rc))
    }
}

/// The `slk_set()` routine sets a soft label.
///
/// - labnum: is the label number, from 1 to 8 (12 if `slk_init()` was called
///           with `SoftLabelType::{FourFourFour,FourFourFourIndex}`);
/// - label:  is be the string to put on the label, up to eight (five if
///           `slk_init() was called with `SoftLabelType::{FourFour,FourFourIndex}`)
///           characters in length.
/// - fmt:    indicating whether the label is to be left-justified, centered
///           or right-justified.
pub fn slk_set<S: Into<String>>(labnum: i32, label: Option<S>, fmt: Justification) -> result!(()) {
    let label = label.and_then(|str| Some(str.into().to_string()));

    match unsafe { ncurses::slk_set(labnum, option_str_as_ptr!(label), fmt.value()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_set", rc))
    }
}

/// Forces all the soft labels to be output the next time a `slk_noutrefresh()`
/// is performed.
pub fn slk_touch() -> result!(()) {
    match ncurses::slk_touch() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_touch", rc))
    }
}

/// The wide string version of the `slk_set()` routine.
pub fn slk_wset(labnum: i32, label: Option<&WideString>, fmt: Justification) -> result!(()) {
    match unsafe { ncurses::slk_wset(labnum, option_widestr_as_ptr(label), fmt.value()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_wset", rc))
    }
}

/// Turn off the standout attribute. On some terminals this has the side
/// effect of turning off all attributes.
pub fn standend() -> result!(()) {
    match ncurses::standend() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("standend", rc))
    }
}

/// Turn on attribute A_STANDOUT.
pub fn standout() -> result!(()) {
    match ncurses::standout() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("standout", rc))
    }
}

/// Must be called if the programmer wants to use colors, and before any other
/// color manipulation routine is called. It is good practice to call this
/// routine right after `initscr()`.
///
/// `start_color()` initializes eight basic colors (black, red, green, yellow,
/// blue, magenta, cyan, and white), and two global variables in the NCurses
/// module, COLORS and COLOR_PAIRS, containing the maximum number of colors
/// and color-pairs the terminal can support. It also restores the colors on
/// the terminal to the values they had when the terminal was just turned on.
pub fn start_color() -> result!(()) {
    match ncurses::start_color() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("start_color", rc))
    }
}

/// Return a sub-window, whose upper-left corner is at `origin`, and whose width/height is `size`.
pub fn subpad(handle: WINDOW, size: Size, origin: Origin) -> result!(WINDOW) {
    unsafe { ncurses::subpad(handle, size.lines, size.columns, origin.y, origin.x).ok_or(ncurses_function_error!("subpad")) }
}

/// Return a sub-window, whose upper-left corner is at `origin`, and whose width/height is `size`.
///
/// By default, the sub-window will extend from the specified position to the
/// lower right corner of the window.
///
/// The sub-window shares memory with the window orig, so that changes made to
/// one window will affect both windows. When using this routine, it is necessary
/// to call `touchwin()` or `touchline()` on orig before calling `wrefresh()`
/// on the sub-window.
pub fn subwin(handle: WINDOW, size: Size, origin: Origin) -> result!(WINDOW) {
    unsafe { ncurses::subwin(handle, size.lines, size.columns, origin.y, origin.x).ok_or(ncurses_function_error!("subwin")) }
}

/// If flag is `true`, then `syncup()` is called automatically whenever there is a change in the window.
pub fn syncok(handle: WINDOW, flag: bool) -> result!(()) {
    match unsafe { ncurses::syncok(handle, flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("syncok", rc))
    }
}

/// At present this function is unimplemented.
pub fn term_attrs() -> attr_t {
    unimplemented!();
}

/// At present this function is unimplemented.
///
/// Return a logical OR of all video attributes supported by the terminal.
/// This information is useful when a NCurses program needs complete control
/// over the appearance of the screen.
pub fn termattrs() -> chtype {
    unimplemented!();
}

/// Return the value of the environment variable TERM, as a string,
/// truncated to 14 characters.
pub fn termname() -> result!(String) {
    ncurses::termname().ok_or(ncurses_function_error!("termname"))
}

/// Return the value of the Boolean capability corresponding to the terminfo
/// capability name capname as an `bool`.
pub fn tigetflag(capname: &str) -> result!(bool) {
    match unsafe { ncurses::tigetflag(str_to_cstring_as_slice!(capname)) } {
        -1 => Err(NCurseswError::InvalidCapability),
        0  => Ok(false),
        _  => Ok(true)
    }
}

/// Return the value of the numeric capability corresponding to the terminfo
/// capability name capname as an integer or `None` if it is canceled or
/// absent from the terminal description.
pub fn tigetnum(capname: &str) -> result!(Option<i32>) {
    match unsafe { ncurses::tigetnum(str_to_cstring_as_slice!(capname)) } {
        -2 => Err(NCurseswError::InvalidCapability),
        -1 => Ok(None),
        rc => Ok(Some(rc))
    }
}

/// Return the value of the string capability corresponding to the terminfo
/// capability name capname as a bytes object. Return None if capname is not
/// a terminfo “string capability”, or is canceled or absent from the terminal
/// description.
pub fn tigetstr(capname: &str) -> result!(Option<String>) {
    Ok(unsafe { ncurses::tigetstr(str_to_cstring_as_slice!(capname)) })
}

/// Set blocking or non-blocking read behavior for the window.
pub fn timeout(ms: time::Duration) -> result!(()) {
    Ok(ncurses::timeout(i32::try_from(ms.as_millis())?))
}

/// Pretend that `count` lines have been changed, beginning with line `start`.
///
/// This routines throw away all optimization information about which parts
/// of the window have been touched, by pretending that the entire window
/// has been drawn on. This is sometimes necessary when using overlapping
/// windows, since a change to one window affects the other window, but the
/// records of which lines have been changed in the other window do not
/// reflect the change.
pub fn touchline(handle: WINDOW, count: i32, start: i32) -> result!(()) {
    match unsafe { ncurses::touchline(handle, count, start) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("touchline", rc))
    }
}

/// Pretend the whole window has been changed, for purposes of drawing optimizations.
///
/// This routines throw away all optimization information about which parts
/// of the window have been touched, by pretending that the entire window
/// has been drawn on. This is sometimes necessary when using overlapping
/// windows, since a change to one window affects the other window, but the
/// records of which lines have been changed in the other window do not
/// reflect the change.
pub fn touchwin(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::touchwin(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("touchwin", rc))
    }
}

/// At present this function is unimplemented.
pub fn tparm<S: Into<String>>(_s: S) -> String {
    unimplemented!();
}

/// Specify that the file descriptor `file` be used for typeahead checking.
/// If `file` is None, then no typeahead checking is done.
///
/// The NCurses library does “line-breakout optimization” by looking for
/// typeahead periodically while updating the screen. If input is found,
/// and it is coming from a tty, the current update is postponed until
/// refresh or doupdate is called again, allowing faster response to
/// commands typed in advance. This function allows specifying a different
/// file descriptor for typeahead checking.
pub fn typeahead<FD: AsRawFd + Read>(file: Option<FD>) -> result!(()) {
    match ncurses::typeahead(file.map_or_else(|| -1, |file| file.as_raw_fd())) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("typeahead", rc))
    }
}

/// Return a string which is a printable representation of the character
/// c. Control characters are represented as a caret followed by the character,
/// for example as b'^C'. Printing characters are left as they are.
pub fn unctrl(c: ChtypeChar) -> result!(String) {
    ncurses::unctrl(ChtypeChar::into(c)).ok_or(ncurses_function_error!("unctrl"))
}

/// Push ch so the next `get_wch()` will return it.
///
/// Note: Only one ch can be pushed before `get_wch()` is called.
pub fn unget_wch(ch: WideChar) -> result!(()) {
    match ncurses::unget_wch(WideChar::into(ch)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("unget_wch", rc))
    }
}

/// Push `ch` so the next `getch()` will return it.
///
/// Note: Only one `ch` can be pushed before `getch()` is called.
pub fn ungetch(ch: char) -> result!(()) {
    match ncurses::ungetch(i32::from(ch as u8)) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("ungetch", rc))
    }
}

/// Mark all lines in the window as unchanged since the last call to `refresh()`.
pub fn untouchwin(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::untouchwin(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("untouchwin", rc))
    }
}

/// Allow use of default values for colors on terminals supporting this
/// feature. Use this to support transparency in your application.
/// The default color is assigned to the color `Color::TerminalDefault`.
///
/// The following are equivalent:
/// ```text
/// use_default_colors()?;
/// assume_default_colors(Colors::new(Color::TerminalDefault, Color::TerminalDefault));
/// ```
pub fn use_default_colors() -> result!(()) {
    match ncurses::use_default_colors() {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("use_default_colors", rc))
    }
}

/// If used, this function should be called before `initscr()` or `newterm()`
/// are called. When flag is `false`, the values of lines and columns specified
/// in the terminfo database will be used, even if environment variables
/// LINES and COLUMNS (used by default) are set, or if NCurses is running
/// in a window (in which case default behavior would be to use the window
/// size if LINES and COLUMNS are not set).
pub fn use_env(flag: bool) {
    ncurses::use_env(flag)
}

/// Controls whether the calling application is able to use user-defined or
/// nonstandard names which may be compiled into the terminfo description,
/// i.e., via the terminfo or termcap interfaces.
/// Normally these names are available for use, since the essential decision
/// is made by using the -x option of tic to compile extended terminal
/// definitions. However you can disable this feature to ensure compatibility
/// with other implementations of curses.
pub fn use_extended_names(enable: bool) -> bool {
    ncurses::use_extended_names(enable) == TRUE
}

/// Override locale-encoding checks.
///
/// The `use_legacy_coding()` function is an extension to the NCurses library.
/// It allows the caller to change the result of `unctrl()`, and suppress
/// related checks within the library that would normally cause nonprinting
/// characters to be rendered in visible form. This affects only 8-bit characters.
pub fn use_legacy_coding(level: Legacy) -> result!(Legacy) {
    let rc = ncurses::use_legacy_coding(level.value());

    Legacy::new(rc).ok_or(ncurses_function_error_with_rc!("use_legacy_coding", rc))
}

/// Determine how to compute terminal size. The `use_tioctl()` routine,
/// if used, should be called before `initscr()` or `newterm()` are called
/// (because those compute the screen size).
///
/// After `use_tioctl()` is called with `true` as an argument, NCurses
/// modifies the last step in its computation of screen size as follows:
/// - Checks if the $LINES and $COLUMNS environment variables are set to
///   a number greater than zero.
/// - for each, NCurses updates the corresponding environment variable
///   with the value that it has obtained via operating system call or
///   from the terminal database.
/// - NCurses re-fetches the value of the environment variables so that
///   it is still the environment variables which set the screen size.
///
/// The `use_env()` and `use_tioctl()` routines combine as summarized here:
///
/// use_env   use_tioctl   Summary
/// ----------------------------------------------------------------
/// true      false        This is the default behavior. NCurses uses operating
///                        system calls unless overridden by $LINES or $COLUMNS
///                        environment variables.
/// true      true         NCurses updates $LINES and $COLUMNS based on operating
///                        system calls.
/// false     true         NCurses ignores $LINES and $COLUMNS, uses operating
///                        system calls to obtain size.
/// false     false        NCurses relies on the terminal database to determine size.
pub fn use_tioctl(flag: bool) {
    ncurses::use_tioctl(flag)
}

/// At present this function is unimplemented.
pub fn vid_attr(_attrs: attr_t, _pair: short_t) -> i32 {
    unimplemented!();
}

/// At present this function is unimplemented.
pub fn vidattr(_attrs: chtype) -> i32 {
    unimplemented!();
}

/// Display a vertical line with length `number` consisting of the character `ch`.
pub fn vline(ch: ChtypeChar, number: i32) -> result!(()) {
    match ncurses::vline(ChtypeChar::into(ch), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("vline", rc))
    }
}

/// Display a vertical line with length `number` consisting of the character `ch`.
pub fn vline_set(wch: ComplexChar, number: i32) -> result!(()) {
    match ncurses::vline_set(&ComplexChar::into(wch), number) {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("vline_set", rc))
    }
}

/// Equivalent of `mvwadd_wch()` using `getcuryx()` as `origin`.
pub fn wadd_wch(handle: WINDOW, wch: ComplexChar) -> result!(()) {
    match unsafe { ncurses::wadd_wch(handle, &ComplexChar::into(wch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wadd_wch", rc))
    }
}

/// Equivalent of `mvwadd_wchnstr()` using `getcuryx()` as `origin`.
pub fn wadd_wchnstr(handle: WINDOW, wchstr: &ComplexString, number: i32) -> result!(()) {
    match unsafe { ncurses::wadd_wchnstr(handle, raw_with_nul_as_slice!(wchstr), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wadd_wchnstr", rc))
    }
}

/// Equivalent of `mvwadd_wchstr()` using `getcuryx()` as `origin`.
pub fn wadd_wchstr(handle: WINDOW, wchstr: &ComplexString) -> result!(()) {
    match unsafe { ncurses::wadd_wchstr(handle, raw_with_nul_as_slice!(wchstr)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wadd_wchstr", rc))
    }
}

/// Equivalent of `mvwaddch()` using `getcuryx()` as `origin`.
pub fn waddch(handle: WINDOW, ch: ChtypeChar) -> result!(()) {
    match unsafe { ncurses::waddch(handle, ChtypeChar::into(ch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("waddch", rc))
    }
}

/// Equivalent of `mvwaddchnstr()` using `getcuryx()` as `origin`.
pub fn waddchnstr(handle: WINDOW, chstr: &ChtypeString, number: i32) -> result!(()) {
    match unsafe { ncurses::waddchnstr(handle, raw_with_nul_as_slice!(chstr), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("waddchnstr", rc))
    }
}

/// Equivalent of `mvwaddchstr()` using `getcuryx()` as `origin`.
pub fn waddchstr(handle: WINDOW, chstr: &ChtypeString) -> result!(()) {
    match unsafe { ncurses::waddchstr(handle, raw_with_nul_as_slice!(chstr)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("waddchstr", rc))
    }
}

/// Equivalent of `mvwaddnstr()` using `getcuryx()` as `origin`.
pub fn waddnstr<S: Into<String>>(handle: WINDOW, str: S, number: i32) -> result!(()) {
    let str = str.into().to_string();

    match unsafe { ncurses::waddnstr(handle, c_str_with_nul!(str), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("waddnstr", rc))
    }
}

/// Equivalent of `mvwaddnwstr()` using `getcuryx()` as `origin`.
pub fn waddnwstr(handle: WINDOW, wstr: &WideString, number: i32) -> result!(()) {
    match unsafe { ncurses::waddnwstr(handle, raw_with_nul_as_slice!(wstr), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("waddnwstr", rc))
    }
}

/// Equivalent of `mvwaddstr()` using `getcuryx()` as `origin`.
pub fn waddstr<S: Into<String>>(handle: WINDOW, str: S) -> result!(()) {
    let str = str.into().to_string();

    match unsafe { ncurses::waddstr(handle, c_str_with_nul!(str)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("waddstr", rc))
    }
}

/// Equivalent of `mvwaddwstr()` using `getcuryx()` as `origin`.
pub fn waddwstr(handle: WINDOW, wstr: &WideString) -> result!(()) {
    match unsafe { ncurses::waddwstr(handle, raw_with_nul_as_slice!(wstr)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("waddwstr", rc))
    }
}

/// Retrieve attributes for the given window.
pub fn wattr_get(handle: WINDOW) -> result!(AttributesColorPairSet) {
    let mut attrs: [attr_t; 1] = [0];
    let mut color_pair: [short_t; 1] = [0];
    let mut opts: [i32; 1] = [0];

    match unsafe { ncurses::wattr_get(handle, attrs.as_mut_ptr(), color_pair.as_mut_ptr(), opts.as_mut_ptr() as *mut c_void) } {
        OK => Ok(match ncurses_colortype() {
                     NCursesColorType::Normal => {
                         AttributesColorPairSet::Normal(
                             normal::AttributesColorPair::new(
                                 normal::Attributes::_from(None, attrs[0]),
                                 normal::ColorPair::_from(None, color_pair[0])
                             )
                         )
                     },
                     NCursesColorType::Extend => {
                         AttributesColorPairSet::Extend(
                             extend::AttributesColorPair::new(
                                 extend::Attributes::_from(None, attrs[0]),
                                 extend::ColorPair::_from(None, opts[0])
                             )
                         )
                     }
              }),
        rc => Err(ncurses_function_error_with_rc!("wattr_get", rc))
    }
}

/// Turn off window attributes, without affecting other attributes.
pub fn wattr_off<A, T>(handle: WINDOW, attrs: A) -> result!(())
    where A: AttributesType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::wattr_off(handle, attrs.as_attr_t(), ptr::null_mut()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wattr_off", rc))
    }
}

/// Turn on window attributes, without affecting other attributes.
pub fn wattr_on<A, T>(handle: WINDOW, attrs: A) -> result!(())
    where A: AttributesType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::wattr_on(handle, attrs.as_attr_t(), ptr::null_mut()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wattr_on", rc))
    }
}

/// Sets the current attributes of the given window to `attrs`,
/// with color specified by `color_pair`.
pub fn wattr_set<A, P, T>(handle: WINDOW, attrs: A, color_pair: P) -> result!(())
    where A: AttributesType<T>,
          P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::wattr_set(handle, attrs.as_attr_t(), color_pair.as_short_t(), color_pair.as_mut_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wattr_set", rc))
    }
}

/// Remove attribute attrs from the “background” set applied to all writes
/// to the current window.
pub fn wattroff(handle: WINDOW, attrs: normal::Attributes) -> result!(()) {
    match unsafe { ncurses::wattroff(handle, normal::Attributes::into(attrs)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wattroff", rc))
    }
}

/// Add attribute attrs from the “background” set applied to all writes to
/// the current window.
pub fn wattron(handle: WINDOW, attrs: normal::Attributes) -> result!(()) {
    match unsafe { ncurses::wattron(handle, normal::Attributes::into(attrs)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wattron", rc))
    }
}

/// Set the “background” set of attributes to attrs. This set is initially
/// no attributes.
pub fn wattrset(handle: WINDOW, attrs: normal::Attributes) -> result!(()) {
    match unsafe { ncurses::wattrset(handle, normal::Attributes::into(attrs)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wattrset", rc))
    }
}

/// Set the background property of the specified window and then apply this setting
/// to every character position in that window.
///
/// According to X/Open Curses, it should do this:
/// - The rendition of every character on the screen is changed to the new background rendition.
/// - Wherever the former background character appears, it is changed to the new background character.
pub fn wbkgd(handle: WINDOW, ch: ChtypeChar) -> result!(()) {
    match unsafe { ncurses::wbkgd(handle, ChtypeChar::into(ch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wbkgd", rc))
    }
}

/// Manipulate the background of the specified window. The window background is a
/// character (with rendition). The attribute part of the background is combined
/// (OR'ed) with all non-blank characters that are written into the window with
/// `waddch()`. Both the character and attribute parts of the background are
/// combined with the blank characters. The background becomes a property of the
/// character and moves with the character through any scrolling and insert/delete
/// line/character operations.
///
/// To the extent possible on a particular terminal, the attribute part of the
/// background is displayed as the graphic rendition of the character put on the screen.
pub fn wbkgdset(handle: WINDOW, ch: ChtypeChar) {
    unsafe { ncurses::wbkgdset(handle, ChtypeChar::into(ch)) }
}

/// Set the background property of the window to the complex character `wch`.
/// The change is then applied to every character position in that window:
/// - The attribute of every character in the window is changed to the new
///   background attribute.
/// - Wherever the former background character appears, it is changed to
///   the new background character.
pub fn wbkgrnd(handle: WINDOW, wch: ComplexChar) -> result!(()) {
    match unsafe { ncurses::wbkgrnd(handle, &ComplexChar::into(wch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wbkgrnd", rc))
    }
}

/// Set the window’s background. A window’s background consists of a character
/// and it's combination of attributes as a complex character. The attribute
/// part of the background is combined (OR’ed) with all non-blank characters
/// that are written into the window. Both the character and attribute parts
/// of the background are combined with the blank characters. The background
/// becomes a property of the character and moves with the character through
/// any scrolling and insert/delete line/character operations.
pub fn wbkgrndset(handle: WINDOW, wch: ComplexChar) {
    unsafe { ncurses::wbkgrndset(handle, &ComplexChar::into(wch)) }
}

/// Draw a border around the edges of the window. Each parameter specifies the
/// character to use for a specific part of the border.
///
/// See the table below for more details.
///
/// ls : Left side
/// rs : Right side
/// ts : Top
/// bs : Bottom
/// tl : Upper-left corner
/// tr : Upper-right corner
/// bl : Bottom-left corner
/// br : Bottom-right corner
pub fn wborder(
    handle: WINDOW,
    ls: ChtypeChar,
    rs: ChtypeChar,
    ts: ChtypeChar,
    bs: ChtypeChar,
    tl: ChtypeChar,
    tr: ChtypeChar,
    bl: ChtypeChar,
    br: ChtypeChar) -> result!(())
{
    match unsafe { ncurses::wborder(
        handle,
        ChtypeChar::into(ls),
        ChtypeChar::into(rs),
        ChtypeChar::into(ts),
        ChtypeChar::into(bs),
        ChtypeChar::into(tl),
        ChtypeChar::into(tr),
        ChtypeChar::into(bl),
        ChtypeChar::into(br)
    ) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wborder", rc)),
    }
}

/// Draw a border around the edges of the window. Each parameter specifies the
/// character to use for a specific part of the border.
///
/// See the table below for more details.
///
/// ls : Left side
/// rs : Right side
/// ts : Top
/// bs : Bottom
/// tl : Upper-left corner
/// tr : Upper-right corner
/// bl : Bottom-left corner
/// br : Bottom-right corner
pub fn wborder_set(
    handle: WINDOW,
    ls: ComplexChar,
    rs: ComplexChar,
    ts: ComplexChar,
    bs: ComplexChar,
    tl: ComplexChar,
    tr: ComplexChar,
    bl: ComplexChar,
    br: ComplexChar) -> result!(())
{
    match unsafe { ncurses::wborder_set(
        handle,
        &ComplexChar::into(ls),
        &ComplexChar::into(rs),
        &ComplexChar::into(ts),
        &ComplexChar::into(bs),
        &ComplexChar::into(tl),
        &ComplexChar::into(tr),
        &ComplexChar::into(bl),
        &ComplexChar::into(br)
    ) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wborder_set", rc))
    }
}

/// Equivalent of `mvwchgat()` using `getcuryx()` as `origin`.
pub fn wchgat<A, P, T>(handle: WINDOW, number: i32, attrs: A, color_pair: P) -> result!(())
    where A: AttributesType<T>,
          P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::wchgat(handle, number, attrs.as_attr_t(), color_pair.as_short_t(), color_pair.as_const_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wchgat", rc))
    }
}

/// Like `erase()`, but also cause the whole window to be repainted upon
/// next call to `refresh()`.
pub fn wclear(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::wclear(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wclear", rc))
    }
}

/// Erase from cursor to the end of the window: all lines below the cursor
/// are deleted, and then the equivalent of `clrtoeol()` is performed.
pub fn wclrtobot(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::wclrtobot(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wclrtobot", rc))
    }
}

/// Erase from cursor to the end of the line.
pub fn wclrtoeol(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::wclrtoeol(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wclrtoeol", rc))
    }
}

/// Sets the current color of the given window to the foreground/background
/// combination described by the color_pair parameter.
pub fn wcolor_set<P, T>(handle: WINDOW, color_pair: P) -> result!(())
    where P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    match unsafe { ncurses::wcolor_set(handle, color_pair.as_short_t(), color_pair.as_mut_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wcolor_set", rc))
    }
}

/// Update the current cursor position of all the ancestors of the window
/// to reflect the current cursor position of the window.
pub fn wcursyncup(handle: WINDOW) {
    unsafe { ncurses::wcursyncup(handle) }
}

/// Delete any character at current position.
pub fn wdelch(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::wdelch(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wdelch", rc))
    }
}

/// Add a complex character `wch`, and immediately call `refresh()` on the window.
pub fn wecho_wchar(handle: WINDOW, wch: ComplexChar) -> result!(()) {
    match unsafe { ncurses::wecho_wchar(handle, &ComplexChar::into(wch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wecho_wchar", rc))
    }
}

/// Add a character (withrendition) `ch`, and immediately call `refresh()` on the window.
pub fn wechochar(handle: WINDOW, ch: ChtypeChar) -> result!(()) {
    match unsafe { ncurses::wechochar(handle, ChtypeChar::into(ch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wechochar", rc))
    }
}

/// Clear the window.
pub fn werase(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::werase(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("werase", rc))
    }
}

/// Equivalent of `mvwget_wch()` using `getcuryx()` as `origin`.
pub fn wget_wch(handle: WINDOW) -> result!(CharacterResult<WideChar>) {
    let mut wch: [wint_t; 1] = [0];

    match unsafe { ncurses::wget_wch(handle, wch.as_mut_ptr()) } {
        EINTR        => Err(NCurseswError::InterruptedCall),
        #[cfg(feature = "key_resize_as_error")]
        KEY_RESIZE   => Err(NCurseswError::KeyResize),
        KEY_CODE_YES => {
            match i32::try_from(wch[0])? {
                #[cfg(feature = "key_resize_as_error")]
                KEY_RESIZE => Err(NCurseswError::KeyResize),
                _          => Ok(CharacterResult::Key(KeyBinding::try_from(wch[0])?))
            }
        },
        rc           => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("wget_wch", rc))
            } else {
                Ok(CharacterResult::Character(WideChar::from(wch[0])))
            }
        }
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use wgetn_wstr() instead")]
/// Equivalent of `mvwget_wstr()` using `getcuryx()` as `origin`.
pub fn wget_wstr(handle: WINDOW) -> result!(WideString) {
    let mut buf: [wint_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wint_t = buf.as_mut_ptr();

    match unsafe { ncurses::wget_wstr(handle, ptr) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("wget_wstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}wget_wstr() : ptr.is_null()", MODULE_PATH);

                let buf_as_bytes = unsafe { slice::from_raw_parts(ptr as *mut wchar_t, LINE_MAX) };

                for (idx, &byte) in buf_as_bytes.iter().enumerate() {
                    if byte == 0x00 {
                        return Ok(WideString::from(&buf_as_bytes[..idx]));
                    }
                }

                Ok(WideString::from(buf_as_bytes))
            }
        }
    }
}

/// Returns the specified window's current background character as a complex character.
pub fn wgetbkgrnd(handle: WINDOW) -> result!(ComplexChar) {
    let mut wch: [cchar_t; 1] = unsafe { mem::zeroed() };

    match unsafe { ncurses::wgetbkgrnd(handle, wch.as_mut_ptr()) } {
        OK => Ok(ComplexChar::from(wch[0])),
        rc => Err(ncurses_function_error_with_rc!("wgetbkgrnd", rc))
    }
}

/// Equivalent of `mvwgetch()` using `getcuryx()` as `origin`.
pub fn wgetch(handle: WINDOW) -> result!(CharacterResult<char>) {
    match unsafe { ncurses::wgetch(handle) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        #[cfg(feature = "key_resize_as_error")]
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("wgetch", rc))
            } else if (KEY_MIN..=KEY_MAX).contains(&rc) {
                Ok(CharacterResult::Key(KeyBinding::from(rc)))
            } else {
                Ok(CharacterResult::Character(char::from(u8::try_from(i8::try_from(rc)?)?)))
            }
        }
    }
}

/// Returns the delay timeout as set in `wtimeout()`.
pub fn wgetdelay(handle: WINDOW) -> result!(time::Duration) {
    Ok(time::Duration::from_millis(u64::try_from(unsafe { ncurses::wgetdelay(handle) })?))
}

/// Equivalent of `mvwgetn_wstr()` using `getcuryx()` as `origin`.
pub fn wgetn_wstr(handle: WINDOW, number: i32) -> result!(WideString) {
    assert!(number <= LINE_MAX as i32, "{}wgetn_wstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [wint_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wint_t = buf.as_mut_ptr();

    match unsafe { ncurses::wgetn_wstr(handle, ptr, number) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("wgetn_wstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}wgetn_wstr() : ptr.is_null()", MODULE_PATH);

                let buf_as_bytes = unsafe { slice::from_raw_parts(ptr as *mut wchar_t, LINE_MAX) };

                for (idx, &byte) in buf_as_bytes.iter().enumerate() {
                    if byte == 0x00 {
                        return Ok(WideString::from(&buf_as_bytes[..idx]));
                    }
                }

                Ok(WideString::from(buf_as_bytes))
            }
        }
    }
}

/// Equivalent of `mvwgetnstr()` using `getcuryx()` as `origin`.
pub fn wgetnstr(handle: WINDOW, number: i32) -> result!(String) {
    assert!(number <= LINE_MAX as i32, "{}wgetnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    match unsafe { ncurses::wgetnstr(handle, ptr, number) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("wgetnstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}wgetnstr() : ptr.is_null()", MODULE_PATH);

                Ok(unsafe { FromCStr::from_c_str(ptr) })
            }
        }
    }
}

/// Returns the parent WINDOW pointer for sub-windows, or `None` for
/// windows having no parent.
pub fn wgetparent(handle: WINDOW) -> Option<WINDOW> {
    unsafe { ncurses::wgetparent(handle) }
}

/// Returns the top and bottom rows for the scrolling margin as set
/// by `wsetscrreg()`.
pub fn wgetscrreg(handle: WINDOW) -> result!(Region) {
    let mut top: [i32; 1] = [0];
    let mut bottom: [i32; 1] = [0];

    match unsafe { ncurses::wgetscrreg(handle, top.as_mut_ptr(), bottom.as_mut_ptr()) } {
        OK => Ok(Region { top: top[0], bottom: bottom[0] }),
        rc => Err(ncurses_function_error_with_rc!("wgetscrreg", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use wgetnstr() instead")]
/// Equivalent of `mvwgetstr()` using `getcuryx()` as `origin`.
pub fn wgetstr(handle: WINDOW) -> result!(String) {
    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    match unsafe { ncurses::wgetstr(handle, ptr) } {
        EINTR      => Err(NCurseswError::InterruptedCall),
        KEY_RESIZE => Err(NCurseswError::KeyResize),
        rc         => {
            if rc.is_negative() {
                Err(ncurses_function_error_with_rc!("wgetstr", rc))
            } else {
                assert!(!ptr.is_null(), "{}wgetstr() : ptr.is_null()", MODULE_PATH);

                Ok(unsafe { FromCStr::from_c_str(ptr) })
            }
        }
    }
}

/// Equivalent of `mvwhline()` using `getcuryx()` as `origin`.
pub fn whline(handle: WINDOW, ch: ChtypeChar, number: i32) -> result!(()) {
    match unsafe { ncurses::whline(handle, ChtypeChar::into(ch), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("whline", rc))
    }
}

/// Equivalent of `mvwhline_set()` using `getcuryx()` as `origin`.
pub fn whline_set(handle: WINDOW, wch: ComplexChar, number: i32) -> result!(()) {
    match unsafe { ncurses::whline_set(handle, &ComplexChar::into(wch), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("whline_set", rc))
    }
}

/// Equivalent of `mvwin_wch()` using `getcuryx()` as `origin`.
pub fn win_wch(handle: WINDOW) -> result!(ComplexChar) {
    let mut wcval: [cchar_t; 1] = unsafe { mem::zeroed() };

    match unsafe { ncurses::win_wch(handle, wcval.as_mut_ptr()) } {
        OK => Ok(ComplexChar::from(wcval[0])),
        rc => Err(ncurses_function_error_with_rc!("win_wch", rc))
    }
}

/// Equivalent of `mvwin_wchnstr()` using `getcuryx()` as `origin`.
pub fn win_wchnstr(handle: WINDOW, number: i32) -> result!(ComplexString) {
    assert!(number <= LINE_MAX as i32, "{}win_wchnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [cchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut cchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::win_wchnstr(handle, ptr, number) } {
        OK => {
            assert!(!ptr.is_null(), "{}win_wchnstr() : ptr.is_null()", MODULE_PATH);

            Ok(ComplexString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(number)?) }))
        },
        rc => Err(ncurses_function_error_with_rc!("win_wchnstr", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use win_wchnstr() instead")]
/// Equivalent of `mvwin_wchstr()` using `getcuryx()` as `origin`.
pub fn win_wchstr(handle: WINDOW) -> result!(ComplexString) {
    let mut buf: [cchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut cchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::win_wchstr(handle, ptr) } {
        OK => {
            assert!(!ptr.is_null(), "{}win_wchstr() : ptr.is_null()", MODULE_PATH);

            Ok(ComplexString::from(unsafe { slice::from_raw_parts(ptr, LINE_MAX) }))
        },
        rc => Err(ncurses_function_error_with_rc!("win_wchstr", rc))
    }
}

/// Equivalent of `mvwinch()` using `getcuryx()` as `origin`.
pub fn winch(handle: WINDOW) -> ChtypeChar {
    ChtypeChar::from(unsafe { ncurses::winch(handle) })
}

/// Equivalent of `mvwinchnstr()` using `getcuryx()` as `origin`.
pub fn winchnstr(handle: WINDOW, number: i32) -> result!(ChtypeString) {
    assert!(number <= LINE_MAX as i32, "{}winchnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [chtype; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut chtype = buf.as_mut_ptr();

    let len = unsafe { ncurses::winchnstr(handle, ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("winchnstr", len))
    } else {
        assert!(!ptr.is_null(), "{}winchnstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}winchnstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(ChtypeString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use winchnstr() instead")]
/// Equivalent of `mvwinchstr()` using `getcuryx()` as `origin`.
pub fn winchstr(handle: WINDOW) -> result!(ChtypeString) {
    let mut buf: [chtype; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut chtype = buf.as_mut_ptr();

    let len = unsafe { ncurses::winchstr(handle, ptr) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("inchstr", len))
    } else {
        assert!(!ptr.is_null(), "{}winchstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}winchstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(ChtypeString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

/// Equivalent of `mvwinnstr()` using `getcuryx()` as `origin`.
pub fn winnstr(handle: WINDOW, number: i32) -> result!(String) {
    assert!(number <= LINE_MAX as i32, "{}winnstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    let len = unsafe { ncurses::winnstr(handle, ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("winnstr", len))
    } else {
        assert!(!ptr.is_null(), "{}winnstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}winnstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(unsafe { FromCStr::from_c_str(ptr) })
    }
}

/// Equivalent of `mvwinnwstr()` using `getcuryx()` as `origin`.
pub fn winnwstr(handle: WINDOW, number: i32) -> result!(WideString) {
    assert!(number <= LINE_MAX as i32, "{}winnwstr() : number={}, LINE_MAX={}", MODULE_PATH, number, LINE_MAX);

    let mut buf: [wchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wchar_t = buf.as_mut_ptr();

    let len = unsafe { ncurses::winnwstr(handle, ptr, number) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("winnwstr", len))
    } else {
        assert!(!ptr.is_null(), "{}winnwstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}winnwstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(WideString::from(unsafe { slice::from_raw_parts(ptr, usize::try_from(len)?) }))
    }
}

/// Equivalent of `mvwins_nwstr()` using `getcuryx()` as `origin`.
pub fn wins_nwstr(handle: WINDOW, wstr: &WideString, number: i32) -> result!(()) {
    match unsafe { ncurses::wins_nwstr(handle, raw_with_nul_as_slice!(wstr), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wins_nwstr", rc))
    }
}

/// Equivalent of `mvwins_wch()` using `getcuryx()` as `origin`.
pub fn wins_wch(handle: WINDOW, wch: ComplexChar) -> result!(()) {
    match unsafe { ncurses::wins_wch(handle, &ComplexChar::into(wch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wins_wch", rc))
    }
}

/// Equivalent of `mvwins_wstr()` using `getcuryx()` as `origin`.
pub fn wins_wstr(handle: WINDOW, wstr: &WideString) -> result!(()) {
    match unsafe { ncurses::wins_wstr(handle, raw_with_nul_as_slice!(wstr)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wins_wstr", rc))
    }
}

/// Equivalent of `mvwinsch()` using `getcuryx()` as `origin`.
pub fn winsch(handle: WINDOW, ch: ChtypeChar) -> result!(()) {
    match unsafe { ncurses::winsch(handle, ChtypeChar::into(ch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("winsch", rc))
    }
}

/// For positive `n`, insert `n` lines into the specified window above the
/// current line. The `n` bottom lines are lost. For negative `n`, delete
/// `n` lines (starting with the one under the cursor), and move the
/// remaining lines up. The bottom `n` lines are cleared. The current
/// cursor position remains the same.
pub fn winsdelln(handle: WINDOW, n: i32) -> result!(()) {
    match unsafe { ncurses::winsdelln(handle, n) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("winsdelln", rc))
    }
}

/// Insert a blank line under the cursor. All following lines are moved down by one line.
pub fn winsertln(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::winsertln(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("winsertln", rc))
    }
}

/// Equivalent of `mvwinsnstr()` using `getcuryx()` as `origin`.
pub fn winsnstr<S: Into<String>>(handle: WINDOW, str: S, number: i32) -> result!(()) {
    let str = str.into().to_string();

    match unsafe { ncurses::winsnstr(handle, c_str_with_nul!(str), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("winsnstr", rc))
    }
}

/// Equivalent of `mvwinsstr()` using `getcuryx()` as `origin`.
pub fn winsstr<S: Into<String>>(handle: WINDOW, str: S) -> result!(()) {
    let str = str.into().to_string();

    match unsafe { ncurses::winsstr(handle, c_str_with_nul!(str)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("winsstr", rc))
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use winnstr() instead")]
/// Equivalent of `mvwinstr()` using `getcuryx()` as `origin`.
pub fn winstr(handle: WINDOW) -> result!(String) {
    let mut buf: [i8; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut i8 = buf.as_mut_ptr();

    let len = unsafe { ncurses::winstr(handle, ptr) };

    if len.is_negative() {
        Err(ncurses_function_error_with_rc!("winstr", len))
    } else {
        assert!(!ptr.is_null(), "{}winstr() : ptr.is_null()", MODULE_PATH);
        assert!(len > 0 && len <= LINE_MAX as i32, "{}winstr() : len={}, LINE_MAX={}", MODULE_PATH, len, LINE_MAX);

        Ok(unsafe { FromCStr::from_c_str(ptr) })
    }
}

#[deprecated(since = "0.1.2", note = "underlying native function can cause undefined behaviour. Use winnwstr() instead")]
/// Equivalent of `mvwinwstr()` using `getcuryx()` as `origin`.
pub fn winwstr(handle: WINDOW) -> result!(WideString) {
    let mut buf: [wchar_t; LINE_MAX] = unsafe { mem::zeroed() };
    let ptr: *mut wchar_t = buf.as_mut_ptr();

    match unsafe { ncurses::winwstr(handle, ptr) } {
        OK => {
            assert!(!ptr.is_null(), "{}winwstr() : ptr.is_null()", MODULE_PATH);

            Ok(WideString::from(unsafe { slice::from_raw_parts(ptr, LINE_MAX) }))
        },
        rc => Err(ncurses_function_error_with_rc!("winwstr", rc))
    }
}

/// Move cursor to `origin`.
pub fn wmove(handle: WINDOW, origin: Origin) -> result!(()) {
    match unsafe { ncurses::wmove(handle, origin.y, origin.x) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wmove", rc))
    }
}

/// Mark for refresh but wait. This function updates the data structure representing
/// the desired state of the window, but does not force an update of the physical
/// screen. To accomplish that, call `doupdate()`.
pub fn wnoutrefresh(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::wnoutrefresh(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wnoutrefresh", rc))
    }
}

/// Indicate that `region` are corrupted and should be completely redrawn on the
/// next `refresh()` call.
pub fn wredrawln(handle: WINDOW, region: Region) -> result!(()) {
    match unsafe { ncurses::wredrawln(handle, region.top, region.bottom) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wredrawln", rc))
    }
}

/// Update the display immediately (sync actual screen with previous
/// drawing/deleting methods).
pub fn wrefresh(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::wrefresh(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wrefresh", rc))
    }
}

/// Reallocate storage for a NCurses window to adjust its dimensions to the
/// specified values. If either dimension is larger than the current values,
/// the window’s data is filled with blanks that have the current background
/// rendition (as set by `bkgdset()`) merged into them.
pub fn wresize(handle: WINDOW, size: Size) -> result!(()) {
    match unsafe { ncurses::wresize(handle, size.lines, size.columns) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wresize", rc))
    }
}

/// For positive n, the `wscrl()` routine scroll the window up `n` lines
/// (line i+n becomes i); otherwise scroll the window down `n` lines.
/// This involves moving the lines in the window character image structure.
/// The current cursor position is not changed.
///
/// For these functions to work, scrolling must be enabled via `scrollok()`.
pub fn wscrl(handle: WINDOW, n: i32) -> result!(()) {
    match unsafe { ncurses::wscrl(handle, n) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wscrl", rc))
    }
}

/// Set the scrolling region ro `region`. All scrolling actions will take place in this region.
pub fn wsetscrreg(handle: WINDOW, region: Region) -> result!(()) {
    match unsafe { ncurses::wsetscrreg(handle, region.top, region.bottom) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wsetscrreg", rc))
    }
}

/// Turn off the standout attribute. On some terminals this has the side
/// effect of turning off all attributes.
pub fn wstandend(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::wstandend(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wstandend", rc))
    }
}

/// Turn on attribute A_STANDOUT.
pub fn wstandout(handle: WINDOW) -> result!(()) {
    match unsafe { ncurses::wstandout(handle) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wstandout", rc))
    }
}

/// Touch each location in the window that has been touched in any of its
/// ancestor windows. This routine is called by `refresh()`, so it should
/// almost never be necessary to call it manually.
pub fn wsyncdown(handle: WINDOW) {
    unsafe { ncurses::wsyncdown(handle) }
}

/// Touch all locations in ancestors of the window that have been changed in the window.
pub fn wsyncup(handle: WINDOW) {
    unsafe { ncurses::wsyncup(handle) }
}

/// Set blocking or non-blocking read behavior for the window.
pub fn wtimeout(handle: WINDOW, ms: time::Duration) -> result!(()) {
    Ok(unsafe { ncurses::wtimeout(handle, i32::try_from(ms.as_millis())?) })
}

/// The `wtouchln()` routine makes `n` lines in the window, starting at `line`,
/// look as if they have (Changed::True) or have not (Changed::False) been
/// changed since the last call to `wrefresh()`.
pub fn wtouchln(handle: WINDOW, line: i32, n: i32, changed: Changed) -> result!(()) {
    let change = match changed {
        Changed::True  => 1,
        Changed::False => 0
    };

    match unsafe { ncurses::wtouchln(handle, line, n, change) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wtouchln", rc))
    }
}

/// The `wunctrl()` routine returns a wide character string which is a printable
/// representation of the character `ch`, ignoring attributes. Control characters
/// are displayed in the ^X notation. Printing characters are displayed as is.
pub fn wunctrl(ch: ComplexChar) -> result!(WideChar) {
    let mut wch: [cchar_t; 1] = [ComplexChar::into(ch)];

    match unsafe { ncurses::wunctrl(wch.as_mut_ptr()) } {
        //Some(ptr) => Ok(WideChar::from(unsafe { wchar_t::try_from(slice::from_raw_parts(ptr, 1)[0])? })),
        Some(ptr) => Ok(WideChar::from(unsafe { slice::from_raw_parts(ptr, 1)[0] })),
        None      => Err(ncurses_function_error!("wunctrl"))
    }
}

/// Equivalent of `mvwvline()` using `getcuryx()` as `origin`.
pub fn wvline(handle: WINDOW, ch: ChtypeChar, number: i32) -> result!(()) {
    match unsafe { ncurses::wvline(handle, ChtypeChar::into(ch), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wvline", rc))
    }
}

/// Equivalent of `mvwvline_set()` using `getcuryx()` as `origin`.
pub fn wvline_set(handle: WINDOW, wch: ComplexChar, number: i32) -> result!(()) {
    match unsafe { ncurses::wvline_set(handle, &ComplexChar::into(wch), number) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("wvline_set", rc))
    }
}

// screen `_sp` functions.

/// Screen function of `assume_default_colors()`.
pub fn assume_default_colors_sp<S, C, T>(screen: SCREEN, colors: S) -> result!(())
    where S: ColorsType<C, T>,
          C: ColorType<T>,
          T: ColorAttributeTypes
{
    assert!(screen == colors.screen().unwrap_or(ptr::null_mut()), "assume_default_colors_sp() : screen != colors.screen()");

    match unsafe { ncurses::assume_default_colors_sp(screen, colors.foreground().number(), colors.background().number()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("assume_default_colors_sp", rc))
    }
}

/// Screen function of `baudrate()`.
pub fn baudrate_sp(screen: SCREEN) -> i32 {
    unsafe { ncurses::baudrate_sp(screen) }
}

/// Screen function of `beep()`.
pub fn beep_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::beep_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("beep_sp", rc))
    }
}

/// Screen function of `can_change_color()`.
pub fn can_change_color_sp(screen: SCREEN) -> bool {
    unsafe { ncurses::can_change_color_sp(screen) }
}

/// Screen function of `cbreak()`.
pub fn cbreak_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::cbreak_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("cbreak_sp", rc))
    }
}

#[deprecated(since = "0.5.0", note = "Use normal::Color::rgb() or shims::ncurses::color_content_sp() instead")]
/// Screen function of `color_content()`.
pub fn color_content_sp(screen: SCREEN, color_number: short_t) -> result!(normal::RGB) {
    let mut r: [short_t; 1] = [0];
    let mut g: [short_t; 1] = [0];
    let mut b: [short_t; 1] = [0];

    match unsafe { ncurses::color_content_sp(screen, color_number, r.as_mut_ptr(), g.as_mut_ptr(), b.as_mut_ptr()) } {
        OK => Ok(normal::RGB::new(r[0], g[0], b[0])),
        rc => Err(ncurses_function_error_with_rc!("color_content_sp", rc))
    }
}

/// Screen function of `curs_set()`.
pub fn curs_set_sp(screen: SCREEN, cursor: CursorType) -> result!(CursorType) {
    let rc = unsafe { ncurses::curs_set_sp(screen, cursor.value()) };

    CursorType::new(rc).ok_or(ncurses_function_error_with_rc!("curs_set_sp", rc))
}

/// Screen function of `define_key()`.
pub fn define_key_sp<S: Into<String>>(screen: SCREEN, definition: Option<S>, keycode: KeyBinding) -> result!(()) {
    let definition = definition.and_then(|str| Some(str.into().to_string()));

    match unsafe { ncurses::define_key_sp(screen, option_str_as_ptr!(definition), KeyBinding::into(keycode)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("define_key_sp", rc))
    }
}

/// Screen function of `def_prog_mode()`.
pub fn def_prog_mode_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::def_prog_mode_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("def_prog_mode_sp", rc))
    }
}

/// Screen function of `def_shell_mode()`.
pub fn def_shell_mode_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::def_shell_mode_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("def_shell_mode_sp", rc))
    }
}

/// Screen function of `delay_output()`.
pub fn delay_output_sp(screen: SCREEN, ms: time::Duration) -> result!(()) {
    match unsafe { ncurses::delay_output_sp(screen, i32::try_from(ms.as_millis())?) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("delay_output_sp", rc))
    }
}

/// Screen function of `doupdate()`.
pub fn doupdate_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::doupdate_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("doupdate_sp", rc))
    }
}

/// Screen function of `echo()`.
pub fn echo_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::echo_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("echo_sp", rc))
    }
}

/// Screen function of `endwin()`.
pub fn endwin_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::endwin_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("endwin_sp", rc))
    }
}

/// Screen function of `erasechar()`.
pub fn erasechar_sp(screen: SCREEN) -> result!(char) {
    let rc = unsafe { ncurses::erasechar_sp(screen) };

    if rc.is_negative() {
        Err(ncurses_function_error_with_rc!("erasechar_sp", i32::from(rc)))
    } else {
        Ok(char::from(u8::try_from(rc)?))
    }
}

#[deprecated(since = "0.5.0", note = "Use extend::Color::rgb() or shims::ncurses::extended_color_content_sp() instead")]
/// Screen function of `extended_color_content()`.
pub fn extended_color_content_sp(screen: SCREEN, color_number: i32) -> result!(extend::RGB) {
    let mut r: [i32; 1] = [0];
    let mut g: [i32; 1] = [0];
    let mut b: [i32; 1] = [0];

    match unsafe { ncurses::extended_color_content_sp(screen, color_number, r.as_mut_ptr(), g.as_mut_ptr(), b.as_mut_ptr()) } {
        OK => Ok(extend::RGB::new(r[0], g[0], b[0])),
        rc => Err(ncurses_function_error_with_rc!("extended_color_content_sp", rc))
    }
}

#[deprecated(since = "0.5.0", note = "Use extend::ColorPair::colors() or shims::ncurses::extended_pair_content_sp() instead")]
/// Screen function of `extended_pair_content()`.
pub fn extended_pair_content_sp(screen: SCREEN, color_pair: i32) -> result!(extend::Colors) {
    let mut fg: [i32; 1] = [0];
    let mut bg: [i32; 1] = [0];

    match unsafe { ncurses::extended_pair_content_sp(screen, color_pair, fg.as_mut_ptr(), bg.as_mut_ptr()) } {
        OK => Ok(extend::Colors::new(extend::Color::_from(Some(screen), extend::ColorPalette::_from(fg[0])), extend::Color::_from(Some(screen), extend::ColorPalette::_from(bg[0])))),
        rc => Err(ncurses_function_error_with_rc!("extended_pair_content_sp", rc))
    }
}

/// Screen function of `extended_slk_color()`.
pub fn extended_slk_color_sp(screen: SCREEN, color_pair: extend::ColorPair) -> result!(()) {
    match unsafe { ncurses::extended_slk_color_sp(screen, color_pair.number()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("extended_slk_color_sp", rc))
    }
}

/// Screen function of `filter()`.
pub fn filter_sp(screen: SCREEN) {
    unsafe { ncurses::filter_sp(screen) }
}

#[deprecated(since = "0.5.0", note = "specified color_pair must go out of scope before reuse of it's color pair number otherwise unpredicable results may occur.")]
/// Screen function of `free_pair()`.
pub fn free_pair_sp<P, T>(screen: SCREEN, color_pair: P) -> result!(())
    where P:   ColorPairType<T>,
          i32: From<T>,
          T:   ColorAttributeTypes
{
    assert!(screen == color_pair.screen().unwrap_or(ptr::null_mut()), "free_pair_sp() : screen != color_pair.screen()");

    match unsafe { ncurses::free_pair_sp(screen, i32::from(color_pair.number())) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("free_pair_sp", rc))
    }
}

/// Screen function of `flash()`.
pub fn flash_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::flash_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("flash_sp", rc))
    }
}

/// Screen function of `flushinp()`.
pub fn flushinp_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::flushinp_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("flushinp_sp", rc))
    }
}

/// Screen function of `get_escdelay()`.
pub fn get_escdelay_sp(screen: SCREEN) -> result!(time::Duration) {
    Ok(time::Duration::from_millis(u64::try_from(unsafe { ncurses::get_escdelay_sp(screen) })?))
}

/// Screen function of `getwin()`.
pub fn getwin_sp<I: AsRawFd + Read>(screen: SCREEN, file: &I) -> result!(WINDOW) {
    unsafe { ncurses::getwin_sp(screen, fdopen(file, "r")?).ok_or(ncurses_function_error!("getwin_sp")) }
}

/// Screen function of `halfdelay()`.
pub fn halfdelay_sp(screen: SCREEN, tenths: time::Duration) -> result!(()) {
    match unsafe { ncurses::halfdelay_sp(screen, i32::try_from(tenths.as_secs())? / 10) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("halfdelay_sp", rc))
    }
}

/// Screen function of `has_colors()`.
pub fn has_colors_sp(screen: SCREEN) -> bool {
    unsafe { ncurses::has_colors_sp(screen) }
}

/// Screen function of `has_ic()`.
pub fn has_ic_sp(screen: SCREEN) -> bool {
    unsafe { ncurses::has_ic_sp(screen) }
}

/// Screen function of `has_il()`.
pub fn has_il_sp(screen: SCREEN) -> bool {
    unsafe { ncurses::has_il_sp(screen) }
}

/// Screen function of `has_key()`.
pub fn has_key_sp(screen: SCREEN, ch: KeyBinding) -> bool {
    unsafe { ncurses::has_key_sp(screen, KeyBinding::into(ch)) == TRUE }
}

#[deprecated(since = "0.5.0", note = "Use normal::Color::set_rgb() or shims::ncurses::init_color_sp() instead")]
/// Screen function of `init_color()`.
pub fn init_color_sp(screen: SCREEN, color_number: short_t, rgb: normal::RGB) -> result!(()) {
    if i32::from(color_number) >= COLORS() {
        Err(NCurseswError::ColorLimit)
    } else {
        match unsafe { ncurses::init_color_sp(screen, color_number, rgb.red(), rgb.green(), rgb.blue()) } {
            OK => {
                set_ncurses_colortype(NCursesColorType::Normal);

                Ok(())
            },
            rc => Err(ncurses_function_error_with_rc!("init_color_sp", rc))
        }
    }
}

#[deprecated(since = "0.4.0", note = "Use extend::Color::set_rgb() or shims::ncurses::init_extended_color_sp() instead")]
/// Screen function of `init_extended_color()`.
pub fn init_extended_color_sp(screen: SCREEN, color_number: i32, rgb: extend::RGB) -> result!(()) {
    if color_number >= COLORS() {
        Err(NCurseswError::ColorLimit)
    } else {
        match unsafe { ncurses::init_extended_color_sp(screen, color_number, rgb.red(), rgb.green(), rgb.blue()) } {
            OK => {
                set_ncurses_colortype(NCursesColorType::Extend);

                Ok(())
            },
            rc => Err(ncurses_function_error_with_rc!("init_extended_color_sp", rc))
        }
    }
}

#[deprecated(since = "0.5.0", note = "Use extend::ColorPair::new_sp() or shims::ncurses::init_extended_pair_sp() instead")]
/// Screen function of `init_extended_pair()`.
pub fn init_extended_pair_sp(screen: SCREEN, color_pair: i32, colors: extend::Colors) -> result!(extend::ColorPair) {
    if color_pair < 1 || color_pair >= COLOR_PAIRS() {
        Err(NCurseswError::ColorPairLimit)
    } else if colors.foreground().number() >= COLORS() || colors.background().number() >= COLORS() {
        Err(NCurseswError::ColorLimit)
    } else {
        match unsafe { ncurses::init_extended_pair_sp(screen, color_pair, colors.foreground().number(), colors.background().number()) } {
            OK => Ok(extend::ColorPair::_from(Some(screen), color_pair)),
            rc => Err(ncurses_function_error_with_rc!("init_extended_pair_sp", rc))
        }
    }
}

#[deprecated(since = "0.5.0", note = "Use normal::ColorPair::new_sp() or shims::ncurses::init_pair_sp() instead")]
/// Screen function of `init_pair()`.
pub fn init_pair_sp(screen: SCREEN, color_pair: short_t, colors: normal::Colors) -> result!(normal::ColorPair) {
    if color_pair < 1 || i32::from(color_pair) >= COLOR_PAIRS() {
        Err(NCurseswError::ColorPairLimit)
    } else if colors.foreground().number() >= COLORS() || colors.background().number() >= COLORS() {
        Err(NCurseswError::ColorLimit)
    } else {
        match unsafe { ncurses::init_pair_sp(screen, color_pair, short_t::try_from(colors.foreground().number())?, short_t::try_from(colors.background().number())?) } {
            OK => Ok(normal::ColorPair::_from(Some(screen), color_pair)),
            rc => Err(ncurses_function_error_with_rc!("init_pair_sp", rc))
        }
    }
}

/// Screen function of `intrflush()`.
pub fn intrflush_sp(screen: SCREEN, flag: bool) -> result!(()) {
    match unsafe { ncurses::intrflush_sp(screen, ptr::null_mut(), flag) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("intrflush_sp", rc))
    }
}

/// Screen function of `isendwin()`.
pub fn isendwin_sp(screen: SCREEN) -> bool {
    unsafe { ncurses::isendwin_sp(screen) }
}

/// Screen function of `is_term_resized()`.
pub fn is_term_resized_sp(screen: SCREEN, size: Size) -> bool {
    unsafe { ncurses::is_term_resized_sp(screen, size.lines, size.columns) }
}

/// Screen function of `keybound()`.
pub fn keybound_sp(screen: SCREEN, keycode: KeyBinding, count: i32) -> Option<String> {
    unsafe { ncurses::keybound_sp(screen, KeyBinding::into(keycode), count) }
}

/// Screen function of `key_defined()`.
pub fn key_defined_sp<S: Into<String>>(screen: SCREEN, definition: S) -> result!(Option<KeyBinding>) {
    let definition = definition.into().to_string();

    let rc = unsafe { ncurses::key_defined_sp(screen, c_str_with_nul!(definition)) };

    if rc.is_negative() {
        Err(ncurses_function_error_with_rc!("key_defined_sp", rc))
    } else if rc == 0 {
        Ok(None)
    } else {
        Ok(Some(KeyBinding::from(rc)))
    }
}

/// Screen function of `keyname()`.
pub fn keyname_sp(screen: SCREEN, c: KeyBinding) -> result!(String) {
    unsafe { ncurses::keyname_sp(screen, KeyBinding::into(c)).ok_or(ncurses_function_error!("keyname_sp")) }
}

/// Screen function of `keyok()`.
pub fn keyok_sp(screen: SCREEN, keycode: KeyBinding, enable: bool) -> result!(()) {
    match unsafe { ncurses::keyok_sp(screen, KeyBinding::into(keycode), enable) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("keyok_sp", rc))
    }
}

/// Screen function of `killchar()`.
pub fn killchar_sp(screen: SCREEN) -> result!(char) {
    let rc = unsafe { ncurses::killchar_sp(screen) };

    if rc.is_negative() {
        Err(ncurses_function_error_with_rc!("killchar_sp", i32::from(rc)))
    } else {
        Ok(char::from(u8::try_from(rc)?))
    }
}

/// Screen function of `longname()`.
pub fn longname_sp(screen: SCREEN) -> result!(String) {
    unsafe { ncurses::longname_sp(screen).ok_or(ncurses_function_error!("longname_sp")) }
}

/// Screen function of `mcprint()`.
pub fn mcprint_sp(screen: SCREEN, data: &[i8], len: i32) -> result!(i32) {
    match unsafe { ncurses::mcprint_sp(screen, data.as_ptr() as *mut i8, len) } {
        ERR => Err(ncurses_os_error!("mcprint_sp")),
        rc  => Ok(rc)
    }
}

/// Screen function of `mvcur()`.
pub fn mvcur_sp(screen: SCREEN, old: Origin, new: Origin) -> result!(()) {
    match unsafe { ncurses::mvcur_sp(screen, old.y, old.x, new.y, new.x) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("mvcur_sp", rc))
    }
}

#[deprecated(since = "0.5.0", note = "ncurses library call superseeded by native rust call. Use std::thread::sleep(dur: std::time::Duration) instead")]
/// Screen function of `namps()`.
pub fn napms_sp(screen: SCREEN, ms: time::Duration) -> result!(()) {
    match unsafe { ncurses::napms_sp(screen, i32::try_from(ms.as_millis())?) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("napms_sp", rc))
    }
}

/// Screen function of `newpad()`.
pub fn newpad_sp(screen: SCREEN, size: Size) -> result!(WINDOW) {
    unsafe { ncurses::newpad_sp(screen, size.lines, size.columns).ok_or(ncurses_function_error!("newpad_sp")) }
}

/// When creating a new screen, the library uses static variables which have
/// been preset, e.g. by `use_env()`, `filter()` etc. With the screen-pointer
/// extension, there are situations where it must create a current screen
/// before the unextended library does. The `new_prescr()` function is used
/// internally to handle these cases. It is also provided as an entrypoint
/// to allow applications to customize the library initialization.
pub fn new_prescr() -> result!(SCREEN) {
    unsafe { ncurses::new_prescr().ok_or(ncurses_function_error!("new_prescr")) }
}

/// Screen function of `newterm()`.
pub fn newterm_sp<S, O, I>(screen: SCREEN, term: Option<S>, output: &O, input: &I) -> result!(SCREEN)
    where S: Into<String>,
          O: AsRawFd + Write,
          I: AsRawFd + Read
{
    let term = term.and_then(|str| Some(str.into().to_string()));

    unsafe {
        ncurses::newterm_sp(
            screen,
            option_str_as_ptr!(term),
            fdopen(output, "wb+")?,
            fdopen(input, "rb+")?
        ).ok_or(ncurses_function_error!("newterm_sp"))
    }
}

/// Screen function of `newwin()`.
pub fn newwin_sp(screen: SCREEN, size: Size, origin: Origin) -> result!(WINDOW) {
    unsafe { ncurses::newwin_sp(screen, size.lines, size.columns, origin.y, origin.x).ok_or(ncurses_function_error!("newwin_sp")) }
}

/// Screen function of `nl()`.
pub fn nl_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::nl_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("nl_sp", rc))
    }
}

/// Screen function of `nocbreak()`.
pub fn nocbreak_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::nocbreak_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("nocbreak_sp", rc))
    }
}

/// Screen function of `noecho()`.
pub fn noecho_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::noecho_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("noecho_sp", rc))
    }
}

/// Screen function of `nofilter()`.
pub fn nofilter_sp(screen: SCREEN) {
    unsafe { ncurses::nofilter_sp(screen) }
}

/// Screen function of `nonl()`.
pub fn nonl_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::nonl_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("nonl_sp", rc))
    }
}

/// Screen function of `noqiflush()`.
pub fn noqiflush_sp(screen: SCREEN) {
    unsafe { ncurses::noqiflush_sp(screen) }
}

/// Screen function of `noraw()`.
pub fn noraw_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::noraw_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("noraw_sp", rc))
    }
}

#[deprecated(since = "0.5.0", note = "Use normal::ColorPair::colors() or shims::ncurses::pair_content_sp() instead")]
/// Screen function of `pair_content()`.
pub fn pair_content_sp(screen: SCREEN, color_pair: short_t) -> result!(normal::Colors) {
    let mut fg: [short_t; 1] = [0];
    let mut bg: [short_t; 1] = [0];

    match unsafe { ncurses::pair_content_sp(screen, color_pair, fg.as_mut_ptr(), bg.as_mut_ptr()) } {
        OK => Ok(normal::Colors::new(normal::Color::_from(Some(screen), normal::ColorPalette::_from(fg[0])), normal::Color::_from(Some(screen), normal::ColorPalette::_from(bg[0])))),
        rc => Err(ncurses_function_error_with_rc!("pair_content_sp", rc))
    }
}

/// Screen function of `qiflush()`.
pub fn qiflush_sp(screen: SCREEN) {
    unsafe { ncurses::qiflush_sp(screen) }
}

/// Screen function of `raw()`.
pub fn raw_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::raw_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("raw_sp", rc))
    }
}

#[deprecated(since = "0.5.0", note = "use with caution as this routine will reset all color pairs potentially before they go out of scope and the color pairs will default to terminal default foreground and backgound colors.")]
/// Screen function of `reset_color_pairs()`.
pub fn reset_color_pairs_sp(screen: SCREEN) {
    unsafe { ncurses::reset_color_pairs_sp(screen) }
}

/// Screen function of `reset_prog_mode()`.
pub fn reset_prog_mode_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::reset_prog_mode_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("reset_prog_mode_sp", rc))
    }
}

/// Screen function of `reset_shell_mode()`.
pub fn reset_shell_mode_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::reset_shell_mode_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("reset_shell_mode_sp", rc))
    }
}

/// Screen function of `resetty()`.
pub fn resetty_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::resetty_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("resetty_sp", rc))
    }
}

/// Screen function of `resize_term()`.
pub fn resize_term_sp(screen: SCREEN, size: Size) -> result!(()) {
    match unsafe { ncurses::resize_term_sp(screen, size.lines, size.columns) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("resize_term_sp", rc))
    }
}

/// Screen function of `resizeterm()`.
pub fn resizeterm_sp(screen: SCREEN, size: Size) -> result!(()) {
    match unsafe { ncurses::resizeterm_sp(screen, size.lines, size.columns) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("resizeterm_sp", rc))
    }
}

// int restartterm_sp(SCREEN*, NCURSES_CONST char*, int, int *);

/// Screen function of `ripoffline()`.
pub fn ripoffline_sp(screen: SCREEN, line: Orientation, init: RipoffInit) -> result!(()) {
    match unsafe { ncurses::ripoffline_sp(screen, line.value(), init) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("ripoffline_sp", rc))
    }
}

/// Screen function of `savetty()`.
pub fn savetty_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::savetty_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("savetty_sp", rc))
    }
}

/// Screen function of `scr_init()`.
pub fn scr_init_sp<P: AsRef<Path>>(screen: SCREEN, path: P) -> result!(()) {
    match unsafe { ncurses::scr_init_sp(screen, path_to_cstring_as_slice!(path)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scr_init_sp", rc))
    }
}

/// Screen function of `scr_restore()`.
pub fn scr_restore_sp<P: AsRef<Path>>(screen: SCREEN, path: P) -> result!(()) {
    match unsafe { ncurses::scr_restore_sp(screen, path_to_cstring_as_slice!(path)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scr_restore_sp", rc))
    }
}

/// Screen function of `scr_set()`.
pub fn scr_set_sp<P: AsRef<Path>>(screen: SCREEN, path: P) -> result!(()) {
    match unsafe { ncurses::scr_set_sp(screen, path_to_cstring_as_slice!(path)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("scr_set_sp", rc))
    }
}

// TERMINAL* set_curterm_sp(SCREEN*, TERMINAL*);

/// Screen function of `set_escdelay()`.
pub fn set_escdelay_sp(screen: SCREEN, ms: time::Duration) -> result!(()) {
    match unsafe { ncurses::set_escdelay_sp(screen, i32::try_from(ms.as_millis())?) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("set_escdelay_sp", rc))
    }
}

/// Screen function of `set_tabsize()`.
pub fn set_tabsize_sp(screen: SCREEN, size: i32) -> result!(()) {
    match unsafe { ncurses::set_tabsize_sp(screen, size) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("set_tabsize_sp", rc))
    }
}

/// Screen function of `slk_attroff()`.
pub fn slk_attroff_sp(screen: SCREEN, attrs: normal::Attributes) -> result!(()) {
    assert!(screen == attrs.screen().unwrap_or(ptr::null_mut()), "slk_attroff_sp() : screen != color_pair.screen()");

    match unsafe { ncurses::slk_attroff_sp(screen, normal::Attributes::into(attrs)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attroff_sp", rc))
    }
}

/// Screen function of `slk_attron()`.
pub fn slk_attron_sp(screen: SCREEN, attrs: normal::Attributes) -> result!(()) {
    assert!(screen == attrs.screen().unwrap_or(ptr::null_mut()), "slk_attron_sp() : screen != color_pair.screen()");

    match unsafe { ncurses::slk_attron_sp(screen, normal::Attributes::into(attrs)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attron_sp", rc))
    }
}

/// Screen function of `slk_attr_set()`.
pub fn slk_attr_set_sp<A, P, T>(screen: SCREEN, attrs: A, color_pair: P) -> result!(())
    where A: AttributesType<T>,
          P: ColorPairType<T>,
          T: ColorAttributeTypes
{
    assert!(screen == attrs.screen().unwrap_or(ptr::null_mut()), "slk_attr_set_sp() : screen != attrs.screen()");
    assert!(screen == color_pair.screen().unwrap_or(ptr::null_mut()), "slk_attr_set_sp() : screen != color_pair.screen()");

    match unsafe { ncurses::slk_attr_set_sp(screen, attrs.as_attr_t(), color_pair.as_short_t(), color_pair.as_mut_ptr()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attr_set_sp", rc))
    }
}

/// Screen function of `slk_attrset()`.
pub fn slk_attrset_sp(screen: SCREEN, attrs: normal::Attributes) -> result!(()) {
    assert!(screen == attrs.screen().unwrap_or(ptr::null_mut()), "slk_attrset_sp() : screen != attrs.screen()");

    match unsafe { ncurses::slk_attrset_sp(screen, normal::Attributes::into(attrs)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_attrset_sp", rc))
    }
}

/// Screen function of `slk_attr()`.
pub fn slk_attr_sp(screen: SCREEN) -> normal::Attributes {
    normal::Attributes::_from(Some(screen), unsafe { ncurses::slk_attr_sp(screen) })
}

/// Screen function of `slk_clear()`.
pub fn slk_clear_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::slk_clear_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_clear_sp", rc))
    }
}

/// Screen function of `slk_color()`.
pub fn slk_color_sp(screen: SCREEN, color_pair: normal::ColorPair) -> result!(()) {
    assert!(screen == color_pair.screen().unwrap_or(ptr::null_mut()), "slk_color_sp() : screen != color_pair.screen()");

    match unsafe { ncurses::slk_color_sp(screen, color_pair.number()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_color_sp", rc))
    }
}

/// Screen function of `slk_init()`.
pub fn slk_init_sp(screen: SCREEN, fmt: SoftLabelType) -> result!(()) {
    match unsafe { ncurses::slk_init_sp(screen, fmt.value()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_init_sp", rc))
    }
}

/// Screen function of `slk_label()`.
pub fn slk_label_sp(screen: SCREEN, labnum: i32) -> Option<String> {
    unsafe { ncurses::slk_label_sp(screen, labnum) }
}

/// Screen function of `slk_noutrefresh()`.
pub fn slk_noutrefresh_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::slk_noutrefresh_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_noutrefresh_sp", rc))
    }
}

/// Screen function of `slk_refresh()`.
pub fn slk_refresh_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::slk_refresh_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_refresh_sp", rc))
    }
}

/// Screen function of `slk_restore()`.
pub fn slk_restore_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::slk_restore_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_restore_sp", rc))
    }
}

/// Screen function of `slk_set()`.
pub fn slk_set_sp<S: Into<String>>(screen: SCREEN, label_number: i32, label: Option<S>, fmt: Justification) -> result!(()) {
    let label = label.and_then(|str| Some(str.into().to_string()));

    match unsafe { ncurses::slk_set_sp(screen, label_number, option_str_as_ptr!(label), fmt.value()) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_set_sp", rc))
    }
}

/// Screen function of `slk_touch()`.
pub fn slk_touch_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::slk_touch_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("slk_touch_sp", rc))
    }
}

/// Screen function of `start_color()`.
pub fn start_color_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::start_color_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("start_color_sp", rc))
    }
}

/// Screen function of `term_attrs()`.
pub fn term_attrs_sp(_screen: SCREEN) -> attr_t {
    unimplemented!();
}

/// Screen function of `termattrs()`.
pub fn termattrs_sp(_screen: SCREEN) -> chtype {
    unimplemented!();
}

/// Screen function of `termname()`.
pub fn termname_sp(screen: SCREEN) -> result!(String) {
    unsafe { ncurses::termname_sp(screen).ok_or(ncurses_function_error!("termname_sp")) }
}

/// Screen function of `typeahead()`.
pub fn typeahead_sp<FD: AsRawFd + Read>(screen: SCREEN, file: Option<FD>) -> result!(()) {
    match unsafe { ncurses::typeahead_sp(screen, file.map_or_else(|| -1, |file| file.as_raw_fd())) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("typeahead_sp", rc))
    }
}

/// Screen function of `unctrl()`.
pub fn unctrl_sp(screen: SCREEN, c: ChtypeChar) -> result!(String) {
    unsafe { ncurses::unctrl_sp(screen, ChtypeChar::into(c)).ok_or(ncurses_function_error!("unctrl_sp")) }
}

/// Screen function of `ungetch()`.
pub fn ungetch_sp(screen: SCREEN, ch: char) -> result!(()) {
    match unsafe { ncurses::ungetch_sp(screen, i32::from(ch as u8)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("ungetch_sp", rc))
    }
}

/// Screen function of `unget_wch()`.
pub fn unget_wch_sp(screen: SCREEN, ch: WideChar) -> result!(()) {
    match unsafe { ncurses::unget_wch_sp(screen, WideChar::into(ch)) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("unget_wch_sp", rc))
    }
}

/// Screen function of `use_default_colors()`.
pub fn use_default_colors_sp(screen: SCREEN) -> result!(()) {
    match unsafe { ncurses::use_default_colors_sp(screen) } {
        OK => Ok(()),
        rc => Err(ncurses_function_error_with_rc!("use_default_colors_sp", rc))
    }
}

/// Screen function of `use_env()`.
pub fn use_env_sp(screen: SCREEN, f: bool) {
    unsafe { ncurses::use_env_sp(screen, f) }
}

/// Screen function of `use_tioctl()`.
pub fn use_tioctl_sp(screen: SCREEN, f: bool) {
    unsafe { ncurses::use_tioctl_sp(screen, f) }
}

/// Screen function of `use_legacy_coding()`.
pub fn use_legacy_coding_sp(screen: SCREEN, level: Legacy) -> result!(Legacy) {
    let rc = unsafe { ncurses::use_legacy_coding_sp(screen, level.value()) };

    Legacy::new(rc).ok_or(ncurses_function_error_with_rc!("use_legacy_coding_sp", rc))
}

/// Screen function of `vid_attr()`.
pub fn vid_attr_sp(_screen: SCREEN, _attrs: attr_t, _pair: short_t) -> i32 {
    unimplemented!();
}

/// Screen function of `vidattr()`.
pub fn vidattr_sp(_screen: SCREEN, _attrs: chtype) -> i32 {
    unimplemented!();
}

// int vid_puts_sp(SCREEN*, attr_t, short, void *, NCURSES_SP_OUTC);

// int vidputs_sp(SCREEN*, chtype, NCURSES_SP_OUTC);

/// Screen function of `wunctrl()`.
pub fn wunctrl_sp(screen: SCREEN, ch: ComplexChar) -> result!(WideChar) {
    let mut wch: [cchar_t; 1] = [ComplexChar::into(ch)];

    match unsafe { ncurses::wunctrl_sp(screen, wch.as_mut_ptr()) } {
        //Some(ptr) => Ok(WideChar::from(unsafe { wchar_t::try_from(slice::from_raw_parts(ptr, 1)[0])? })),
        Some(ptr) => Ok(WideChar::from(unsafe { slice::from_raw_parts(ptr, 1)[0] })),
        None      => Err(ncurses_function_error!("wunctrl_sp"))
    }
}

/// Screen function of `erasewchar()`.
pub fn erasewchar_sp(screen: SCREEN) -> result!(WideChar) {
    let mut wch: [wchar_t; 1] = [0];

    match unsafe { ncurses::erasewchar_sp(screen, wch.as_mut_ptr()) } {
        OK => Ok(WideChar::from(wch[0])),
        rc => Err(ncurses_function_error_with_rc!("erasewchar_sp", rc))
    }
}

/// Screen function of `killwchar()`.
pub fn killwchar_sp(screen: SCREEN) -> result!(WideChar) {
    let mut wch: [wchar_t; 1] = [0];

    match unsafe { ncurses::killwchar_sp(screen, wch.as_mut_ptr()) } {
        OK => Ok(WideChar::from(wch[0])),
        rc => Err(ncurses_function_error_with_rc!("killwchar_sp", rc))
    }
}

// private functions.

// get a file stream from a file descriptor.
fn fdopen<FD: AsRawFd>(file: &FD, mode: &str) -> result!(ncurses::FILE) {
    unsafe { funcs::fdopen(file, c_str_with_nul!(mode)).ok_or(ncurses_os_error!("fdopen")) }
}

fn path_to_cstring_as_vec<P: AsRef<Path>>(path: P) -> result!(Vec<u8>) {
    str_to_cstring_as_vec(path.as_ref().to_str().expect("path is invalid!!!"))
}

fn str_to_cstring_as_vec(str: &str) -> result!(Vec<u8>) {
    Ok(ffi::CString::new(str)?.into_bytes_with_nul())
}

fn option_widestr_as_ptr(wstr: Option<&WideString>) -> *const wchar_t {
    // mbstowcs
    wstr.map_or_else(ptr::null, |name| raw_with_nul_as_slice!(name).as_ptr())
}