File: mswproc.c

package info (click to toggle)
glhack 1.2-4
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 26,744 kB
  • sloc: ansic: 208,571; cpp: 13,139; yacc: 2,005; makefile: 1,155; lex: 377; sh: 121; awk: 89; sed: 11
file content (2353 lines) | stat: -rw-r--r-- 74,100 bytes parent folder | download | duplicates (22)
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
/* Copyright (C) 2001 by Alex Kompel <shurikk@pacbell.net> */
/* NetHack may be freely redistributed.  See license for details. */

/*
 * This file implements the interface between the window port specific
 * code in the mswin port and the rest of the nethack game engine. 
*/

#include "hack.h"
#include "dlb.h"
#include "func_tab.h"   /* for extended commands */
#include "winMS.h"
#include "mhmap.h"
#include "mhstatus.h"
#include "mhtext.h"
#include "mhmsgwnd.h"
#include "mhmenu.h"
#include "mhsplash.h"
#include "mhmsg.h"
#include "mhinput.h"
#include "mhaskyn.h"
#include "mhdlg.h"
#include "mhrip.h"
#include "mhmain.h"
#include "mhfont.h"
#include "resource.h"

#define LLEN 128

extern const char *killed_by_prefix[];

#ifdef _DEBUG
extern void logDebug(const char *fmt, ...);
#else
void logDebug(const char *fmt, ...) { }
#endif

static void mswin_main_loop(void);
static BOOL initMapTiles(void);
static void mswin_color_from_string(char *colorstring, HBRUSH* brushptr, COLORREF *colorptr);
static void prompt_for_player_selection(void);

#define TOTAL_BRUSHES	10
HBRUSH brush_table[TOTAL_BRUSHES];
int max_brush = 0;

HBRUSH menu_bg_brush = NULL;
HBRUSH menu_fg_brush = NULL;
HBRUSH text_bg_brush = NULL;
HBRUSH text_fg_brush = NULL;
HBRUSH status_bg_brush = NULL;
HBRUSH status_fg_brush = NULL;
HBRUSH message_bg_brush = NULL;
HBRUSH message_fg_brush = NULL;

COLORREF menu_bg_color = RGB(0, 0, 0);
COLORREF menu_fg_color = RGB(0xFF, 0xFF, 0xFF);
COLORREF text_bg_color = RGB(0, 0, 0);
COLORREF text_fg_color = RGB(0xFF, 0xFF, 0xFF);
COLORREF status_bg_color = RGB(0, 0, 0);
COLORREF status_fg_color = RGB(0xFF, 0xFF, 0xFF);
COLORREF message_bg_color = RGB(0, 0, 0);
COLORREF message_fg_color = RGB(0xFF, 0xFF, 0xFF);

/* Interface definition, for windows.c */
struct window_procs mswin_procs = {
    "MSWIN",
    WC_COLOR|WC_HILITE_PET|WC_ALIGN_MESSAGE|WC_ALIGN_STATUS|
	WC_INVERSE|WC_SCROLL_AMOUNT|WC_SCROLL_MARGIN|WC_MAP_MODE|
	WC_FONT_MESSAGE|WC_FONT_STATUS|WC_FONT_MENU|WC_FONT_TEXT|WC_FONT_MAP|
	WC_FONTSIZ_MESSAGE|WC_FONTSIZ_STATUS|WC_FONTSIZ_MENU|WC_FONTSIZ_TEXT|
	WC_TILE_WIDTH|WC_TILE_HEIGHT|WC_TILE_FILE|WC_VARY_MSGCOUNT|
	WC_WINDOWCOLORS|WC_PLAYER_SELECTION|WC_SPLASH_SCREEN|WC_POPUP_DIALOG,
    0L,
    mswin_init_nhwindows,
    mswin_player_selection,
    mswin_askname,
    mswin_get_nh_event,
    mswin_exit_nhwindows,
    mswin_suspend_nhwindows,
    mswin_resume_nhwindows,
    mswin_create_nhwindow,
    mswin_clear_nhwindow,
    mswin_display_nhwindow,
    mswin_destroy_nhwindow,
    mswin_curs,
    mswin_putstr,
    mswin_display_file,
    mswin_start_menu,
    mswin_add_menu,
    mswin_end_menu,
    mswin_select_menu,
    genl_message_menu,		/* no need for X-specific handling */
    mswin_update_inventory,
    mswin_mark_synch,
    mswin_wait_synch,
#ifdef CLIPPING
    mswin_cliparound,
#endif
#ifdef POSITIONBAR
    donull,
#endif
    mswin_print_glyph,
    mswin_raw_print,
    mswin_raw_print_bold,
    mswin_nhgetch,
    mswin_nh_poskey,
    mswin_nhbell,
    mswin_doprev_message,
    mswin_yn_function,
    mswin_getlin,
    mswin_get_ext_cmd,
    mswin_number_pad,
    mswin_delay_output,
#ifdef CHANGE_COLOR	/* only a Mac option currently */
	mswin,
	mswin_change_background,
#endif
    /* other defs that really should go away (they're tty specific) */
    mswin_start_screen,
    mswin_end_screen,
    mswin_outrip,
    mswin_preference_update,
};


/*  
init_nhwindows(int* argcp, char** argv)
                -- Initialize the windows used by NetHack.  This can also
                   create the standard windows listed at the top, but does
                   not display them.
                -- Any commandline arguments relevant to the windowport
                   should be interpreted, and *argcp and *argv should
                   be changed to remove those arguments.
                -- When the message window is created, the variable
                   iflags.window_inited needs to be set to TRUE.  Otherwise
                   all plines() will be done via raw_print().
                ** Why not have init_nhwindows() create all of the "standard"
                ** windows?  Or at least all but WIN_INFO?      -dean
*/
void mswin_init_nhwindows(int* argc, char** argv)
{
	logDebug("mswin_init_nhwindows()\n");

#ifdef _DEBUG
	{
		/* truncate trace file */
		FILE *dfp = fopen("nhtrace.log", "w");
		fclose(dfp);
	}
#endif
    mswin_nh_input_init();

	/* set it to WIN_ERR so we can detect attempts to
	   use this ID before it is inialized */
	WIN_MAP = WIN_ERR;

    /* Read Windows settings from the reqistry */
    /* First set safe defaults */
    GetNHApp()->regMainMinX = CW_USEDEFAULT;
    mswin_read_reg();
    /* Create the main window */
    GetNHApp()->hMainWnd = mswin_init_main_window();
    if (!GetNHApp()->hMainWnd)
    {
        panic("Cannot create main window");
    }

    /* Set menu check mark for interface mode */
    mswin_menu_check_intf_mode();

    /* check default values */
	if( iflags.wc_fontsiz_status<NHFONT_SIZE_MIN || 
		iflags.wc_fontsiz_status>NHFONT_SIZE_MAX )
		iflags.wc_fontsiz_status = NHFONT_DEFAULT_SIZE;

	if( iflags.wc_fontsiz_message<NHFONT_SIZE_MIN || 
		iflags.wc_fontsiz_message>NHFONT_SIZE_MAX )
		iflags.wc_fontsiz_message = NHFONT_DEFAULT_SIZE;

	if( iflags.wc_fontsiz_text<NHFONT_SIZE_MIN || 
		iflags.wc_fontsiz_text>NHFONT_SIZE_MAX )
		iflags.wc_fontsiz_text = NHFONT_DEFAULT_SIZE;

	if( iflags.wc_fontsiz_menu<NHFONT_SIZE_MIN || 
		iflags.wc_fontsiz_menu>NHFONT_SIZE_MAX )
		iflags.wc_fontsiz_menu = NHFONT_DEFAULT_SIZE;

	if( iflags.wc_align_message==0 ) iflags.wc_align_message = ALIGN_TOP;
	if( iflags.wc_align_status==0 ) iflags.wc_align_status = ALIGN_BOTTOM;
	if( iflags.wc_scroll_margin==0 ) iflags.wc_scroll_margin = DEF_CLIPAROUND_MARGIN;
	if( iflags.wc_scroll_amount==0 ) iflags.wc_scroll_amount = DEF_CLIPAROUND_AMOUNT;
	if( iflags.wc_tile_width==0 ) iflags.wc_tile_width = TILE_X;
	if( iflags.wc_tile_height==0 ) iflags.wc_tile_height = TILE_Y;

	if( iflags.wc_vary_msgcount==0 ) iflags.wc_vary_msgcount = 4;

	/* force tabs in menus */
	iflags.menu_tab_sep = 1;

	/* force toptenwin to be true.  toptenwin is the option that decides whether to
	 * write output to a window or stdout.  stdout doesn't make sense on Windows
	 * non-console applications
	 */
	flags.toptenwin = 1;
	set_option_mod_status("toptenwin", SET_IN_FILE);
	set_option_mod_status("perm_invent", SET_IN_FILE);

	/* initialize map tiles bitmap */
	initMapTiles();

	/* set tile-related options to readonly */
	set_wc_option_mod_status(
	   WC_TILE_WIDTH|WC_TILE_HEIGHT|WC_TILE_FILE,
	   DISP_IN_GAME);

	/* set font-related options to change in the game */
	set_wc_option_mod_status(
		WC_HILITE_PET |
		WC_ALIGN_MESSAGE | 
		WC_ALIGN_STATUS |
		WC_SCROLL_AMOUNT |
		WC_SCROLL_MARGIN |
		WC_MAP_MODE |
		WC_FONT_MESSAGE |
		WC_FONT_STATUS |
		WC_FONT_MENU |
		WC_FONT_TEXT |
		WC_FONTSIZ_MESSAGE | 
		WC_FONTSIZ_STATUS | 
		WC_FONTSIZ_MENU | 
		WC_FONTSIZ_TEXT |
		WC_VARY_MSGCOUNT,
		SET_IN_GAME 
	);

	mswin_color_from_string(iflags.wc_foregrnd_menu, &menu_fg_brush, &menu_fg_color);
	mswin_color_from_string(iflags.wc_foregrnd_message, &message_fg_brush, &message_fg_color);
	mswin_color_from_string(iflags.wc_foregrnd_status, &status_fg_brush, &status_fg_color);
	mswin_color_from_string(iflags.wc_foregrnd_text, &text_fg_brush, &text_fg_color);
	mswin_color_from_string(iflags.wc_backgrnd_menu, &menu_bg_brush, &menu_bg_color);
	mswin_color_from_string(iflags.wc_backgrnd_message, &message_bg_brush, &message_bg_color);
	mswin_color_from_string(iflags.wc_backgrnd_status, &status_bg_brush, &status_bg_color);
	mswin_color_from_string(iflags.wc_backgrnd_text, &text_bg_brush, &text_bg_color);

 if (iflags.wc_splash_screen) mswin_display_splash_window(FALSE);
	iflags.window_inited = TRUE;
}


/* Do a window-port specific player type selection. If player_selection()
   offers a Quit option, it is its responsibility to clean up and terminate
   the process. You need to fill in pl_character[0].
*/
void mswin_player_selection(void)
{
	int nRole;

	logDebug("mswin_player_selection()\n");

	if (iflags.wc_player_selection == VIA_DIALOG) {
	    /* pick player type randomly (use pre-selected role/race/gender/alignment) */
	    if( flags.randomall ) {
		if (flags.initrole < 0) {
			flags.initrole = pick_role(flags.initrace, flags.initgend,
							flags.initalign, PICK_RANDOM);
			if (flags.initrole < 0) {
				raw_print("Incompatible role!");
				flags.initrole = randrole();
			}
		}

		if (flags.initrace < 0 || !validrace(flags.initrole, flags.initrace)) {
			flags.initrace = pick_race(flags.initrole, flags.initgend,
								flags.initalign, PICK_RANDOM);
			if (flags.initrace < 0) {
				raw_print("Incompatible race!");
				flags.initrace = randrace(flags.initrole);
			}
		}

		if (flags.initgend < 0 || !validgend(flags.initrole, flags.initrace,
						flags.initgend)) {
			flags.initgend = pick_gend(flags.initrole, flags.initrace,
							flags.initalign, PICK_RANDOM);
			if (flags.initgend < 0) {
				raw_print("Incompatible gender!");
				flags.initgend = randgend(flags.initrole, flags.initrace);
			}
		}

		if (flags.initalign < 0 || !validalign(flags.initrole, flags.initrace,
								flags.initalign)) {
			flags.initalign = pick_align(flags.initrole, flags.initrace,
								flags.initgend, PICK_RANDOM);
			if (flags.initalign < 0) {
				raw_print("Incompatible alignment!");
				flags.initalign = randalign(flags.initrole, flags.initrace);
			}
		}
	    } else {
		/* select a role */
		if( mswin_player_selection_window( &nRole ) == IDCANCEL ) {
			bail(0);
		}
	    }
	} else { /* iflags.wc_player_selection == VIA_PROMPTS */
	    prompt_for_player_selection();
	}
}

void prompt_for_player_selection(void)
{
	int i, k, n;
	char pick4u = 'n', thisch, lastch = 0;
	char pbuf[QBUFSZ], plbuf[QBUFSZ];
	winid win;
	anything any;
	menu_item *selected = 0;
        DWORD box_result;

  	logDebug("prompt_for_player_selection()\n");

	/* prevent an unnecessary prompt */
	rigid_role_checks();

	/* Should we randomly pick for the player? */
	if (!flags.randomall &&
	    (flags.initrole == ROLE_NONE || flags.initrace == ROLE_NONE ||
	     flags.initgend == ROLE_NONE || flags.initalign == ROLE_NONE)) {
	    /* int echoline; */
	    char *prompt = build_plselection_prompt(pbuf, QBUFSZ, flags.initrole,
				flags.initrace, flags.initgend, flags.initalign);

	    /* tty_putstr(BASE_WINDOW, 0, ""); */
	    /* echoline = wins[BASE_WINDOW]->cury; */
            box_result = NHMessageBox(NULL, prompt, 
					MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON1);
            pick4u = (box_result == IDYES) ? 'y' : (box_result == IDNO) ? 'n' : '\033';
	    /* tty_putstr(BASE_WINDOW, 0, prompt); */
	    do {
		/* pick4u = lowc(readchar()); */
		if (index(quitchars, pick4u)) pick4u = 'y';
	    } while(!index(ynqchars, pick4u));
	    if ((int)strlen(prompt) + 1 < CO) {
		/* Echo choice and move back down line */
		/* tty_putsym(BASE_WINDOW, (int)strlen(prompt)+1, echoline, pick4u); */
		/* tty_putstr(BASE_WINDOW, 0, ""); */
	    } else
		/* Otherwise it's hard to tell where to echo, and things are
		 * wrapping a bit messily anyway, so (try to) make sure the next
		 * question shows up well and doesn't get wrapped at the
		 * bottom of the window.
		 */
		/* tty_clear_nhwindow(BASE_WINDOW) */ ;
	    
	    if (pick4u != 'y' && pick4u != 'n') {
give_up:	/* Quit */
		if (selected) free((genericptr_t) selected);
		bail((char *)0);
		/*NOTREACHED*/
		return;
	    }
	}

	(void)  root_plselection_prompt(plbuf, QBUFSZ - 1,
			flags.initrole, flags.initrace, flags.initgend, flags.initalign);

	/* Select a role, if necessary */
	/* we'll try to be compatible with pre-selected race/gender/alignment,
	 * but may not succeed */
	if (flags.initrole < 0) {
	    char rolenamebuf[QBUFSZ];
	    /* Process the choice */
	    if (pick4u == 'y' || flags.initrole == ROLE_RANDOM || flags.randomall) {
		/* Pick a random role */
		flags.initrole = pick_role(flags.initrace, flags.initgend,
						flags.initalign, PICK_RANDOM);
		if (flags.initrole < 0) {
		    /* tty_putstr(BASE_WINDOW, 0, "Incompatible role!"); */
		    flags.initrole = randrole();
		}
 	    } else {
	    	/* tty_clear_nhwindow(BASE_WINDOW); */
		/* tty_putstr(BASE_WINDOW, 0, "Choosing Character's Role"); */
		/* Prompt for a role */
		win = create_nhwindow(NHW_MENU);
		start_menu(win);
		any.a_void = 0;         /* zero out all bits */
		for (i = 0; roles[i].name.m; i++) {
		    if (ok_role(i, flags.initrace, flags.initgend,
							flags.initalign)) {
			any.a_int = i+1;	/* must be non-zero */
			thisch = lowc(roles[i].name.m[0]);
			if (thisch == lastch) thisch = highc(thisch);
			if (flags.initgend != ROLE_NONE && flags.initgend != ROLE_RANDOM) {
				if (flags.initgend == 1  && roles[i].name.f)
					Strcpy(rolenamebuf, roles[i].name.f);
				else
					Strcpy(rolenamebuf, roles[i].name.m);
			} else {
				if (roles[i].name.f) {
					Strcpy(rolenamebuf, roles[i].name.m);
					Strcat(rolenamebuf, "/");
					Strcat(rolenamebuf, roles[i].name.f);
				} else 
					Strcpy(rolenamebuf, roles[i].name.m);
			}	
			add_menu(win, NO_GLYPH, &any, thisch,
			    0, ATR_NONE, an(rolenamebuf), MENU_UNSELECTED);
			lastch = thisch;
		    }
		}
		any.a_int = pick_role(flags.initrace, flags.initgend,
				    flags.initalign, PICK_RANDOM)+1;
		if (any.a_int == 0)	/* must be non-zero */
		    any.a_int = randrole()+1;
		add_menu(win, NO_GLYPH, &any , '*', 0, ATR_NONE,
				"Random", MENU_UNSELECTED);
		any.a_int = i+1;	/* must be non-zero */
		add_menu(win, NO_GLYPH, &any , 'q', 0, ATR_NONE,
				"Quit", MENU_UNSELECTED);
		Sprintf(pbuf, "Pick a role for your %s", plbuf);
		end_menu(win, pbuf);
		n = select_menu(win, PICK_ONE, &selected);
		destroy_nhwindow(win);

		/* Process the choice */
		if (n != 1 || selected[0].item.a_int == any.a_int)
		    goto give_up;		/* Selected quit */

		flags.initrole = selected[0].item.a_int - 1;
		free((genericptr_t) selected),	selected = 0;
	    }
	    (void)  root_plselection_prompt(plbuf, QBUFSZ - 1,
			flags.initrole, flags.initrace, flags.initgend, flags.initalign);
	}
	
	/* Select a race, if necessary */
	/* force compatibility with role, try for compatibility with
	 * pre-selected gender/alignment */
	if (flags.initrace < 0 || !validrace(flags.initrole, flags.initrace)) {
	    /* pre-selected race not valid */
	    if (pick4u == 'y' || flags.initrace == ROLE_RANDOM || flags.randomall) {
		flags.initrace = pick_race(flags.initrole, flags.initgend,
							flags.initalign, PICK_RANDOM);
		if (flags.initrace < 0) {
		    /* tty_putstr(BASE_WINDOW, 0, "Incompatible race!"); */
		    flags.initrace = randrace(flags.initrole);
		}
	    } else {	/* pick4u == 'n' */
		/* Count the number of valid races */
		n = 0;	/* number valid */
		k = 0;	/* valid race */
		for (i = 0; races[i].noun; i++) {
		    if (ok_race(flags.initrole, i, flags.initgend,
							flags.initalign)) {
			n++;
			k = i;
		    }
		}
		if (n == 0) {
		    for (i = 0; races[i].noun; i++) {
			if (validrace(flags.initrole, i)) {
			    n++;
			    k = i;
			}
		    }
		}

		/* Permit the user to pick, if there is more than one */
		if (n > 1) {
		    /* tty_clear_nhwindow(BASE_WINDOW); */
		    /* tty_putstr(BASE_WINDOW, 0, "Choosing Race"); */
		    win = create_nhwindow(NHW_MENU);
		    start_menu(win);
		    any.a_void = 0;         /* zero out all bits */
		    for (i = 0; races[i].noun; i++)
			if (ok_race(flags.initrole, i, flags.initgend,
							flags.initalign)) {
			    any.a_int = i+1;	/* must be non-zero */
			    add_menu(win, NO_GLYPH, &any, races[i].noun[0],
				0, ATR_NONE, races[i].noun, MENU_UNSELECTED);
			}
		    any.a_int = pick_race(flags.initrole, flags.initgend,
					flags.initalign, PICK_RANDOM)+1;
		    if (any.a_int == 0)	/* must be non-zero */
			any.a_int = randrace(flags.initrole)+1;
		    add_menu(win, NO_GLYPH, &any , '*', 0, ATR_NONE,
				    "Random", MENU_UNSELECTED);
		    any.a_int = i+1;	/* must be non-zero */
		    add_menu(win, NO_GLYPH, &any , 'q', 0, ATR_NONE,
				    "Quit", MENU_UNSELECTED);
		    Sprintf(pbuf, "Pick the race of your %s", plbuf);
		    end_menu(win, pbuf);
		    n = select_menu(win, PICK_ONE, &selected);
		    destroy_nhwindow(win);
		    if (n != 1 || selected[0].item.a_int == any.a_int)
			goto give_up;		/* Selected quit */

		    k = selected[0].item.a_int - 1;
		    free((genericptr_t) selected),	selected = 0;
		}
		flags.initrace = k;
	    }
	    (void)  root_plselection_prompt(plbuf, QBUFSZ - 1,
			flags.initrole, flags.initrace, flags.initgend, flags.initalign);
	}

	/* Select a gender, if necessary */
	/* force compatibility with role/race, try for compatibility with
	 * pre-selected alignment */
	if (flags.initgend < 0 || !validgend(flags.initrole, flags.initrace,
						flags.initgend)) {
	    /* pre-selected gender not valid */
	    if (pick4u == 'y' || flags.initgend == ROLE_RANDOM || flags.randomall) {
		flags.initgend = pick_gend(flags.initrole, flags.initrace,
						flags.initalign, PICK_RANDOM);
		if (flags.initgend < 0) {
		    /* tty_putstr(BASE_WINDOW, 0, "Incompatible gender!"); */
		    flags.initgend = randgend(flags.initrole, flags.initrace);
		}
	    } else {	/* pick4u == 'n' */
		/* Count the number of valid genders */
		n = 0;	/* number valid */
		k = 0;	/* valid gender */
		for (i = 0; i < ROLE_GENDERS; i++) {
		    if (ok_gend(flags.initrole, flags.initrace, i,
							flags.initalign)) {
			n++;
			k = i;
		    }
		}
		if (n == 0) {
		    for (i = 0; i < ROLE_GENDERS; i++) {
			if (validgend(flags.initrole, flags.initrace, i)) {
			    n++;
			    k = i;
			}
		    }
		}

		/* Permit the user to pick, if there is more than one */
		if (n > 1) {
		    /* tty_clear_nhwindow(BASE_WINDOW); */
		    /* tty_putstr(BASE_WINDOW, 0, "Choosing Gender"); */
		    win = create_nhwindow(NHW_MENU);
		    start_menu(win);
		    any.a_void = 0;         /* zero out all bits */
		    for (i = 0; i < ROLE_GENDERS; i++)
			if (ok_gend(flags.initrole, flags.initrace, i,
							    flags.initalign)) {
			    any.a_int = i+1;
			    add_menu(win, NO_GLYPH, &any, genders[i].adj[0],
				0, ATR_NONE, genders[i].adj, MENU_UNSELECTED);
			}
		    any.a_int = pick_gend(flags.initrole, flags.initrace,
					    flags.initalign, PICK_RANDOM)+1;
		    if (any.a_int == 0)	/* must be non-zero */
			any.a_int = randgend(flags.initrole, flags.initrace)+1;
		    add_menu(win, NO_GLYPH, &any , '*', 0, ATR_NONE,
				    "Random", MENU_UNSELECTED);
		    any.a_int = i+1;	/* must be non-zero */
		    add_menu(win, NO_GLYPH, &any , 'q', 0, ATR_NONE,
				    "Quit", MENU_UNSELECTED);
		    Sprintf(pbuf, "Pick the gender of your %s", plbuf);
		    end_menu(win, pbuf);
		    n = select_menu(win, PICK_ONE, &selected);
		    destroy_nhwindow(win);
		    if (n != 1 || selected[0].item.a_int == any.a_int)
			goto give_up;		/* Selected quit */

		    k = selected[0].item.a_int - 1;
		    free((genericptr_t) selected),	selected = 0;
		}
		flags.initgend = k;
	    }
	    (void)  root_plselection_prompt(plbuf, QBUFSZ - 1,
			flags.initrole, flags.initrace, flags.initgend, flags.initalign);
	}

	/* Select an alignment, if necessary */
	/* force compatibility with role/race/gender */
	if (flags.initalign < 0 || !validalign(flags.initrole, flags.initrace,
							flags.initalign)) {
	    /* pre-selected alignment not valid */
	    if (pick4u == 'y' || flags.initalign == ROLE_RANDOM || flags.randomall) {
		flags.initalign = pick_align(flags.initrole, flags.initrace,
							flags.initgend, PICK_RANDOM);
		if (flags.initalign < 0) {
		    /* tty_putstr(BASE_WINDOW, 0, "Incompatible alignment!"); */
		    flags.initalign = randalign(flags.initrole, flags.initrace);
		}
	    } else {	/* pick4u == 'n' */
		/* Count the number of valid alignments */
		n = 0;	/* number valid */
		k = 0;	/* valid alignment */
		for (i = 0; i < ROLE_ALIGNS; i++) {
		    if (ok_align(flags.initrole, flags.initrace, flags.initgend,
							i)) {
			n++;
			k = i;
		    }
		}
		if (n == 0) {
		    for (i = 0; i < ROLE_ALIGNS; i++) {
			if (validalign(flags.initrole, flags.initrace, i)) {
			    n++;
			    k = i;
			}
		    }
		}

		/* Permit the user to pick, if there is more than one */
		if (n > 1) {
		    /* tty_clear_nhwindow(BASE_WINDOW); */
		    /* tty_putstr(BASE_WINDOW, 0, "Choosing Alignment"); */
		    win = create_nhwindow(NHW_MENU);
		    start_menu(win);
		    any.a_void = 0;         /* zero out all bits */
		    for (i = 0; i < ROLE_ALIGNS; i++)
			if (ok_align(flags.initrole, flags.initrace,
							flags.initgend, i)) {
			    any.a_int = i+1;
			    add_menu(win, NO_GLYPH, &any, aligns[i].adj[0],
				 0, ATR_NONE, aligns[i].adj, MENU_UNSELECTED);
			}
		    any.a_int = pick_align(flags.initrole, flags.initrace,
					    flags.initgend, PICK_RANDOM)+1;
		    if (any.a_int == 0)	/* must be non-zero */
			any.a_int = randalign(flags.initrole, flags.initrace)+1;
		    add_menu(win, NO_GLYPH, &any , '*', 0, ATR_NONE,
				    "Random", MENU_UNSELECTED);
		    any.a_int = i+1;	/* must be non-zero */
		    add_menu(win, NO_GLYPH, &any , 'q', 0, ATR_NONE,
				    "Quit", MENU_UNSELECTED);
		    Sprintf(pbuf, "Pick the alignment of your %s", plbuf);
		    end_menu(win, pbuf);
		    n = select_menu(win, PICK_ONE, &selected);
		    destroy_nhwindow(win);
		    if (n != 1 || selected[0].item.a_int == any.a_int)
			goto give_up;		/* Selected quit */

		    k = selected[0].item.a_int - 1;
		    free((genericptr_t) selected),	selected = 0;
		}
		flags.initalign = k;
	    }
	}
	/* Success! */
	/* tty_display_nhwindow(BASE_WINDOW, FALSE); */
}

/* Ask the user for a player name. */
void mswin_askname(void)
{
	logDebug("mswin_askname()\n");

	if( mswin_getlin_window("Who are you?", plname, PL_NSIZ)==IDCANCEL ) {
		bail("bye-bye");
		/* not reached */
	}
}


/* Does window event processing (e.g. exposure events).
   A noop for the tty and X window-ports.
*/
void mswin_get_nh_event(void)
{
	MSG msg;

	logDebug("mswin_get_nh_event()\n");
	while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)!=0 ) {
		if (!TranslateAccelerator(msg.hwnd, GetNHApp()->hAccelTable, &msg)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	} 
	return;
}

/* Exits the window system.  This should dismiss all windows,
   except the "window" used for raw_print().  str is printed if possible.
*/
void mswin_exit_nhwindows(const char *str)
{
	logDebug("mswin_exit_nhwindows(%s)\n", str);
    /* Write Window settings to the registry */
    mswin_write_reg();
    while (max_brush) 
	DeleteObject(brush_table[--max_brush]);
}

/* Prepare the window to be suspended. */
void mswin_suspend_nhwindows(const char *str)
{
	logDebug("mswin_suspend_nhwindows(%s)\n", str);
	return;
}


/* Restore the windows after being suspended. */
void mswin_resume_nhwindows()
{
	logDebug("mswin_resume_nhwindows()\n");
	return;
}

/*  Create a window of type "type" which can be 
        NHW_MESSAGE     (top line)
        NHW_STATUS      (bottom lines)
        NHW_MAP         (main dungeon)
        NHW_MENU        (inventory or other "corner" windows)
        NHW_TEXT        (help/text, full screen paged window)
*/
winid 
mswin_create_nhwindow(int type)
{
	winid i = 0;
	MSNHMsgAddWnd data;

	logDebug("mswin_create_nhwindow(%d)\n", type);

	/* Return the next available winid
	 */

	for (i=1; i<MAXWINDOWS; i++)
	  if (GetNHApp()->windowlist[i].win == NULL &&
		  !GetNHApp()->windowlist[i].dead)
		  break;
	if (i == MAXWINDOWS)
	  panic ("ERROR:  No windows available...\n");

    switch (type) {
    case NHW_MAP:
	{
		GetNHApp()->windowlist[i].win = mswin_init_map_window();
		GetNHApp()->windowlist[i].type = type;
		GetNHApp()->windowlist[i].dead = 0;
		break;
	}
    case NHW_MESSAGE:
	{
		GetNHApp()->windowlist[i].win = mswin_init_message_window();
		GetNHApp()->windowlist[i].type = type;
		GetNHApp()->windowlist[i].dead = 0;
		break;
	}
    case NHW_STATUS:
	{
		GetNHApp()->windowlist[i].win = mswin_init_status_window();
		GetNHApp()->windowlist[i].type = type;
		GetNHApp()->windowlist[i].dead = 0;
		break;
	}    
    case NHW_MENU:
	{
		GetNHApp()->windowlist[i].win = NULL; //will create later
		GetNHApp()->windowlist[i].type = type;
		GetNHApp()->windowlist[i].dead = 1;
		break;
	} 
    case NHW_TEXT:
	{
		GetNHApp()->windowlist[i].win = mswin_init_text_window();
		GetNHApp()->windowlist[i].type = type;
		GetNHApp()->windowlist[i].dead = 0;
		break;
	}
	}

	ZeroMemory(&data, sizeof(data) );
	data.wid = i;
	SendMessage( GetNHApp()->hMainWnd, 
		         WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_ADDWND, (LPARAM)&data );
	return i;
}

/* Clear the given window, when asked to. */
void mswin_clear_nhwindow(winid wid)
{
	logDebug("mswin_clear_nhwindow(%d)\n", wid);

    if ((wid >= 0) && 
        (wid < MAXWINDOWS) &&
        (GetNHApp()->windowlist[wid].win != NULL))
    {
#ifdef REINCARNATION
		if( GetNHApp()->windowlist[wid].type == NHW_MAP ) {
			if( Is_rogue_level(&u.uz) ) 
				mswin_map_mode(mswin_hwnd_from_winid(WIN_MAP), ROGUE_LEVEL_MAP_MODE);
			else 
				mswin_map_mode(mswin_hwnd_from_winid(WIN_MAP), iflags.wc_map_mode);
		}
#endif

		SendMessage( 
			 GetNHApp()->windowlist[wid].win, 
			 WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_CLEAR_WINDOW, (LPARAM)NULL );
	}
}

/* -- Display the window on the screen.  If there is data
                   pending for output in that window, it should be sent.
                   If blocking is TRUE, display_nhwindow() will not
                   return until the data has been displayed on the screen,
                   and acknowledged by the user where appropriate.
                -- All calls are blocking in the tty window-port.
                -- Calling display_nhwindow(WIN_MESSAGE,???) will do a
                   --more--, if necessary, in the tty window-port.
*/
void mswin_display_nhwindow(winid wid, BOOLEAN_P block)
{
	logDebug("mswin_display_nhwindow(%d, %d)\n", wid, block);
	if (GetNHApp()->windowlist[wid].win != NULL)
	{
		if (GetNHApp()->windowlist[wid].type == NHW_MENU) {
			MENU_ITEM_P* p;
			mswin_menu_window_select_menu(GetNHApp()->windowlist[wid].win, PICK_NONE, &p);
		} if (GetNHApp()->windowlist[wid].type == NHW_TEXT) {
			mswin_display_text_window(GetNHApp()->windowlist[wid].win);
		} if (GetNHApp()->windowlist[wid].type == NHW_RIP) {
			mswin_display_RIP_window(GetNHApp()->windowlist[wid].win);
		} else {
			if( !block ) {
				UpdateWindow(GetNHApp()->windowlist[wid].win);
			} else {
				if ( GetNHApp()->windowlist[wid].type == NHW_MAP ) {
					(void) mswin_nhgetch();
				}
			}
		}
		SetFocus(GetNHApp()->hMainWnd);
	}
}


HWND mswin_hwnd_from_winid(winid wid)
{
	if( wid>=0 && wid<MAXWINDOWS) {
		return GetNHApp()->windowlist[wid].win;
	} else {
		return NULL;
	}
}

winid mswin_winid_from_handle(HWND hWnd)
{
	winid i = 0;

	for (i=1; i<MAXWINDOWS; i++)
	  if (GetNHApp()->windowlist[i].win == hWnd)
		  return i;
	return -1;
}

winid mswin_winid_from_type(int type)
{
	winid i = 0;

	for (i=1; i<MAXWINDOWS; i++)
	  if (GetNHApp()->windowlist[i].type == type)
		  return i;
	return -1;
}

void mswin_window_mark_dead(winid wid)
{
	if( wid>=0 && wid<MAXWINDOWS) {
		GetNHApp()->windowlist[wid].win = NULL;
		GetNHApp()->windowlist[wid].dead = 1;
	}
}

/* Destroy will dismiss the window if the window has not 
 * already been dismissed.
*/
void mswin_destroy_nhwindow(winid wid)
{
	logDebug("mswin_destroy_nhwindow(%d)\n", wid);

    if ((GetNHApp()->windowlist[wid].type == NHW_MAP) || 
        (GetNHApp()->windowlist[wid].type == NHW_MESSAGE) || 
        (GetNHApp()->windowlist[wid].type == NHW_STATUS)) {
		/* main windows is going to take care of those */
		return;
    }

    if (wid != -1) {
		if( !GetNHApp()->windowlist[wid].dead &&
			GetNHApp()->windowlist[wid].win != NULL ) 
			DestroyWindow(GetNHApp()->windowlist[wid].win);
		GetNHApp()->windowlist[wid].win = NULL;
		GetNHApp()->windowlist[wid].type = 0;
		GetNHApp()->windowlist[wid].dead = 0;
	}
}

/* Next output to window will start at (x,y), also moves
 displayable cursor to (x,y).  For backward compatibility,
 1 <= x < cols, 0 <= y < rows, where cols and rows are
 the size of window.
*/
void mswin_curs(winid wid, int x, int y)
{
	logDebug("mswin_curs(%d, %d, %d)\n", wid, x, y);

    if ((wid >= 0) && 
        (wid < MAXWINDOWS) &&
        (GetNHApp()->windowlist[wid].win != NULL))
    {
		 MSNHMsgCursor data;
		 data.x = x;
		 data.y = y;
		 SendMessage( 
			 GetNHApp()->windowlist[wid].win, 
			 WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_CURSOR, (LPARAM)&data );
    }
}

/*
putstr(window, attr, str)
                -- Print str on the window with the given attribute.  Only
                   printable ASCII characters (040-0126) must be supported.
                   Multiple putstr()s are output on separate lines.
Attributes
                   can be one of
                        ATR_NONE (or 0)
                        ATR_ULINE
                        ATR_BOLD
                        ATR_BLINK
                        ATR_INVERSE
                   If a window-port does not support all of these, it may map
                   unsupported attributes to a supported one (e.g. map them
                   all to ATR_INVERSE).  putstr() may compress spaces out of
                   str, break str, or truncate str, if necessary for the
                   display.  Where putstr() breaks a line, it has to clear
                   to end-of-line.
                -- putstr should be implemented such that if two putstr()s
                   are done consecutively the user will see the first and
                   then the second.  In the tty port, pline() achieves this
                   by calling more() or displaying both on the same line.
*/
void mswin_putstr(winid wid, int attr, const char *text)
{
	logDebug("mswin_putstr(%d, %d, %s)\n", wid, attr, text);
	
	mswin_putstr_ex(wid, attr, text, 0);
}

void mswin_putstr_ex(winid wid, int attr, const char *text, int app)
{
	if( (wid >= 0) && 
        (wid < MAXWINDOWS) )
	{
		if( GetNHApp()->windowlist[wid].win==NULL &&
			GetNHApp()->windowlist[wid].type==NHW_MENU ) {
			GetNHApp()->windowlist[wid].win = mswin_init_menu_window(MENU_TYPE_TEXT);
			GetNHApp()->windowlist[wid].dead = 0;
		}

		if (GetNHApp()->windowlist[wid].win != NULL)
		{
			 MSNHMsgPutstr data;
			 ZeroMemory(&data, sizeof(data));
			 data.attr = attr;
			 data.text = text;
			 data.append = app;
			 SendMessage( 
				 GetNHApp()->windowlist[wid].win, 
				 WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_PUTSTR, (LPARAM)&data );
		}
        /* yield a bit so it gets done immediately */
        mswin_get_nh_event();
	}
	else
	{
		// build text to display later in message box
		GetNHApp()->saved_text = realloc(GetNHApp()->saved_text, strlen(text) +
			strlen(GetNHApp()->saved_text) + 1);
		strcat(GetNHApp()->saved_text, text);
	}
}

/* Display the file named str.  Complain about missing files
                   iff complain is TRUE.
*/
void mswin_display_file(const char *filename,BOOLEAN_P must_exist)
{
	dlb *f;
	TCHAR wbuf[BUFSZ];

	logDebug("mswin_display_file(%s, %d)\n", filename, must_exist);

	f = dlb_fopen(filename, RDTMODE);
	if (!f) {
		if (must_exist) {
			TCHAR message[90];
			_stprintf(message, TEXT("Warning! Could not find file: %s\n"), NH_A2W(filename, wbuf, sizeof(wbuf)));
			NHMessageBox(GetNHApp()->hMainWnd, message, MB_OK | MB_ICONEXCLAMATION );
		} 
	} else {
		winid text;
		char line[LLEN];

		text = mswin_create_nhwindow(NHW_TEXT);

		while (dlb_fgets(line, LLEN, f)) {
			 size_t len;
			 len = strlen(line);
			 if( line[len-1]=='\n' ) line[len-1]='\x0';
				mswin_putstr(text, ATR_NONE, line);
		}
		(void) dlb_fclose(f);

		mswin_display_nhwindow(text, 1);
		mswin_destroy_nhwindow(text);
	}
}

/* Start using window as a menu.  You must call start_menu()
   before add_menu().  After calling start_menu() you may not
   putstr() to the window.  Only windows of type NHW_MENU may
   be used for menus.
*/
void mswin_start_menu(winid wid)
{
	logDebug("mswin_start_menu(%d)\n", wid);
	if( (wid >= 0) && 
        (wid < MAXWINDOWS) ) {
		if( GetNHApp()->windowlist[wid].win==NULL &&
			GetNHApp()->windowlist[wid].type==NHW_MENU ) {
			GetNHApp()->windowlist[wid].win = mswin_init_menu_window(MENU_TYPE_MENU);
			GetNHApp()->windowlist[wid].dead = 0;
		}

		if(GetNHApp()->windowlist[wid].win != NULL)	{
			SendMessage( 
				 GetNHApp()->windowlist[wid].win, 
				 WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_STARTMENU, (LPARAM)NULL
			);
		}
	}
}

/*
add_menu(windid window, int glyph, const anything identifier,
                                char accelerator, char groupacc,
                                int attr, char *str, boolean preselected)
                -- Add a text line str to the given menu window.  If identifier
                   is 0, then the line cannot be selected (e.g. a title).
                   Otherwise, identifier is the value returned if the line is
                   selected.  Accelerator is a keyboard key that can be used
                   to select the line.  If the accelerator of a selectable
                   item is 0, the window system is free to select its own
                   accelerator.  It is up to the window-port to make the
                   accelerator visible to the user (e.g. put "a - " in front
                   of str).  The value attr is the same as in putstr().
                   Glyph is an optional glyph to accompany the line.  If
                   window port cannot or does not want to display it, this
                   is OK.  If there is no glyph applicable, then this
                   value will be NO_GLYPH.
                -- All accelerators should be in the range [A-Za-z].
                -- It is expected that callers do not mix accelerator
                   choices.  Either all selectable items have an accelerator
                   or let the window system pick them.  Don't do both.
                -- Groupacc is a group accelerator.  It may be any character
                   outside of the standard accelerator (see above) or a
                   number.  If 0, the item is unaffected by any group
                   accelerator.  If this accelerator conflicts with
                   the menu command (or their user defined alises), it loses.
                   The menu commands and aliases take care not to interfere
                   with the default object class symbols.
                -- If you want this choice to be preselected when the
                   menu is displayed, set preselected to TRUE.
*/
void mswin_add_menu(winid wid, int glyph, const ANY_P * identifier,
		CHAR_P accelerator, CHAR_P group_accel, int attr, 
		const char *str, BOOLEAN_P presel)
{
	logDebug("mswin_add_menu(%d, %d, %p, %c, %c, %d, %s, %d)\n",
		     wid, glyph, identifier, (char)accelerator, (char)group_accel,
			 attr, str, presel);
	if ((wid >= 0) && 
		(wid < MAXWINDOWS) &&
		(GetNHApp()->windowlist[wid].win != NULL))
	{
		MSNHMsgAddMenu data;
		ZeroMemory(&data, sizeof(data));
		data.glyph = glyph;
		data.identifier = identifier;
		data.accelerator = accelerator;
		data.group_accel = group_accel;
		data.attr = attr;
		data.str = str;
		data.presel = presel;

		SendMessage( 
			 GetNHApp()->windowlist[wid].win, 
			 WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_ADDMENU, (LPARAM)&data
		);
	}
}

/*
end_menu(window, prompt)
                -- Stop adding entries to the menu and flushes the window
                   to the screen (brings to front?).  Prompt is a prompt
                   to give the user.  If prompt is NULL, no prompt will
                   be printed.
                ** This probably shouldn't flush the window any more (if
                ** it ever did).  That should be select_menu's job.  -dean
*/
void mswin_end_menu(winid wid, const char *prompt)
{
	logDebug("mswin_end_menu(%d, %s)\n", wid, prompt);
	if ((wid >= 0) && 
		(wid < MAXWINDOWS) &&
		(GetNHApp()->windowlist[wid].win != NULL))
	{
		MSNHMsgEndMenu data;
		ZeroMemory(&data, sizeof(data));
		data.text = prompt;

		SendMessage( 
			 GetNHApp()->windowlist[wid].win, 
			 WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_ENDMENU, (LPARAM)&data
		);
	}
}

/*
int select_menu(windid window, int how, menu_item **selected)
                -- Return the number of items selected; 0 if none were chosen,
                   -1 when explicitly cancelled.  If items were selected, then
                   selected is filled in with an allocated array of menu_item
                   structures, one for each selected line.  The caller must
                   free this array when done with it.  The "count" field
                   of selected is a user supplied count.  If the user did
                   not supply a count, then the count field is filled with
                   -1 (meaning all).  A count of zero is equivalent to not
                   being selected and should not be in the list.  If no items
                   were selected, then selected is NULL'ed out.  How is the
                   mode of the menu.  Three valid values are PICK_NONE,
                   PICK_ONE, and PICK_N, meaning: nothing is selectable,
                   only one thing is selectable, and any number valid items
                   may selected.  If how is PICK_NONE, this function should
                   never return anything but 0 or -1.
                -- You may call select_menu() on a window multiple times --
                   the menu is saved until start_menu() or destroy_nhwindow()
                   is called on the window.
                -- Note that NHW_MENU windows need not have select_menu()
                   called for them. There is no way of knowing whether
                   select_menu() will be called for the window at
                   create_nhwindow() time.
*/
int mswin_select_menu(winid wid, int how, MENU_ITEM_P **selected)
{
	int nReturned = -1;

	logDebug("mswin_select_menu(%d, %d)\n", wid, how);

	if ((wid >= 0) && 
		(wid < MAXWINDOWS) &&
		(GetNHApp()->windowlist[wid].win != NULL))
	{
		nReturned = mswin_menu_window_select_menu(GetNHApp()->windowlist[wid].win, how, selected);
	}
    return nReturned;
}

/*
    -- Indicate to the window port that the inventory has been changed.
    -- Merely calls display_inventory() for window-ports that leave the 
	window up, otherwise empty.
*/
void mswin_update_inventory()
{
	logDebug("mswin_update_inventory()\n");
}

/*
mark_synch()    -- Don't go beyond this point in I/O on any channel until
                   all channels are caught up to here.  Can be an empty call
                   for the moment
*/
void mswin_mark_synch()
{
	logDebug("mswin_mark_synch()\n");
}

/*
wait_synch()    -- Wait until all pending output is complete (*flush*() for
                   streams goes here).
                -- May also deal with exposure events etc. so that the
                   display is OK when return from wait_synch().
*/
void mswin_wait_synch()
{
	logDebug("mswin_wait_synch()\n");
}

/*
cliparound(x, y)-- Make sure that the user is more-or-less centered on the
                   screen if the playing area is larger than the screen.
                -- This function is only defined if CLIPPING is defined.
*/
void mswin_cliparound(int x, int y)
{
	winid wid = WIN_MAP;

	logDebug("mswin_cliparound(%d, %d)\n", x, y);

    if ((wid >= 0) && 
        (wid < MAXWINDOWS) &&
        (GetNHApp()->windowlist[wid].win != NULL))
    {
		 MSNHMsgClipAround data;
		 data.x = x;
		 data.y = y;
         SendMessage( 
			 GetNHApp()->windowlist[wid].win, 
			 WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_CLIPAROUND, (LPARAM)&data );
    }
}

/*
print_glyph(window, x, y, glyph)
                -- Print the glyph at (x,y) on the given window.  Glyphs are
                   integers at the interface, mapped to whatever the window-
                   port wants (symbol, font, color, attributes, ...there's
                   a 1-1 map between glyphs and distinct things on the map).
*/
void mswin_print_glyph(winid wid,XCHAR_P x,XCHAR_P y,int glyph)
{
    logDebug("mswin_print_glyph(%d, %d, %d, %d)\n", wid, x, y, glyph);

    if ((wid >= 0) && 
        (wid < MAXWINDOWS) &&
        (GetNHApp()->windowlist[wid].win != NULL))
    {
		MSNHMsgPrintGlyph data;

		ZeroMemory(&data, sizeof(data) );
		data.x = x;
		data.y = y;
		data.glyph = glyph;
		SendMessage( GetNHApp()->windowlist[wid].win, 
		         WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_PRINT_GLYPH, (LPARAM)&data );
	}
}

/*
raw_print(str)  -- Print directly to a screen, or otherwise guarantee that
                   the user sees str.  raw_print() appends a newline to str.
                   It need not recognize ASCII control characters.  This is
                   used during startup (before windowing system initialization
                   -- maybe this means only error startup messages are raw),
                   for error messages, and maybe other "msg" uses.  E.g.
                   updating status for micros (i.e, "saving").
*/
void mswin_raw_print(const char *str)
{
	TCHAR wbuf[255];
    logDebug("mswin_raw_print(%s)\n", str);
	if( str && *str )
		NHMessageBox(GetNHApp()->hMainWnd, NH_A2W(str, wbuf, sizeof(wbuf)), 
		    MB_ICONINFORMATION | MB_OK );
}

/*
raw_print_bold(str)
                -- Like raw_print(), but prints in bold/standout (if
possible).
*/
void mswin_raw_print_bold(const char *str)
{
	TCHAR wbuf[255];
    logDebug("mswin_raw_print_bold(%s)\n", str);
	if( str && *str )
		NHMessageBox(GetNHApp()->hMainWnd, NH_A2W(str, wbuf, sizeof(wbuf)), 
		    MB_ICONINFORMATION | MB_OK );
}

/*
int nhgetch()   -- Returns a single character input from the user.
                -- In the tty window-port, nhgetch() assumes that tgetch()
                   will be the routine the OS provides to read a character.
                   Returned character _must_ be non-zero.
*/
int mswin_nhgetch()
{
	PMSNHEvent event;
    int key = 0;

	logDebug("mswin_nhgetch()\n");
	

	while( (event = mswin_input_pop()) == NULL ||
		   event->type != NHEVENT_CHAR ) 
		mswin_main_loop();

	key = event->kbd.ch;
    return (key);
}

/*
int nh_poskey(int *x, int *y, int *mod)
                -- Returns a single character input from the user or a
                   a positioning event (perhaps from a mouse).  If the
                   return value is non-zero, a character was typed, else,
                   a position in the MAP window is returned in x, y and mod.
                   mod may be one of

                        CLICK_1         -- mouse click type 1 
                        CLICK_2         -- mouse click type 2 

                   The different click types can map to whatever the
                   hardware supports.  If no mouse is supported, this
                   routine always returns a non-zero character.
*/
int mswin_nh_poskey(int *x, int *y, int *mod)
{
	PMSNHEvent event;
  	int key;

	logDebug("mswin_nh_poskey()\n");

	while( (event = mswin_input_pop())==NULL ) mswin_main_loop();

	if( event->type==NHEVENT_MOUSE ) {
		*mod = event->ms.mod;
		*x = event->ms.x;
		*y = event->ms.y;
		key = 0;
	} else {
		key = event->kbd.ch;
	}
	return (key);
}

/*
nhbell()        -- Beep at user.  [This will exist at least until sounds are
                   redone, since sounds aren't attributable to windows anyway.]
*/
void mswin_nhbell()
{
	logDebug("mswin_nhbell()\n");
}

/*
doprev_message()
                -- Display previous messages.  Used by the ^P command.
                -- On the tty-port this scrolls WIN_MESSAGE back one line.
*/
int mswin_doprev_message()
{
    logDebug("mswin_doprev_message()\n");
	SendMessage(mswin_hwnd_from_winid(WIN_MESSAGE), WM_VSCROLL, MAKEWPARAM(SB_LINEUP, 0), (LPARAM)NULL); 
    return 0;
}

/*
char yn_function(const char *ques, const char *choices, char default)
                -- Print a prompt made up of ques, choices and default.
                   Read a single character response that is contained in
                   choices or default.  If choices is NULL, all possible
                   inputs are accepted and returned.  This overrides
                   everything else.  The choices are expected to be in
                   lower case.  Entering ESC always maps to 'q', or 'n',
                   in that order, if present in choices, otherwise it maps
                   to default.  Entering any other quit character (SPACE,
                   RETURN, NEWLINE) maps to default.
                -- If the choices string contains ESC, then anything after
                   it is an acceptable response, but the ESC and whatever
                   follows is not included in the prompt.
                -- If the choices string contains a '#' then accept a count.
                   Place this value in the global "yn_number" and return '#'.
                -- This uses the top line in the tty window-port, other
                   ports might use a popup.
*/
char mswin_yn_function(const char *question, const char *choices,
		CHAR_P def)
{
    char ch;
    char yn_esc_map='\033';
    char message[BUFSZ];
	char res_ch[2];
    int createcaret;
	boolean digit_ok, allow_num;

	logDebug("mswin_yn_function(%s, %s, %d)\n", question, choices, def);

    if (WIN_MESSAGE == WIN_ERR && choices == ynchars) {
        char *text = realloc(strdup(GetNHApp()->saved_text), strlen(question)
			+ strlen(GetNHApp()->saved_text) + 1);
        DWORD box_result;
        strcat(text, question);
        box_result = NHMessageBox(NULL,
             NH_W2A(text, message, sizeof(message)),
             MB_YESNOCANCEL | MB_ICONQUESTION | 
             ((def == 'y') ? MB_DEFBUTTON1 :
              (def == 'n') ? MB_DEFBUTTON2 : MB_DEFBUTTON3));
        free(text);
		GetNHApp()->saved_text = strdup("");
        return box_result == IDYES ? 'y' : box_result == IDNO ? 'n' : '\033';
    }

    if (choices) {
		char *cb, choicebuf[QBUFSZ];

		allow_num = (index(choices, '#') != 0);

		Strcpy(choicebuf, choices);
		if ((cb = index(choicebuf, '\033')) != 0) {
			/* anything beyond <esc> is hidden */
			*cb = '\0';
		}
		sprintf(message, "%s [%s] ", question, choicebuf);
		if (def) sprintf(eos(message), "(%c) ", def);
		/* escape maps to 'q' or 'n' or default, in that order */
		yn_esc_map = (index(choices, 'q') ? 'q' :
			(index(choices, 'n') ? 'n' : def));
    } else {
		Strcpy(message, question);
		Strcat(message, " ");
    }

    createcaret = 1;
    SendMessage(mswin_hwnd_from_winid(WIN_MESSAGE), 
        WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_CARET, (LPARAM)&createcaret );

    mswin_clear_nhwindow(WIN_MESSAGE);
    mswin_putstr(WIN_MESSAGE, ATR_BOLD, message);

    /* Only here if main window is not present */
	ch = 0;
    do {
		ShowCaret(mswin_hwnd_from_winid(WIN_MESSAGE));
		ch=mswin_nhgetch();
		HideCaret(mswin_hwnd_from_winid(WIN_MESSAGE));
		if (choices) ch = lowc(ch);
		else break; /* If choices is NULL, all possible inputs are accepted and returned. */

		digit_ok = allow_num && digit(ch);
		if (ch=='\033') {
			if (index(choices, 'q'))
				ch = 'q';
			else if (index(choices, 'n'))
				ch = 'n';
			else
				ch = def;
			break;
	    } else if (index(quitchars, ch)) {
			ch = def;
			break;
		} else if (!index(choices, ch) && !digit_ok) {
			mswin_nhbell();
			ch = (char)0;
			/* and try again... */
		} else if (ch == '#' || digit_ok) {
			char z, digit_string[2];
			int n_len = 0;
			long value = 0;
			mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, ("#"), 1); n_len++;
			digit_string[1] = '\0';
			if (ch != '#') {
				digit_string[0] = ch;
				mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, digit_string, 1); n_len++;
				value = ch - '0';
				ch = '#';
			}
			do {	/* loop until we get a non-digit */
				z = lowc(readchar());
				if (digit(z)) {
					value = (10 * value) + (z - '0');
					if (value < 0) break;	/* overflow: try again */
					digit_string[0] = z;
					mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, digit_string, 1);
					n_len++;
				} else if (z == 'y' || index(quitchars, z)) {
					if (z == '\033')  value = -1;	/* abort */
					z = '\n';	/* break */
				} else if (z == '\b') {
					if (n_len <= 1) { value = -1;  break; }
					else { value /= 10;  mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, digit_string, -1);  n_len--; }
				} else {
					value = -1;	/* abort */
					mswin_nhbell();
					break;
				}
			} while (z != '\n');
			if (value > 0) yn_number = value;
			else if (value == 0) ch = 'n';		/* 0 => "no" */
			else {	/* remove number from top line, then try again */
				mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, digit_string, -n_len); n_len = 0;
				ch = (char)0;
			}
		}
	} while( !ch );

    createcaret = 0;
    SendMessage(mswin_hwnd_from_winid(WIN_MESSAGE), 
        WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_CARET, (LPARAM)&createcaret );

	/* display selection in the message window */
	if( isprint(ch) && ch!='#' ) {
		res_ch[0] = ch;
		res_ch[1] = '\x0';
		mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, res_ch, 1);
	}

    return ch;
}

/*
getlin(const char *ques, char *input)
	    -- Prints ques as a prompt and reads a single line of text,
	       up to a newline.  The string entered is returned without the
	       newline.  ESC is used to cancel, in which case the string
	       "\033\000" is returned.
	    -- getlin() must call flush_screen(1) before doing anything.
	    -- This uses the top line in the tty window-port, other
	       ports might use a popup.
*/
void mswin_getlin(const char *question, char *input)
{

	logDebug("mswin_getlin(%s, %p)\n", question, input);

    if (!iflags.wc_popup_dialog)
    {
        char c;
        int len;
        int done;
        int createcaret;

        createcaret = 1;
        SendMessage(mswin_hwnd_from_winid(WIN_MESSAGE), 
            WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_CARET, (LPARAM)&createcaret );

 mswin_clear_nhwindow(WIN_MESSAGE);
        mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, question, 0);
        mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, " ", 1);
        input[0] = '\0';
        len = 0;
        ShowCaret(mswin_hwnd_from_winid(WIN_MESSAGE));
        done = FALSE;
        while (!done)
        {
            c = mswin_nhgetch();
            switch (c)
            {
                case VK_ESCAPE:
                    strcpy(input, "\033");
                    done = TRUE;
                    break;
                case '\n':
                case '\r':
                case -115:
                    done = TRUE;
                    break;
                default:
                    if (input[0])
                        mswin_putstr_ex(WIN_MESSAGE, ATR_NONE, input, -len);
                    if (c == VK_BACK) {
                        if (len > 0) len--;
                        input[len] = '\0';
                    } else {

                        input[len++] = c;
                        input[len] = '\0';
                    }
                    mswin_putstr_ex(WIN_MESSAGE, ATR_NONE, input, 1);
                    break;
            }
        }
        HideCaret(mswin_hwnd_from_winid(WIN_MESSAGE));
        createcaret = 0;
        SendMessage(mswin_hwnd_from_winid(WIN_MESSAGE), 
            WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_CARET, (LPARAM)&createcaret );
    }
    else
    {
	    if( mswin_getlin_window(question, input, BUFSZ)==IDCANCEL ) {
		    strcpy(input, "\033");
	    }
    }
}

/*
int get_ext_cmd(void)
	    -- Get an extended command in a window-port specific way.
	       An index into extcmdlist[] is returned on a successful
	       selection, -1 otherwise.
*/
int mswin_get_ext_cmd()
{
	int ret;
	logDebug("mswin_get_ext_cmd()\n");

    if (!iflags.wc_popup_dialog)
    {
        char c;
        char cmd[BUFSZ];
        int i, len;
        int createcaret;

        createcaret = 1;
        SendMessage(mswin_hwnd_from_winid(WIN_MESSAGE), 
            WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_CARET, (LPARAM)&createcaret );

        cmd[0] = '\0';
        i = -2;
 mswin_clear_nhwindow(WIN_MESSAGE);
        mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, "#", 0);
        len = 0;
        ShowCaret(mswin_hwnd_from_winid(WIN_MESSAGE));
        while (i == -2)
        {
            int oindex, com_index;
            c = mswin_nhgetch();
            switch (c)
            {
                case VK_ESCAPE:
                    i = -1;
                    break;
                case '\n':
                case '\r':
                case -115:
                    for (i = 0; extcmdlist[i].ef_txt != (char *)0; i++)
                        if (!strcmpi(cmd, extcmdlist[i].ef_txt)) break;

                    if (extcmdlist[i].ef_txt == (char *)0) {
                        pline("%s: unknown extended command.", cmd);
                        i = -1;
                    }
                    break;
                default:
                    if (cmd[0])
                        mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, cmd, -(int)strlen(cmd));
                    if (c == VK_BACK)
                    {
                        if (len > 0) len--;
                        cmd[len] = '\0';
                    }
                    else
                    {

                        cmd[len++] = c;
                        cmd[len] = '\0';
                        /* Find a command with this prefix in extcmdlist */
	                    com_index = -1;
	                    for (oindex = 0; extcmdlist[oindex].ef_txt != (char *)0; oindex++) {
		                    if (!strncmpi(cmd, extcmdlist[oindex].ef_txt, len)) {
			                    if (com_index == -1)	/* no matches yet */
			                        com_index = oindex;
                                else
                                    com_index = -2;     /* two matches, don't complete */
		                    }
	                    }
	                    if (com_index >= 0) {
		                    Strcpy(cmd, extcmdlist[com_index].ef_txt);
	                    }
                    }
                    mswin_putstr_ex(WIN_MESSAGE, ATR_BOLD, cmd, 1);
                    break;
            }
        }
        HideCaret(mswin_hwnd_from_winid(WIN_MESSAGE));
        createcaret = 0;
        SendMessage(mswin_hwnd_from_winid(WIN_MESSAGE), 
            WM_MSNH_COMMAND, (WPARAM)MSNH_MSG_CARET, (LPARAM)&createcaret );
	    return i;
    }
    else
    {
    	if(mswin_ext_cmd_window (&ret) == IDCANCEL)
	    	return -1;
	    else 
		    return ret;
    }
}


/*
number_pad(state)
	    -- Initialize the number pad to the given state.
*/
void mswin_number_pad(int state)
{
    /* Do Nothing */
	logDebug("mswin_number_pad(%d)\n", state);
}

/*
delay_output()  -- Causes a visible delay of 50ms in the output.
	       Conceptually, this is similar to wait_synch() followed
	       by a nap(50ms), but allows asynchronous operation.
*/
void mswin_delay_output()
{
	logDebug("mswin_delay_output()\n");
	Sleep(50);
}

void mswin_change_color() 
{ 
	logDebug("mswin_change_color()\n"); 
}

char *mswin_get_color_string() 
{ 
	logDebug("mswin_get_color_string()\n");
	return( "" ); 
}

/*
start_screen()  -- Only used on Unix tty ports, but must be declared for
	       completeness.  Sets up the tty to work in full-screen
	       graphics mode.  Look at win/tty/termcap.c for an
	       example.  If your window-port does not need this function
	       just declare an empty function.
*/
void mswin_start_screen()
{
    /* Do Nothing */
	logDebug("mswin_start_screen()\n");
}

/*
end_screen()    -- Only used on Unix tty ports, but must be declared for
	       completeness.  The complement of start_screen().
*/
void mswin_end_screen()
{
    /* Do Nothing */
	logDebug("mswin_end_screen()\n");
}

/*
outrip(winid, int)
	    -- The tombstone code.  If you want the traditional code use
	       genl_outrip for the value and check the #if in rip.c.
*/
#define STONE_LINE_LEN	16
void mswin_outrip(winid wid, int how)
{
	char buf[BUFSZ];

   	logDebug("mswin_outrip(%d)\n", wid, how);
    if ((wid >= 0) && (wid < MAXWINDOWS) ) {
		DestroyWindow(GetNHApp()->windowlist[wid].win);
		GetNHApp()->windowlist[wid].win = mswin_init_RIP_window();
		GetNHApp()->windowlist[wid].type = NHW_RIP;
		GetNHApp()->windowlist[wid].dead = 0;
	}

	/* Put name on stone */
	Sprintf(buf, "%s", plname);
	buf[STONE_LINE_LEN] = 0;
	putstr(wid, 0, buf);

	/* Put $ on stone */
#ifndef GOLDOBJ
	Sprintf(buf, "%ld Au", u.ugold);
#else
	Sprintf(buf, "%ld Au", done_money);
#endif
	buf[STONE_LINE_LEN] = 0; /* It could be a *lot* of gold :-) */
	putstr(wid, 0, buf);

	/* Put together death description */
	switch (killer_format) {
		default: impossible("bad killer format?");
		case KILLED_BY_AN:
			Strcpy(buf, killed_by_prefix[how]);
			Strcat(buf, an(killer));
			break;
		case KILLED_BY:
			Strcpy(buf, killed_by_prefix[how]);
			Strcat(buf, killer);
			break;
		case NO_KILLER_PREFIX:
			Strcpy(buf, killer);
			break;
	}

	/* Put death type on stone */
	putstr(wid, 0, buf);

	/* Put year on stone */
	Sprintf(buf, "%4d", getyear());
	putstr(wid, 0, buf);
	mswin_finish_rip_text(wid);
}

/* handle options updates here */
void mswin_preference_update(const char *pref)
{
	HDC hdc;

	if( stricmp( pref, "font_menu")==0 ||
		stricmp( pref, "font_size_menu")==0 ) {
		if( iflags.wc_fontsiz_menu<NHFONT_SIZE_MIN || 
			iflags.wc_fontsiz_menu>NHFONT_SIZE_MAX )
			iflags.wc_fontsiz_menu = NHFONT_DEFAULT_SIZE;

		hdc = GetDC(GetNHApp()->hMainWnd);
		mswin_get_font(NHW_MENU, ATR_NONE, hdc, TRUE);
		mswin_get_font(NHW_MENU, ATR_BOLD, hdc, TRUE);
		mswin_get_font(NHW_MENU, ATR_DIM, hdc, TRUE);
		mswin_get_font(NHW_MENU, ATR_ULINE, hdc, TRUE);
		mswin_get_font(NHW_MENU, ATR_BLINK, hdc, TRUE);
		mswin_get_font(NHW_MENU, ATR_INVERSE, hdc, TRUE);
		ReleaseDC(GetNHApp()->hMainWnd, hdc);

		mswin_layout_main_window(NULL);
		return;
	}

	if( stricmp( pref, "font_status")==0 ||
		stricmp( pref, "font_size_status")==0 ) {

		if( iflags.wc_fontsiz_status<NHFONT_SIZE_MIN || 
			iflags.wc_fontsiz_status>NHFONT_SIZE_MAX )
			iflags.wc_fontsiz_status = NHFONT_DEFAULT_SIZE;

		hdc = GetDC(GetNHApp()->hMainWnd);
		mswin_get_font(NHW_STATUS, ATR_NONE, hdc, TRUE);
		mswin_get_font(NHW_STATUS, ATR_BOLD, hdc, TRUE);
		mswin_get_font(NHW_STATUS, ATR_DIM, hdc, TRUE);
		mswin_get_font(NHW_STATUS, ATR_ULINE, hdc, TRUE);
		mswin_get_font(NHW_STATUS, ATR_BLINK, hdc, TRUE);
		mswin_get_font(NHW_STATUS, ATR_INVERSE, hdc, TRUE);
		ReleaseDC(GetNHApp()->hMainWnd, hdc);

		InvalidateRect(mswin_hwnd_from_winid(WIN_STATUS), NULL, TRUE);
		mswin_layout_main_window(NULL);
		return;
	}

	if( stricmp( pref, "font_message")==0 ||
		stricmp( pref, "font_size_message")==0 ) {

		if( iflags.wc_fontsiz_message<NHFONT_SIZE_MIN || 
			iflags.wc_fontsiz_message>NHFONT_SIZE_MAX )
			iflags.wc_fontsiz_message = NHFONT_DEFAULT_SIZE;

		hdc = GetDC(GetNHApp()->hMainWnd);
		mswin_get_font(NHW_MESSAGE, ATR_NONE, hdc, TRUE);
		mswin_get_font(NHW_MESSAGE, ATR_BOLD, hdc, TRUE);
		mswin_get_font(NHW_MESSAGE, ATR_DIM, hdc, TRUE);
		mswin_get_font(NHW_MESSAGE, ATR_ULINE, hdc, TRUE);
		mswin_get_font(NHW_MESSAGE, ATR_BLINK, hdc, TRUE);
		mswin_get_font(NHW_MESSAGE, ATR_INVERSE, hdc, TRUE);
		ReleaseDC(GetNHApp()->hMainWnd, hdc);

		InvalidateRect(mswin_hwnd_from_winid(WIN_MESSAGE), NULL, TRUE);
		mswin_layout_main_window(NULL);
		return;
	}

	if( stricmp( pref, "font_text")==0 ||
		stricmp( pref, "font_size_text")==0 ) {

		if( iflags.wc_fontsiz_text<NHFONT_SIZE_MIN || 
			iflags.wc_fontsiz_text>NHFONT_SIZE_MAX )
			iflags.wc_fontsiz_text = NHFONT_DEFAULT_SIZE;

		hdc = GetDC(GetNHApp()->hMainWnd);
		mswin_get_font(NHW_TEXT, ATR_NONE, hdc, TRUE);
		mswin_get_font(NHW_TEXT, ATR_BOLD, hdc, TRUE);
		mswin_get_font(NHW_TEXT, ATR_DIM, hdc, TRUE);
		mswin_get_font(NHW_TEXT, ATR_ULINE, hdc, TRUE);
		mswin_get_font(NHW_TEXT, ATR_BLINK, hdc, TRUE);
		mswin_get_font(NHW_TEXT, ATR_INVERSE, hdc, TRUE);
		ReleaseDC(GetNHApp()->hMainWnd, hdc);

		mswin_layout_main_window(NULL);
		return;
	}

	if( stricmp( pref, "scroll_amount")==0 ) {
		mswin_cliparound(u.ux, u.uy);
		return;
	}

	if( stricmp( pref, "scroll_margin")==0 ) {
		mswin_cliparound(u.ux, u.uy);
		return;
	}

	if( stricmp( pref, "map_mode")==0 ) {
		mswin_select_map_mode( iflags.wc_map_mode );
		return;
	}

	if( stricmp( pref, "hilite_pet")==0 ) {
		InvalidateRect(mswin_hwnd_from_winid(WIN_MAP), NULL, TRUE);
		return;
	}

	if( stricmp( pref, "align_message")==0 ||
		stricmp( pref, "align_status")==0 ) {
		mswin_layout_main_window(NULL);
		return;
	}

	if( stricmp( pref, "vary_msgcount")==0 ) {
		InvalidateRect(mswin_hwnd_from_winid(WIN_MESSAGE), NULL, TRUE);
		mswin_layout_main_window(NULL);
		return;
	}

}


void mswin_main_loop()
{
	MSG msg;

	while( !mswin_have_input() &&
		   GetMessage(&msg, NULL, 0, 0)!=0 ) {
 		if (GetNHApp()->regNetHackMode ||
 			!TranslateAccelerator(msg.hwnd, GetNHApp()->hAccelTable, &msg))
 		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	} 
}

/* clean up and quit */
void bail(const char *mesg)
{
    clearlocks();
    mswin_exit_nhwindows(mesg);
    terminate(EXIT_SUCCESS);
    /*NOTREACHED*/
}

BOOL initMapTiles(void)
{
	HBITMAP hBmp;
	BITMAP  bm;
	TCHAR   wbuf[MAX_PATH];
	int     tl_num;
	SIZE    map_size;
	extern int total_tiles_used;

	/* no file - no tile */
	if( !(iflags.wc_tile_file && *iflags.wc_tile_file) ) 
		return TRUE;

	/* load bitmap */
	hBmp = LoadImage(
				GetNHApp()->hApp, 
				NH_A2W(iflags.wc_tile_file, wbuf, MAX_PATH),
				IMAGE_BITMAP,
				0,
				0,
				LR_LOADFROMFILE | LR_DEFAULTSIZE 
			);
	if( hBmp==NULL ) {
		raw_print("Cannot load tiles from the file. Reverting back to default.");
		return FALSE;
	}

	/* calculate tile dimensions */
	GetObject(hBmp, sizeof(BITMAP), (LPVOID)&bm);
	if( bm.bmWidth%iflags.wc_tile_width ||
		bm.bmHeight%iflags.wc_tile_height ) {
		DeleteObject(hBmp);
		raw_print("Tiles bitmap does not match tile_width and tile_height options. Reverting back to default.");
		return FALSE;
	}

	tl_num = (bm.bmWidth/iflags.wc_tile_width)*
		     (bm.bmHeight/iflags.wc_tile_height);
	if( tl_num<total_tiles_used ) {
		DeleteObject(hBmp);
		raw_print("Number of tiles in the bitmap is less than required by the game. Reverting back to default.");
		return FALSE;
	}

	/* set the tile information */
	if( GetNHApp()->bmpMapTiles!=GetNHApp()->bmpTiles ) {
		DeleteObject(GetNHApp()->bmpMapTiles);
	}

	GetNHApp()->bmpMapTiles = hBmp;
	GetNHApp()->mapTile_X = iflags.wc_tile_width;
	GetNHApp()->mapTile_Y = iflags.wc_tile_height;
	GetNHApp()->mapTilesPerLine = bm.bmWidth / iflags.wc_tile_width;

	map_size.cx = GetNHApp()->mapTile_X * COLNO;
	map_size.cy = GetNHApp()->mapTile_Y * ROWNO;
	mswin_map_stretch(
		mswin_hwnd_from_winid(WIN_MAP),
		&map_size,
		TRUE 
	);
	return TRUE;
}

void mswin_popup_display(HWND hWnd, int* done_indicator)
{
	MSG msg;
	HWND hChild;
	HMENU hMenu;
	int mi_count;
	int i;

	/* activate the menu window */
	GetNHApp()->hPopupWnd = hWnd;

	mswin_layout_main_window(hWnd);

	/* disable game windows */
	for( hChild=GetWindow(GetNHApp()->hMainWnd, GW_CHILD);
		 hChild;
		 hChild = GetWindow(hChild, GW_HWNDNEXT) ) {
		if( hChild!= hWnd) EnableWindow(hChild, FALSE);
	}

	/* disable menu */
	hMenu = GetMenu( GetNHApp()->hMainWnd );
	mi_count = GetMenuItemCount( hMenu );
	for( i=0; i<mi_count; i++ ) {
		EnableMenuItem(hMenu, i, MF_BYPOSITION | MF_GRAYED);
	}
	DrawMenuBar( GetNHApp()->hMainWnd );

	/* bring menu window on top */
	SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);

	/* go into message loop */
	while( IsWindow(hWnd) && 
		   (done_indicator==NULL || !*done_indicator) &&
		   GetMessage(&msg, NULL, 0, 0)!=0 ) {
		if( !IsDialogMessage(hWnd, &msg) ) {
			if (!TranslateAccelerator(msg.hwnd, GetNHApp()->hAccelTable, &msg)) {
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
	}
}

void mswin_popup_destroy(HWND hWnd)
{
	HWND hChild;
	HMENU hMenu;
	int mi_count;
	int i;

	/* enable game windows */
	for( hChild=GetWindow(GetNHApp()->hMainWnd, GW_CHILD);
		 hChild;
		 hChild = GetWindow(hChild, GW_HWNDNEXT) ) {
		if( hChild!= hWnd) {
			EnableWindow(hChild, TRUE);
		}
	}

	/* enable menu */
	hMenu = GetMenu( GetNHApp()->hMainWnd );
	mi_count = GetMenuItemCount( hMenu );
	for( i=0; i<mi_count; i++ ) {
		EnableMenuItem(hMenu, i, MF_BYPOSITION | MF_ENABLED);
	}
	DrawMenuBar( GetNHApp()->hMainWnd );

	SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW);
	GetNHApp()->hPopupWnd = NULL;
	mswin_window_mark_dead( mswin_winid_from_handle(hWnd) );
	DestroyWindow(hWnd);

	mswin_layout_main_window(hWnd);

	SetFocus(GetNHApp()->hMainWnd );
}

#ifdef _DEBUG
#include <stdarg.h>

void
logDebug(const char *fmt, ...)
{
  FILE *dfp = fopen("nhtrace.log", "a");

  if (dfp) {
     va_list args;

     va_start(args, fmt);
     vfprintf(dfp, fmt, args);
     va_end(args);
     fclose(dfp);
  }
}

#endif


/* Reading and writing settings from the registry. */
#define CATEGORYKEY         "Software"
#define COMPANYKEY          "NetHack"
#define PRODUCTKEY          "NetHack 3.4.3"
#define SETTINGSKEY         "Settings"
#define MAINSHOWSTATEKEY    "MainShowState"
#define MAINMINXKEY         "MainMinX"
#define MAINMINYKEY         "MainMinY"
#define MAINMAXXKEY         "MainMaxX"
#define MAINMAXYKEY         "MainMaxY"
#define MAINLEFTKEY         "MainLeft"
#define MAINRIGHTKEY        "MainRight"
#define MAINTOPKEY          "MainTop"
#define MAINBOTTOMKEY       "MainBottom"

/* #define all the subkeys here */
#define INTFKEY "Interface"

void
mswin_read_reg()
{
    HKEY key;
    DWORD size;
    char keystring[MAX_PATH];

    sprintf(keystring, "%s\\%s\\%s\\%s", 
        CATEGORYKEY, COMPANYKEY, PRODUCTKEY, SETTINGSKEY);

    /* Set the defaults here. The very first time the app is started, nothing is 
       read from the registry, so these defaults apply. */
    GetNHApp()->saveRegistrySettings = 1;   /* Normally, we always save */
    GetNHApp()->regNetHackMode = 0;

    if (RegOpenKeyEx(HKEY_CURRENT_USER, keystring, 0, KEY_READ, &key) 
            != ERROR_SUCCESS)
        return;

    size = sizeof(DWORD);
    /* Read the keys here. */
    RegQueryValueEx(key, INTFKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regNetHackMode)), &size);
    /* Main window placement */
    RegQueryValueEx(key, MAINSHOWSTATEKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regMainShowState)), &size);
    RegQueryValueEx(key, MAINMINXKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regMainMinX)), &size);
    RegQueryValueEx(key, MAINMINYKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regMainMinY)), &size);
    RegQueryValueEx(key, MAINMAXXKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regMainMaxX)), &size);
    RegQueryValueEx(key, MAINMAXYKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regMainMaxY)), &size);
    RegQueryValueEx(key, MAINLEFTKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regMainLeft)), &size);
    RegQueryValueEx(key, MAINRIGHTKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regMainRight)), &size);
    RegQueryValueEx(key, MAINTOPKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regMainTop)), &size);
    RegQueryValueEx(key, MAINBOTTOMKEY, 0, NULL, (unsigned char *)(&(GetNHApp()->regMainBottom)), &size);
    
    RegCloseKey(key);
}

void
mswin_write_reg()
{
    HKEY key;
    DWORD disposition;

    if (GetNHApp()->saveRegistrySettings)
    {
        char keystring[MAX_PATH];

        sprintf(keystring, "%s\\%s\\%s\\%s", 
            CATEGORYKEY, COMPANYKEY, PRODUCTKEY, SETTINGSKEY);

        if (RegOpenKeyEx(HKEY_CURRENT_USER, keystring, 0, KEY_WRITE, &key) != ERROR_SUCCESS)
        {
            RegCreateKeyEx(HKEY_CURRENT_USER, keystring, 0, "",
                REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &disposition);
        }

        /* Write the keys here */
        RegSetValueEx(key, INTFKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regNetHackMode)), sizeof(DWORD));
        /* Main window placement */
        RegSetValueEx(key, MAINSHOWSTATEKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regMainShowState)), sizeof(DWORD));
        RegSetValueEx(key, MAINMINXKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regMainMinX)), sizeof(DWORD));
        RegSetValueEx(key, MAINMINYKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regMainMinY)), sizeof(DWORD));
        RegSetValueEx(key, MAINMAXXKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regMainMaxX)), sizeof(DWORD));
        RegSetValueEx(key, MAINMAXYKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regMainMaxY)), sizeof(DWORD));
        RegSetValueEx(key, MAINLEFTKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regMainLeft)), sizeof(DWORD));
        RegSetValueEx(key, MAINRIGHTKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regMainRight)), sizeof(DWORD));
        RegSetValueEx(key, MAINTOPKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regMainTop)), sizeof(DWORD));
        RegSetValueEx(key, MAINBOTTOMKEY, 0, REG_DWORD, (unsigned char *)(&(GetNHApp()->regMainBottom)), sizeof(DWORD));

        RegCloseKey(key);
    }
}

void
mswin_destroy_reg()
{
    char keystring[MAX_PATH];
    HKEY key;
    DWORD nrsubkeys;

    /* Delete keys one by one, as NT does not delete trees */
    sprintf(keystring, "%s\\%s\\%s\\%s", 
        CATEGORYKEY, COMPANYKEY, PRODUCTKEY, SETTINGSKEY);
    RegDeleteKey(HKEY_CURRENT_USER, keystring);
    sprintf(keystring, "%s\\%s\\%s", 
        CATEGORYKEY, COMPANYKEY, PRODUCTKEY);
    RegDeleteKey(HKEY_CURRENT_USER, keystring);
    /* The company key will also contain information about newer versions
       of nethack (e.g. a subkey called NetHack 4.0), so only delete that
       if it's empty now. */
    sprintf(keystring, "%s\\%s", CATEGORYKEY, COMPANYKEY);
    /* If we cannot open it, we probably cannot delete it either... Just
       go on and see what happens. */
    RegOpenKeyEx(HKEY_CURRENT_USER, keystring, 0, KEY_READ, &key); 
    nrsubkeys = 0;
    RegQueryInfoKey(key, NULL, NULL, NULL, &nrsubkeys, NULL, NULL, NULL, 
        NULL, NULL, NULL, NULL);
    RegCloseKey(key);
    if (nrsubkeys == 0)
        RegDeleteKey(HKEY_CURRENT_USER, keystring);

    /* Prevent saving on exit */
    GetNHApp()->saveRegistrySettings = 0;
}

typedef struct ctv
{
	const char *colorstring;
	COLORREF colorvalue;
} color_table_value;

/*
 * The color list here is a combination of:
 * NetHack colors.  (See mhmap.c)
 * HTML colors. (See http://www.w3.org/TR/REC-html40/types.html#h-6.5 )
 */

static color_table_value color_table[] = {
/* NetHack colors */
	{ "black",		RGB(0x55, 0x55, 0x55)},
	{ "red", 		RGB(0xFF, 0x00, 0x00)},
	{ "green", 		RGB(0x00, 0x80, 0x00)},
	{ "brown",		RGB(0xA5, 0x2A, 0x2A)},
	{ "blue",		RGB(0x00, 0x00, 0xFF)},
	{ "magenta", 		RGB(0xFF, 0x00, 0xFF)},
	{ "cyan", 		RGB(0x00, 0xFF, 0xFF)},
	{ "orange",		RGB(0xFF, 0xA5, 0x00)},
	{ "brightgreen",	RGB(0x00, 0xFF, 0x00)},
	{ "yellow", 		RGB(0xFF, 0xFF, 0x00)},
	{ "brightblue",		RGB(0x00, 0xC0, 0xFF)},
	{ "brightmagenta",	RGB(0xFF, 0x80, 0xFF)},
	{ "brightcyan", 	RGB(0x80, 0xFF, 0xFF)},
	{ "white", 		RGB(0xFF, 0xFF, 0xFF)},
/* Remaining HTML colors */
	{ "trueblack",		RGB(0x00, 0x00, 0x00)},
	{ "gray", 		RGB(0x80, 0x80, 0x80)},
	{ "grey", 		RGB(0x80, 0x80, 0x80)},
	{ "purple",		RGB(0x80, 0x00, 0x80)},
	{ "silver",		RGB(0xC0, 0xC0, 0xC0)},
	{ "maroon",		RGB(0x80, 0x00, 0x00)},
	{ "fuchsia",		RGB(0xFF, 0x00, 0xFF)}, /* = NetHack magenta */
	{ "lime", 		RGB(0x00, 0xFF, 0x00)}, /* = NetHack bright green */
	{ "olive", 		RGB(0x80, 0x80, 0x00)},
	{ "navy", 		RGB(0x00, 0x00, 0x80)},
	{ "teal", 		RGB(0x00, 0x80, 0x80)},
	{ "aqua", 		RGB(0x00, 0xFF, 0xFF)}, /* = NetHack cyan */
	{ "", 			RGB(0x00, 0x00, 0x00)},
};

typedef struct ctbv
{
	char *colorstring;
	int syscolorvalue;
} color_table_brush_value;

static color_table_brush_value color_table_brush[] = {
	{ "activeborder", 	COLOR_ACTIVEBORDER	},
	{ "activecaption",	COLOR_ACTIVECAPTION	},
	{ "appworkspace",		COLOR_APPWORKSPACE	},
	{ "background",		COLOR_BACKGROUND		},
	{ "btnface",		COLOR_BTNFACE		},
	{ "btnshadow",		COLOR_BTNSHADOW		},
	{ "btntext", 		COLOR_BTNTEXT		},
	{ "captiontext",		COLOR_CAPTIONTEXT		},
	{ "graytext",		COLOR_GRAYTEXT		},
	{ "greytext",		COLOR_GRAYTEXT 		},
	{ "highlight",		COLOR_HIGHLIGHT 		},
	{ "highlighttext",	COLOR_HIGHLIGHTTEXT	},
	{ "inactiveborder", 	COLOR_INACTIVEBORDER 	},
	{ "inactivecaption",	COLOR_INACTIVECAPTION 	},
	{ "menu",			COLOR_MENU 			},
	{ "menutext",		COLOR_MENUTEXT 		},
	{ "scrollbar",		COLOR_SCROLLBAR 		},
	{ "window",			COLOR_WINDOW 		},
	{ "windowframe", 		COLOR_WINDOWFRAME 	},
	{ "windowtext",		COLOR_WINDOWTEXT 		},
	{ "", 			-1				},
};

static void mswin_color_from_string(char *colorstring, HBRUSH* brushptr, COLORREF *colorptr)
{
	color_table_value *ctv_ptr = color_table;
	color_table_brush_value *ctbv_ptr = color_table_brush;
	int red_value, blue_value, green_value;
	static char *hexadecimals = "0123456789abcdef";

	if (colorstring == NULL) return;
	if (*colorstring == '#') {
		if (strlen(++colorstring) != 6) return;

		red_value = index(hexadecimals, tolower(*colorstring++)) - hexadecimals;
		red_value *= 16;
		red_value += index(hexadecimals, tolower(*colorstring++)) - hexadecimals;

		green_value = index(hexadecimals, tolower(*colorstring++)) - hexadecimals;
		green_value *= 16;
		green_value += index(hexadecimals, tolower(*colorstring++)) - hexadecimals;

		blue_value = index(hexadecimals, tolower(*colorstring++)) - hexadecimals;
		blue_value *= 16;
		blue_value += index(hexadecimals, tolower(*colorstring++)) - hexadecimals;

		*colorptr = RGB(red_value, green_value, blue_value);
	} else {
	    while (*ctv_ptr->colorstring && stricmp(ctv_ptr->colorstring, colorstring))
		++ctv_ptr;
	    if (*ctv_ptr->colorstring) {
		*colorptr = ctv_ptr->colorvalue;
	    } else {
	      while (*ctbv_ptr->colorstring && stricmp(ctbv_ptr->colorstring, colorstring))
		    ++ctbv_ptr;
		if (*ctbv_ptr->colorstring) {
		    *brushptr = SYSCLR_TO_BRUSH(ctbv_ptr->syscolorvalue);
		    *colorptr = GetSysColor(ctbv_ptr->syscolorvalue);
		}
	    }
	}
	if (max_brush > TOTAL_BRUSHES) panic("Too many colors!");
	*brushptr = CreateSolidBrush(*colorptr);
	brush_table[max_brush++] = *brushptr;
}

int NHMessageBox(HWND hWnd, LPCTSTR text, UINT type)
{
    TCHAR title[MAX_LOADSTRING];
    
    LoadString(GetNHApp()->hApp, IDS_APP_TITLE_SHORT, title, MAX_LOADSTRING);

    return MessageBox(hWnd, text, title, type);
}