File: NetDlg.cpp

package info (click to toggle)
postal1 2015.git20250526%2Bds-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid
  • size: 14,024 kB
  • sloc: cpp: 130,877; ansic: 38,942; python: 874; makefile: 351; sh: 61
file content (3454 lines) | stat: -rw-r--r-- 110,233 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 RWS Inc, All Rights Reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of version 2 of the GNU General Public License as published by
// the Free Software Foundation
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// NetDlg.CPP
// Project: Nostril (aka Postal)
// 
// History:
//		04/08/97 JMI	Started.
//
//		05/20/97	JMI	Now ms_pguiOK and ms_pguiCancel use SAFE_REF() so the
//							current GUI can, optionally, not have one or both GUI
//							items.
//
//		05/25/97	JMI	Integrated newest TCP/IP CNetServer/Client interface.
//							Still need to detect when the game is starting.
//							GUI could still use a little cleaning up.
//
//		05/26/97	JMI	Removed case for NetMsg::DuplicateName in reason
//							for JoinDeny message (it no longer exists).
//
//		05/26/97	JMI	Added sending and receiving of START_REALM.
//							Removed psNumPlayers and psMyPlayerNum parameters.
//
//		05/27/97	JMI	Added sending and receiving of LOAD_REALM before 
//							START_REALM.
//							Fixed bug in OnLoginMsg() which was telling the client
//							the wrong net ID.
//							Upgraded to utilize new functions RSocket::SetPort() and 
//							CNet::OpenPeerData().
//
//		05/27/97	JMI	OnJoinedMsg() now only adds the players' names to the
//							listbox of players.
//
//		05/28/97	JMI	Integrated new dialog.
//
//		05/28/97	JMI	Changed so the LOAD_REALM message motivates the leaving
//							of the dialog interface (was START_REALM that did it
//							before).
//
//		06/11/97	JMI	Removed unnecessary code in OnLoadRealmMsg().
//							Now uses Play_GetNextLevel to get realm names.
//
//		06/11/97	JMI	Now centers client/server dialogs on screen.
//
//		06/13/97 MJR	Restructed lots of stuff to consolidate client and
//							server code into a single function.
//							Implimented new version of START_GAME message.
//							Added code to get/release resources for new deluxe
//							dialog box.
//
//		06/15/97	JMI	Now deactivates client items in listbox as they are
//							added.
//							Also, now, instead of simply squashing the dialog to
//							exclude server controls in client mode, we simply hide
//							the server controls and center the remaining controls
//							in the dialog without altering its size.
//
//		06/16/97	JMI	Now uses g_fontSmall for dialogs.
//
//					MJR	Added use of watchdog timer for network blocking callbacks.
//
//					JMI	Changed use of g_fontSmall to g_fontBig.
//
//		06/17/97	JMI	Now only allows the server to process a DLG_OK.
//
//		06/30/97 MJR	Switched over to new GuiItem.h-supplied macros.
//
//		07/14/97 BRH	Changed call to Play_GetRealmInfo to include the
//							new challenge mode parameter.
//
//		08/02/97	JMI	Added an icon to watchdog timer for network blocking
//							callbacks and made it generally callable.
//
//		08/04/97 BRH	Added protocol parameter to net calls.
//
//		08/11/97	JMI	Changed a little of the structure of SetUpDlg() to allow
//							for more than just two types of dialogs.
//							Also, changed UpdateDialog() to use an RProcessGui which
//							simplifies that down to nearly nothing.  #if 0'd out old
//							stuff for now.
//							Checking in so Mike can compile so we can check his stuff
//							in so I can check this out again.
//
//					MJR	Modified to use new browsing functions and moved all
//							the find-the-host code into a separate function.
//
//					JMI	Now adds the items from the browse list to the dialog
//							(and drops them too (theoretically) ).
//
//		08/12/97	JMI	Dropped hosts were not setting the repaginate flag in
//							UpdateListBox().  Fixed.
//							DoNetGameDialog() now loops nearly all logic while 
//							browsing and no errors.
//
//		08/13/97 JMI	Cleaned up some more stuff.
//					MJR	Fixed bugs that kept us in a browsing loop.
//
//		08/14/97	JMI	Added global difficulty parameter to Play_GetRealmInfo().
//							I imagine it's not actually used for multiplayer levels
//							until we have options to play cooperative.
//
//		08/19/97	JMI	Added some unfinished usage of the multiplayer options
//							updating.  Needs to be updated to the correct spot,
//							either the game settings or the message.  Probably the
//							game settings which then get copied to the message.
//
//		08/19/97	JMI	Now uses the g_GameSettings for the multiplayer options.
//							Tinkered with chat messages that I thought weren't 
//							working but then realized they were being ignored b/c
//							the UpdateDialog() function was being called by the
//							net blocking callback so hopefully I didn't ruin anything
//							in that process... .
//							Genericized SetupDlg() to use UploadLinks().
//
//		08/19/97	JMI	Added a flag to UpdateDialog() indicating that it should
//							not clear any GUIs.  This is useful for when 
//							UpdateDialog() is called via callback (so we don't loose
//							any of the pressages processed via the callback).
//
//		08/20/97	JMI	Up/DownloadLinkInteger() are now hardwired to assume
//							'signed' type for String links b/c bool had a warning
//							for the trickery I was using to determine if the type
//							was signed.
//
//		08/20/97	JMI	Now chat history is a listbox.
//							Clicking the 'Send Chat' button moves focus back to the
//							edit field for better feedback.
//							Limits chats to 20.
//							Now updates client's view of host's multiplay options.
//							Now the server can select a player (for disconnection)
//							from the players list.
//							Implemented host option to disconnect a player.
//							Newest player is EnsureVisible()d in player list now.
//							Newest chat is EnsureVisible()d in chat list now.
//							Now sets number of connected players on two GUIs so
//							there can be a 3D effect.
//							Sends and responds to SETUP_GAME message.
//							Sets options in START_GAME message from dialog settings
//							now.
//							Updates settings even if dialog aborted for consistency.
//
//		08/21/97	JMI	Temporarily hardwired 'Rejuvenate' to ON and disallowed
//							user modifications of the checkbox.
//
//		08/21/97	JMI	Changed call to Update() to UpdateSystem() and occurrences
//							of rspUpdateDisplay() to UpdateDisplay().
//
//		08/23/97 MJR	Lots of changes in how errors are handled and other such
//							stuff.
//
//		08/23/97	JMI	Now list box items appear with a barely perceptible 
//							shadow that makes them alot easier to read.
//							Player colors now displayed as color descriptions.
//
//		08/25/97	JMI	Now the chat text edit field limits the text to the
//							message's capacity for text.
//							Also, got rid of some '***'s.
//
//		08/25/97	JMI	Now removes areas on chat items in chat box to make
//							for the border lines we hide to get more space.
//
//		08/27/97	JMI	Changed NetProbIcons functions to NetProbGui functions.
//							Also, instead of a DrawNetProbGui() there's a 
//							GetNetProbGui() so you can draw it, move it, change the
//							text, etc.
//
//		09/01/97 MJR	Nearing the end of a huge overhaul of networking.
//
//		09/02/97 MJR	It appears to work well after much testing, tuning, and
//							debugging.
//
//		09/03/97 MJR	Fixed a problem that made browsing for yourself fail
//							once in a while (the timeout timer was too short).
//
//		09/06/97	JMI	Now sets the Client's Game Options text field to use
//							the text shadow.  Also, selects the first item in the
//							level browser box in the Server's dialog.
//							Also, combined the status field and the chat box into
//							one 'Net Console'.
//
//		09/06/97	JMI	Now filters out the high word of ie.lKey when checking
//							for enter.  This filters out the the key flags (i.e., 
//							shift, control, alt, system).	 
//
//		09/07/97	JMI	Now BrowseForHosts() updates the display before 
//							displaying the browse dialog.
//
//		09/08/97 MJR	Fixed bug where net prob gui was showing up
//							immediately instead of after the watchdog expired.
//							Also cleaned up the erasing of the net prob gui.
//
//		09/09/97	JMI	Now initializes ms_pguiRetry to NULL in DlgBeGone().
//
//		09/09/97 MJR	Now detects protocol-not-supported and dispalys a
//							specific msg box describing the problem.
//
//		09/11/97 MJR	Now client checks to see whether the level that was
//							specified in the SETUP_GAME message is available, and
//							automatically sends a chat message that complains if it
//							isn't, in the hope that the host player will change it.
//
//							Now the host will send the realm name if only a single
//							realm is available, which tells everyone to only play
//							that realm.
//
//							Changed the dropped message, which was incorrectly using
//							the error message as the player's name.
//
//		09/11/97	JMI	Now only adds the SPECIFIC_MP_REALM_TEXT choice to the
//							host's level browser if ENABLE_PLAY_SPECIFIC_REALMS_ONLY
//							is defined. Otherwise, it chooses the first item in the 
//							listbox.
//
//		09/12/97 MJR	Reversed the #if for which method to use for filling
//							hood listbox.
//
//							Added hardwired realm stuff to SetupGame() when we're
//							in the specific realm mode.
//
//		09/18/97	JMI	There were some /"s instead of \"s.  If someone had
//							their syntax coloring on useful colors, they would've
//							seen this blaringly obvious color collage. :)
//
//		09/24/97	JMI	Fixed OnSetupGameMsg() to handle checking to see if the
//							local machine has the required realm using the title
//							that is passed in the SetupGame msg (was originally 
//							intended to use filenames but got hosed).
//
//		09/26/97	JMI	Now '-' is blocked at the UpdateDialog() level and never
//							reaches the GUIs so that the time limit and kill limit
//							edit fields cannot have a negative number enter in them
//							(of course you could enter the letter 'a' which looks
//							wrong too but I know one cares about that (you'd have to
//							be STUPID to do that but even smart people enter negative
//							numbers for time and kill limits) ).
//							Also, this keeps players from using '-' in their chat
//							strings.
//
//		11/20/97	JMI	Added cooperative flags and associated checkboxes.  Now
//							displays info on client side regarding cooperative mode
//							and carries all the necessary flagage around between
//							messages regarding cooperative mode as well.  Also, now
//							the level browse listbox can show either deathmatch or
//							cooperative levels (controlled by the user's cooperative 
//							checkbox setting).
//							Also, the user can choose operate checkbox deciding
//							whether to allow cooperative play mode (which is missiles
//							and bullets pass through fellow players).
//
//		11/25/97	JMI	Added platform conflict message and more informative
//							version conflict messages (also added version conflict 
//							message for server -- previous the error did not propagate
//							to this level).
//
//		11/25/97	JMI	Changed the server dialog .GUI to be loaded from the HD
//							instead of from the VD so we can guarantee the new asset
//							gets loaded (since they'll use their old Postal disc, we
//							cannot load the .GUI from the CD).
//
//////////////////////////////////////////////////////////////////////////////
//
// Deals with networking dialogs.  There is an interface for the server, 
//	client, and browser dialogs that deal heavily with user input, and GUI 
//	output.  The client/server messages are now handled by the black-box-like
// lower level.
//
//////////////////////////////////////////////////////////////////////////////

#include "RSPiX.h"

#include "CompileOptions.h"
#include "GameSettings.h"
#include "game.h"
#include "play.h"
#include "update.h"
#include "NetDlg.h"
#include "netbrowse.h"


//////////////////////////////////////////////////////////////////////////////
// Module specific macros.
//////////////////////////////////////////////////////////////////////////////

// Common.
#define GUI_ID_OK						1001
#define GUI_ID_CANCEL				1002

// Common Client/Server dialog.
#define GUI_ID_PLAYERS_LISTBOX	1010
#define GUI_ID_CHAT_TEXT			1013
#define GUI_ID_CHAT_SEND			1015
#define GUI_ID_NET_CONSOLE			1016
#define GUI_ID_PLAYERS_STATIC1	7000
#define GUI_ID_PLAYERS_STATIC2	7001

// Client dialog.
#define GUI_ID_OPTIONS_STATIC		2000
#define GUI_ID_RETRY					9000

// Server dialog.
#define GUI_ID_DISCONNECT_PLAYER	6000
//#define GUI_ID_RESPAWN_PLAYERS	3000
#define GUI_ID_ENABLE_TIME_LIMIT	4000
#define GUI_ID_EDIT_TIME_LIMIT	4001
#define GUI_ID_ENABLE_KILL_LIMIT	5000
#define GUI_ID_EDIT_KILL_LIMIT	5001
#define GUI_ID_LEVEL_LISTBOX		1020
#define GUI_ID_SHOW_COOP_LEVELS	8000
#define GUI_ID_ENABLE_COOP_MODE	9000

// Browser dialog.
#define GUI_ID_HOST_LISTBOX		1010

#define SERVER_GUI					"res/shell/Server.gui"
#define CLIENT_GUI					"res/shell/Client.gui"
#define BROWSER_GUI					"res/shell/Browser.gui"
#define GUI_DIR						"menu/"

// Note that this is evaluated at compile time, so even
// if the ptr is NULL, it will work.
#define MAX_STATUS_STR				GUI_MAX_STR

// Maximum number of chat strings in the box.
#define MAX_CHAT_STRINGS			20

// Time between game setup net sends.
#define OPTIONS_SEND_FREQUENCY	2000

// Amount of time that must elapse after the first "Cancel" before an
// addition "Cancel" wil be recognized.
#define CANCEL_DELAY_TIME			1500

// If status hasn't been updated for this long, then we will display the default message
#define STATUS_MAX_DISPLAY_TIME	2000

// NOTE:  If we add anymore icons, we might as well just spend the extra few
// minutes making a separate file for them.
// Net problems icon file.
#define NET_PROB_GUI_FILE			"menu/netprob.gui"

// Initial location for net problems icon on screen.
#define NET_PROB_GUI_X				10
#define NET_PROB_GUI_Y				40

#define NET_PROB_TEXT_SHADOW_COLOR_INDEX	4

#define TERMINATING_GUI_ID			0x80000000

// Note that the following color indices are from the 'Artie Zone' of colors
// in the menu palette and, therefore, should not change.
#define LIST_ITEM_TEXT_SHADOW_COLOR_INDEX			220

// This has been remapped to a Win32 color to make it stand out more
#define NET_STATUS_MSG_COLOR_INDEX					247


//////////////////////////////////////////////////////////////////////////////
// THIS ENTIRE SECTION OF STRINGS SHOULD BE MOVED TO LOCALIZE.CPP!!!
//////////////////////////////////////////////////////////////////////////////

// Client-specific messages displayed in client dialog's status area
char* g_pszClientStat_NameTooLongForChat		= "Name too long, can't chat";
char* g_pszClientStat_YouWereDropped			= "Connection was lost";
char* g_pszClientStat_SomeoneDropped_s			= "\"%s\" is no longer connected";
char* g_pszClientStat_ServerAborted				= "Game aborted";
char* g_pszClientStat_ServerStarted				= "Starting game";
char* g_pszClientStat_Opened						= "Opened connection";
char* g_pszClientStat_Connected					= "Connected";
char* g_pszClientStat_JoinDenyTooMany			= "Can't join -- too many players";
char* g_pszClientStat_JoinDenyLowBandwidth	= "Can't join -- your bandwidth is too low";
char* g_pszClientStat_JoinDenyCantDropIn		= "Can't join -- game has already started";
char* g_pszClientStat_JoinDenyUnknown			= "Can't join -- don't know why";
char* g_pszClientStat_JoinAccepted				= "Joined";
char* g_pszClientStat_LoginAccepted_hd			= "Logged in (ID = %hd)";
char* g_pszClientStat_Startup						= "Trying to connect...";
char* g_pszClientStat_Default						= "Ready";
char* g_pszClientStat_Error_s						= "Network error (%s) -- aborting";
char* g_pszClientStat_Retrying					= "Retry...";

// Server-specific messages displayed in server dialog's status area
char* g_pszServerStat_InvalidDropReq_hd		= "Ignored invalid drop request (ID = %hd)";
char* g_pszServerStat_AcceptedClient			= "\"%s\" has joined";
char* g_pszServerStat_CantAcceptJoinReq		= "Can't grant join request (too many players)";
char* g_pszServerStat_InvalidChangeReq_hd		= "Ignored invalid change request (ID = %hd)";
char* g_pszServerStat_LoginAccepted_hd			= "Login accepted (id = %hd)";
char* g_pszServerStat_LoginDeniedVersion_ld	= "Login denied (obsolete client version %ld)";
char* g_pszServerStat_LoginDeniedMagic			= "Login denied (invalid signature)";
char* g_pszServerStat_Startup						= "Setting up connection...";
char* g_pszServerStat_Default						= "Ready";
char* g_pszServerStat_CantDropSelf				= "You can't drop yourself";
char* g_pszServerStat_PlayerErr					= "Player was dropped (bad connection)";

// General messages displayed in client or server dialog's status area
char* g_pszNetStat_Aborting						= "Aborting...";
char* g_pszNetStat_Starting						= "Starting game...";
char* g_pszNetStat_AttemptToDrop_s				= "Attempting to drop \"%s\"";
char* g_pszNetStat_UnhandledMsg					= "Ignoring extraneous message";

char* g_pszNetStat_NoError							= "No errors";
char* g_pszNetStat_ReceiveError					= "Network error (can't receive data)";
char* g_pszNetStat_InQFullError					= "Network error (input buffer is full)";
char* g_pszNetStat_OutQFullError					= "Network error (output buffer is full)";
char* g_pszNetStat_SendError						= "Network error (can't send data)";
char* g_pszNetStat_InQReadError					= "Network error (can't read data)";
char* g_pszNetStat_OutQWriteError				= "Network error (couldn't write data)";
char* g_pszNetStat_ConnectionError				= "Network error (bad connection)";
char* g_pszNetStat_TimeoutError					= "Network error (time-out)";
char* g_pszNetStat_ListenError					= "Network error (can't listen)";
char* g_pszNetStat_ConnectError					= "Network error (can't connect)";
char* g_pszNetStat_ConnectTimeoutError			= "Network error (connection attempt timed-out)";
char* g_pszNetStat_ClientVersionMismatchError_lu_lu	= "Version mismatch--dropping (Host ver is %lu -- Our ver is %lu)";
char* g_pszNetStat_ServerVersionMismatchError_lu_lu	= "Version mismatch--dropping client (Client ver is %lu -- Our ver is %lu)";
char* g_pszNetStat_CantOpenPeerSocketError	= "Network error (couldn't connect to other players)";
char* g_pszNetStat_LoginDeniedError				= "Login failed";
char* g_pszNetStat_JoinDeniedError				= "Host refused join request";
char* g_pszNetStat_UnknownError					= "Network error (general failure)";
char* g_pszNetStat_ProgramError					= "Network error (generic failure)";
#if defined(WIN32)
	char* g_pszNetStat_ClientPlatformMismatchError	= "Cannot login to host because it is a Mac";
	char* g_pszNetStat_ServerPlatformMismatchError	= "Cannot allow client to connect because it is a Mac";
#else
	char* g_pszNetStat_ClientPlatformMismatchError	= "Cannot login to host because it is a PC";
	char* g_pszNetStat_ServerPlatformMismatchError	= "Cannot allow client to connect because it is a PC";
#endif

// This is  what we say when the user has chosen a protocol that is not supported.
// There are two variations: one for if the user only has one choice (because we
// only support that one) and the other for if the user can try another choice.
char* g_pszNetOnlyProtocolUnsupported_s =
	"Your system does not support \"%s\", which is the required network protocol.\n"
	"\n"
	"This protocol must be added to your system before multiplayer mode can be used.";

char* g_pszNetProtocolUnsupported_s =
	"Your system does not support \"%s\", which is the currently selected network protocol.\n"
	"\n"
	"Either add this protocol to your system or choose a different protocol from the "
	"multiplayer options menu.";

// Text which is used to dynamically update one of the text fields on the client or server dialog
char* g_pszNetDlg_ConnectedPlayers_d			= "Connected Players: %d";

// Text which is used for the net problems GUI.
// WARNING: This is an EXTERN and is used by other modules!
char*	g_pszNetProb_General =
	"Network not responding.\nYou can wait or\npress " NET_PROB_GUI_ABORT_KEY_TEXT" to abort";

// Text to prefix net status messages, if any.
char* g_pszNetStatusMsgPrefix						= "> ";


//////////////////////////////////////////////////////////////////////////////
// Module specific typedefs.
//////////////////////////////////////////////////////////////////////////////

// Dialog actions
typedef enum
	{
	DLG_NOTHING,
	DLG_OK,
	DLG_CANCEL,
	DLG_CHAT,
	DLG_DISCONNECT_PLAYER,
	DLG_OPTIONS_UPDATED,
	DLG_RETRY
	} DLG_ACTION;

// Dialog types.
typedef enum
	{
	DLG_SERVER,
	DLG_CLIENT,
	DLG_BROWSER
	} DLG_TYPE;


// GUI/Var Link
typedef struct
	{
	typedef enum
		{
		Long,
		ULong,
		Short,
		UShort,
		Char,
		UChar,
		String,
		Bool,
		Gui
		} Type;

	int32_t	lId;	// ID of GUI to link to.
	Type	type;
#if 1
	union
		{
		void*			pvLink;
		int32_t*			pl;
		uint32_t*		pul;
		int16_t*		ps;
		uint16_t*		pus;
		char*			pc;
		uint8_t*		puc;
		char*			psz;
		bool*			pb;
		RGuiItem**	ppgui;
		};
#else
	void*	pvLink;
#endif

	} GuiLink;

//////////////////////////////////////////////////////////////////////////////
// Module specific (static) variables / Instantiate class statics.
//////////////////////////////////////////////////////////////////////////////

// Common.
static RGuiItem*	ms_pguiRoot			= NULL;		// Root of GUI tree for network interface.
static RGuiItem*	ms_pguiOk			= NULL;		// GUI that, once 'clicked', indicates acceptance.
static RGuiItem*	ms_pguiCancel		= NULL;		// GUI that, once 'clicked', indicates rejection.

// Client/Server common.
static RListBox*	ms_plbPlayers		= NULL;		// Listbox used by both types of net dialogs.
static RListBox*	ms_plbNetConsole	= NULL;		// List of net console (chat and status) strings.
static RGuiItem*	ms_pguiChatText	= NULL;		// Chat text.
static RGuiItem*	ms_pguiChatSend	= NULL;		// Chat send button.

// Server.
static RListBox*	ms_plbLevelBrowse	= NULL;		// Level browse listbox.
static RGuiItem*	ms_pguiDisconnectPlayer	= NULL;	// Disconnect a player button.
static RMultiBtn*	ms_pmbCoopLevels	= NULL;		// Coop levels checkbox.
static RMultiBtn*	ms_pmbCoopMode		= NULL;		// Coop mode checkbox.

// Client.
static RGuiItem*	ms_pguiOptions		= NULL;		// Options shown on client dialog.
static RGuiItem*	ms_pguiRetry		= NULL;		// Retry button on client dialog shown when needed.

// Browser.
static RListBox*	ms_plbHostBrowse	= NULL;		// Browse for host listbox.

// Other static vars.

static int32_t			ms_lWatchdogTime = 0;			// Watchdog timer
static bool			ms_bNetBlockingAbort = false;	// Net blocking abort flag

static int32_t			ms_lNumConsoleEntries		= 0;			// Track number of chat items.

static bool			ms_bGotSetupMsg = false;
static int16_t		ms_sSetupRealmNum = 0;
static char			ms_szSetupRealmFile[Net::MaxRealmNameSize];
static int32_t			ms_lSetupLastChatComplaint = 0;

static int32_t			ms_lNextOptionsUpdateTime;		// Next time to send an options update.

static RTxt*		ms_ptxtNetProb	= NULL;			// Net problem GUI.
static bool			m_bNetWatchdogExpired	= false;	// Whether net blocking expired
static bool			ms_bCoopLevels	= false;			// true, to use cooperative levels.

// This is used by UpdateDialog() to perform GUI processing.
static RProcessGui	ms_pgDoGui;

// Linkable vars.
static bool			ms_bTimeLimit	= false;			// Enable Time Limit if true.
static bool			ms_bKillLimit	= false;			// Enable Kill Limit if true.
static bool			ms_bCoopMode = false;			// true, for cooperative mode (false for deathmatch).

static GuiLink			ms_aglServerLinkage[]	=
	{
		{ GUI_ID_DISCONNECT_PLAYER,	GuiLink::Gui,		&ms_pguiDisconnectPlayer,				},
//		{ GUI_ID_RESPAWN_PLAYERS,		GuiLink::Short,	&g_GameSettings.m_sHostRejuvenate,	},
		{ GUI_ID_ENABLE_TIME_LIMIT,	GuiLink::Bool,		&ms_bTimeLimit,							},
		{ GUI_ID_EDIT_TIME_LIMIT,		GuiLink::Short,	&g_GameSettings.m_sHostTimeLimit,	},
		{ GUI_ID_ENABLE_KILL_LIMIT,	GuiLink::Bool,		&ms_bKillLimit,							},
		{ GUI_ID_EDIT_KILL_LIMIT,		GuiLink::Short,	&g_GameSettings.m_sHostKillLimit,	},
		{ GUI_ID_LEVEL_LISTBOX,			GuiLink::Gui,		&ms_plbLevelBrowse,						},
		{ GUI_ID_SHOW_COOP_LEVELS,		GuiLink::Gui,		&ms_pmbCoopLevels,						},
		{ GUI_ID_ENABLE_COOP_MODE,		GuiLink::Gui,		&ms_pmbCoopMode,							},
		{ GUI_ID_ENABLE_COOP_MODE,		GuiLink::Bool,		&ms_bCoopMode,								},

		{ static_cast<int32_t>(TERMINATING_GUI_ID), },	// Terminator.
	};

static GuiLink			ms_aglClientLinkage[]	=
	{
		{ GUI_ID_OPTIONS_STATIC,		GuiLink::Gui,		&ms_pguiOptions,							},   
		{ GUI_ID_RETRY,					GuiLink::Gui,		&ms_pguiRetry,								},
													 
		{ static_cast<int32_t>(TERMINATING_GUI_ID), },	// Terminator.
	};

static GuiLink			ms_aglClientServerLinkage[]	=
	{
		{ GUI_ID_PLAYERS_LISTBOX,		GuiLink::Gui,		&ms_plbPlayers,							},   
		{ GUI_ID_CHAT_TEXT,				GuiLink::Gui,		&ms_pguiChatText,							},	 
		{ GUI_ID_CHAT_SEND,				GuiLink::Gui,		&ms_pguiChatSend,							},	   
		{ GUI_ID_NET_CONSOLE,			GuiLink::Gui,		&ms_plbNetConsole,						},	   
		{ GUI_ID_OK,						GuiLink::Gui,		&ms_pguiOk,									},
		{ GUI_ID_CANCEL,					GuiLink::Gui,		&ms_pguiCancel,							},
													 
		{ static_cast<int32_t>(TERMINATING_GUI_ID), },	// Terminator.
	};

static GuiLink			ms_aglBrowserLinkage[]	=
	{
		{ GUI_ID_HOST_LISTBOX,			GuiLink::Gui,		&ms_plbHostBrowse,						},   
		{ GUI_ID_OK,						GuiLink::Gui,		&ms_pguiOk,									},
		{ GUI_ID_CANCEL,					GuiLink::Gui,		&ms_pguiCancel,							},
													 
		{ static_cast<int32_t>(TERMINATING_GUI_ID), },	// Terminator.
	};


//////////////////////////////////////////////////////////////////////////////
// Module specific (static) protos.
//////////////////////////////////////////////////////////////////////////////

static void AddConsoleMsg(	// Returns nothing.
	bool	bChat,				// In:  true for a chat message, or false for others (like net status).
	const char* pszFrmt,		// In:  sprintf style formatting.
	...);							// In:  Optional arguments based on context of pszFrmt.

// Get dialog resource
int16_t DlgGetRes(											// Returns 0 if successfull, non-zero otherwise
	RGuiItem* pgui);										// I/O: Pointer to gui item

// Release dialog resource
void DlgReleaseRes(										// Returns 0 if successfull, non-zero otherwise
	RGuiItem* pgui);										// I/O: Pointer to gui item

// Net blocking callback
static int16_t NetBlockingCallback(void);			// Returns 0 to continue normally, 1 to abort

static int16_t BrowseForHost(
	CNetServer*	pserver,									// I/O: Server interface or NULL if none
	RSocket::Address* paddress);						// Out: Address returned here (if successfull)

static int16_t FindSpecificSystem(
	RSocket::Address* paddress);						// Out: Address returned here (if successfull)

static int16_t BrowseForSelf(
	CNetServer*	pserver,									// I/O: Server interface
	RSocket::Address* paddress);						// Out: Address returned here (if successfull)


//////////////////////////////////////////////////////////////////////////////
// Helper for UploadLinks() to handle all integer vars.
//////////////////////////////////////////////////////////////////////////////
template <class Int>				// Templated input type (can be unsigned).
void UploadLinkInteger(			// Returns nothing.
	RGuiItem*	pgui,				// In:  GUI to upload to.
	Int	i)							// In:  Input val to upload to GUI.
	{
	ASSERT(pgui);

	switch (pgui->m_type)
		{
		case RGuiItem::MultiBtn:
			{
			RMultiBtn*	pmb	= (RMultiBtn*)pgui;
			if (i)
				{
				pmb->m_sState	= 1;
				}
			else
				{
				pmb->m_sState	= 2;
				}
			break;
			}
		case RGuiItem::PushBtn:
			{
			RPushBtn*	ppushbtn	= (RPushBtn*)pgui;
			if (i)
				{
				ppushbtn->m_state	= RPushBtn::On;
				}
			else
				{
				ppushbtn->m_state	= RPushBtn::Off;
				}
			break;
			}
		default:
#if 0
			// Determine if signed (this is wierd but may work) . . .
			if ((Int)-1 < 0)
				{
				// Signed.
				pgui->SetText("%ld", (long)i);
				}
			else
				{
				// Unsigned.
				pgui->SetText("%lu", (uint32_t)i);
				}
#else
			// Hardwire to signed b/c bool was displaying a warning regarding the
			// above comparison to determine the [un]signed nature of the templated
			// type.
			pgui->SetText("%ld", (int32_t)i);
#endif
			break;
		}

	pgui->Compose();
	}

//////////////////////////////////////////////////////////////////////////////
// Helper for DownloadLinks() to handle all integer vars.
//////////////////////////////////////////////////////////////////////////////
template <class Int>				// Templated output type (can be unsigned).
void DownloadLinkInteger(		// Returns nothing.
	RGuiItem*	pgui,				// In:  GUI to download from.
	Int*	pi)						// Out: Input val to download into from GUI.
	{
	ASSERT(pgui);

	switch (pgui->m_type)
		{
		case RGuiItem::MultiBtn:
			{
			RMultiBtn*	pmb	= (RMultiBtn*)pgui;
			*pi = (pmb->m_sState == 1) ? 1 : 0;
			break;
			}
		case RGuiItem::PushBtn:
			{
			RPushBtn*	ppushbtn	= (RPushBtn*)pgui;
			*pi = (ppushbtn->m_state == RPushBtn::On) ? 1 : 0;
			break;
			}
		default:
#if 0
			// Determine if signed (this is wierd but may work) . . .
			if ((Int)-1 < 0)
				{
				// Signed.
				*pi = pgui->GetVal();
				}
			else
				{
				// Unsigned.
				*pi = strtoul(pgui->m_szText, NULL, 0);
				}
#else
			// Hardwire to signed b/c bool was displaying a warning regarding the
			// above comparison to determine the [un]signed nature of the templated
			// type.
			*pi = pgui->GetVal(); 
#endif
			break;
		}

	pgui->Compose();
	}

//////////////////////////////////////////////////////////////////////////////
//
// Upload variables to their GUI links.
//
//////////////////////////////////////////////////////////////////////////////
static void UploadLinks(	// Returns nothing.
	GuiLink*		pagl,			// In:  Links to upload.
	RGuiItem*	pguiRoot)	// In:  GUI to upload to.
	{
	ASSERT(pguiRoot);

	while (pagl->lId != TERMINATING_GUI_ID)
		{
		// Get item.
		RGuiItem*	pgui	= pguiRoot->GetItemFromId(pagl->lId);
		if (pgui)
			{
			switch (pagl->type)
				{
				case GuiLink::Long:
					UploadLinkInteger(pgui, *pagl->pl);
					break;

				case GuiLink::ULong:
					UploadLinkInteger(pgui, *pagl->pul);
					break;
				
				case GuiLink::Short:
					UploadLinkInteger(pgui, *pagl->ps);
					break;
				
				case GuiLink::UShort:
					UploadLinkInteger(pgui, *pagl->pus);
					break;

				case GuiLink::Char:
					UploadLinkInteger(pgui, *pagl->pc);
					break;
				
				case GuiLink::UChar:
					UploadLinkInteger(pgui, *pagl->puc);
					break;

				case GuiLink::Bool:
					UploadLinkInteger(pgui, *pagl->pb);
					break;
				
				case GuiLink::String:
					pgui->SetText("%s", pagl->psz );
					break;

				// This may seem backward but it's more convenient.
				case GuiLink::Gui:
					*pagl->ppgui	= pgui;
					break;

				default:
					TRACE("UploadLinks(): Type %d not supported.\n",
						pagl->type);
					break;
				}
			}
		else
			{
			TRACE("UploadLinks(): GUI ID %d does not exist.\n", pagl->lId);
			}

		// Next.
		pagl++;
		}
	}

//////////////////////////////////////////////////////////////////////////////
//
// Download variables to their GUI links.
//
//////////////////////////////////////////////////////////////////////////////
static void DownloadLinks(	// Returns nothing.
	GuiLink*		pagl,			// In:  Links to upload.
	RGuiItem*	pguiRoot)	// In:  GUI to upload to.
	{
	ASSERT(pguiRoot);

	while (pagl->lId != TERMINATING_GUI_ID)
		{
		// Get item.
		RGuiItem*	pgui	= pguiRoot->GetItemFromId(pagl->lId);
		if (pgui)
			{
			switch (pagl->type)
				{
				case GuiLink::Long:
					DownloadLinkInteger(pgui, pagl->pl);
					break;
				
				case GuiLink::ULong:
					DownloadLinkInteger(pgui, pagl->pul);
					break;
				
				case GuiLink::Short:
					DownloadLinkInteger(pgui, pagl->ps);
					break;
				
				case GuiLink::UShort:
					DownloadLinkInteger(pgui, pagl->pus);
					break;
				
				case GuiLink::Char:
					DownloadLinkInteger(pgui, pagl->pc);
					break;
				
				case GuiLink::UChar:
					DownloadLinkInteger(pgui, pagl->puc);
					break;
				
				case GuiLink::Bool:
					DownloadLinkInteger(pgui, pagl->pb);
					break;
				
				case GuiLink::String:
					strcpy( pagl->psz, pgui->m_szText );
					break;
				
				case GuiLink::Gui:
					break;

				default:
					TRACE("DownloadLinks(): Type %d not yet supported.\n",
						pagl->type);
					break;
				}
			}
		else
			{
			TRACE("DownloadLinks(): GUI ID %d does not exist.\n", pagl->lId);
			}

		// Next.
		pagl++;
		}
	}

//////////////////////////////////////////////////////////////////////////////
// 
// Macro to activate certain parms to make our list item GUI's look nice and
// readable.
//
//////////////////////////////////////////////////////////////////////////////
inline void MakeMoreReadable(		// Returns nothing.
	RGuiItem*	pgui)					// In:  GUI to shadowify using global values.
	{
	ASSERT(pgui);

	if (pgui)
		{
		pgui->m_sTextEffects			= RGuiItem::Shadow;
		pgui->m_u32TextShadowColor	= LIST_ITEM_TEXT_SHADOW_COLOR_INDEX;
		pgui->m_sShowFocus			= FALSE;
		}
	}

//////////////////////////////////////////////////////////////////////////////
//
// [Re]compose Options GUI with word wrap preserving original word wrap status.
//
//////////////////////////////////////////////////////////////////////////////
inline void ComposeOptions(void)
	{
	// Most likely someone has already checked this before calling this but
	// it doesn't hurt to be safe.
	if (ms_pguiOptions)
		{
		// Store old word wrap status so we can restore it when done.
		int16_t sWordWrapWas	= (ms_pguiOptions->m_pprint->m_eModes & RPrint::WORD_WRAP) ? TRUE : FALSE;

		// Enable word wrap (not accessible from GUI editor currently).
		ms_pguiOptions->m_pprint->SetWordWrap(TRUE);

		ms_pguiOptions->Compose();

		// Reset word wrap.
		ms_pguiOptions->m_pprint->SetWordWrap(sWordWrapWas);
		}
	}

//////////////////////////////////////////////////////////////////////////////
//
// Clean/Reset Client dialog to defaults.
//
//////////////////////////////////////////////////////////////////////////////
static void CleanClientDlg(
	CNetClient* pnet,
	bool bRetryButton)
	{
	if (ms_pguiOptions)
		{
		// Set no-connection text for options GUI.
		ms_pguiOptions->SetText("Not currently connected to a host.");
		// Repaginate now!
		ComposeOptions();
		}

	if (ms_plbPlayers)
		{
		// Empty players listbox.
		ms_plbPlayers->RemoveAll();
		}

	int iNumPlayers = (pnet) ? pnet->GetNumPlayers() : 0;
		
	// This cheese updates the number of players displayed.  I cannot remember why we did not simply
	// make this one text shadowed GUI.
	RGuiItem*	pguiConnected	= ms_pguiRoot->GetItemFromId(GUI_ID_PLAYERS_STATIC1);
	RSP_SAFE_GUI_REF_VOID(pguiConnected, SetText(g_pszNetDlg_ConnectedPlayers_d, iNumPlayers));
	RSP_SAFE_GUI_REF_VOID(pguiConnected, Compose());
	pguiConnected	= ms_pguiRoot->GetItemFromId(GUI_ID_PLAYERS_STATIC2);
	RSP_SAFE_GUI_REF_VOID(pguiConnected, SetText(g_pszNetDlg_ConnectedPlayers_d, iNumPlayers));
	RSP_SAFE_GUI_REF_VOID(pguiConnected, Compose());

	
	if (ms_pguiRetry)
		{
		// Show as specified by caller.
		ms_pguiRetry->SetVisible(bRetryButton ? TRUE : FALSE);
		}
	}

//////////////////////////////////////////////////////////////////////////////
//
// Show the selectable network levels in the hood to play listbox.
//
//////////////////////////////////////////////////////////////////////////////
static int16_t ShowLevels(void)						// Returns 0 on success.
	{
	int16_t	sRes	= 0;	// Assume success.

	if (ms_plbLevelBrowse != NULL)
		{
		// Must be listbox.
		ASSERT(ms_plbLevelBrowse->m_type == RGuiItem::ListBox);
		// Get rid of existing entries.
		ms_plbLevelBrowse->RemoveAll();

		#if !defined(ENABLE_PLAY_SPECIFIC_REALMS_ONLY)
			// Add all the available realms.
			char	szRealm[RSP_MAX_PATH+1];
			char	szTitle[512];
			int16_t	i	= 0;
			while (sRes == 0)
				{
				// Get realm name from realm prefs file
				sRes = Play_GetRealmInfo(true, ms_bCoopLevels, false, false, i, g_GameSettings.m_sDifficulty, szRealm, sizeof(szRealm), szTitle, sizeof(szTitle));
				if (sRes == 1)
					{
					// That's it.
					sRes	= 0;
					break;
					}
				else if (sRes == 0)
					{
					// Add to listbox.
					RGuiItem*	pguiLevel = ms_plbLevelBrowse->AddString(szTitle);
					if (pguiLevel != NULL)
						{
						// Activate shadow parameters.
						MakeMoreReadable(pguiLevel);
						pguiLevel->Compose();

						pguiLevel->m_lId = i;
						}
					else
						{
						TRACE("ShowLevels(): Failed to add string to listbox.\n");
						sRes	= -1;
						}
					}
				i++;
				}

		#else

			// Add the one and only level option.
			RGuiItem*	pguiLevel = ms_plbLevelBrowse->AddString(SPECIFIC_MP_REALM_TEXT);
			if (pguiLevel != NULL)
				{
				// Activate shadow parameters.
				MakeMoreReadable(pguiLevel);
				pguiLevel->Compose();

				pguiLevel->m_lId = SPECIFIC_MP_REALM_NUM;
				}
			else
				{
				TRACE("ShowLevels(): Failed to add string to listbox.\n");
				sRes	= -1;
				}

		#endif	// ENABLE_PLAY_SPECIFIC_REALMS_ONLY

		// Select the first item in the listbox.
		ms_plbLevelBrowse->SetSel(ms_plbLevelBrowse->GetFirst() );
		// Update listbox.
		ms_plbLevelBrowse->AdjustContents();
		}

	return sRes;
	}

//////////////////////////////////////////////////////////////////////////////
//
// Be done with the current dialog and related settings.
//
//////////////////////////////////////////////////////////////////////////////
static void DlgBeGone(void)
	{
	// Clean up processor.
	ms_pgDoGui.Unprepare();

	if (ms_pguiRoot != NULL)
		{
		delete ms_pguiRoot;
		}

	ms_pguiRoot					= NULL;
	ms_pguiOk					= NULL;
	ms_pguiCancel				= NULL;
	ms_plbPlayers				= NULL;
	ms_plbNetConsole			= NULL;
	ms_pguiChatText			= NULL;
	ms_pguiChatSend			= NULL;
	ms_plbLevelBrowse			= NULL;
	ms_pguiOptions				= NULL;
	ms_pguiDisconnectPlayer	= NULL;
	ms_pmbCoopLevels			= NULL;
	ms_pmbCoopMode				= NULL;
	ms_plbHostBrowse			= NULL;
	ms_pguiRetry				= NULL;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Setup the specified dialog and related settings.
//
//////////////////////////////////////////////////////////////////////////////
static int16_t SetupDlg(		// Returns 0 on success.
	char*	pszGuiFile,			// In:  Full path to GUI file.
	DLG_TYPE	type)				// In:  Type of dialog.
	{
	int16_t	sRes	= 0;	// Assume success.

	// Make sure everything is clean.
	DlgBeGone();

	// Anh...reset these here.
	ms_lNumConsoleEntries					= 0;
	ms_lNextOptionsUpdateTime	= 0;

	// Create a dialog.  We have to take this approach instea of the nicer
	// LoadInstantiate() method because we need to install callbacks for
	// getting and releasing resources, which we can only do if we already
	// have the gui item (the dialog in this case).  With LoadInstantiate(),
	// the dialog doesn't exist until after the call, and by then the resource
	// has already been loaded (or failed to load in this case because the
	// gui stuff can't possibly know the correct path for loading it).
	ms_pguiRoot = new RDlg;
	if (ms_pguiRoot != NULL)
		{
		// Setup callbacks for getting and releasing resources
		ms_pguiRoot->m_fnGetRes = DlgGetRes;
		ms_pguiRoot->m_fnReleaseRes = DlgReleaseRes;

		// Set font.  The size in this call matters not b/c each GUI item
		// has a size it uses when printing.
		ms_pguiRoot->m_pprint->SetFont(15, &g_fontPostal);

		// Load the gui description file
		sRes = ms_pguiRoot->Load(pszGuiFile);
		if (sRes == 0)
			{

			// Set focus to first child control or none if there's none.
			ms_pguiRoot->SetFocus(ms_pguiRoot->m_listguiChildren.GetHead());

			// The special case stuff.
			switch (type)
				{
				case DLG_CLIENT:
					{
					// Upload client stuff.
					UploadLinks(ms_aglClientLinkage, ms_pguiRoot);

					// Upload stuff common to client/server.
					UploadLinks(ms_aglClientServerLinkage, ms_pguiRoot);

					// If exists . . .
					if (ms_plbPlayers != NULL)
						{
						// Must be listbox.
						ASSERT(ms_plbPlayers->m_type == RGuiItem::ListBox);
						// Get rid of existing entries.
						ms_plbPlayers->RemoveAll();
						}

					// If exists . . .
					if (ms_pguiChatText != NULL)
						{
						// Must be edit.
						ASSERT(ms_pguiChatText->m_type == RGuiItem::Edit);
						// Limit text.
						( (REdit*)ms_pguiChatText)->m_sMaxText	= Net::MaxChatSize - 1;
						}

					// Make the options GUI more readable.
					if (ms_pguiOptions)
						{
						MakeMoreReadable(ms_pguiOptions);
						}

					// Set title text.
					ms_pguiRoot->SetText(
						"%s [%s]", 
						ms_pguiRoot->m_szText, 
						g_GameSettings.m_szPlayerName);
					ms_pguiRoot->Compose();

					// Start with a clean slate.
					CleanClientDlg(0, false);

					break;
					}
				case DLG_SERVER:
					{
					// Upload server stuff.
					UploadLinks(ms_aglServerLinkage, ms_pguiRoot);

					// Upload stuff common to client/server.
					UploadLinks(ms_aglClientServerLinkage, ms_pguiRoot);

					// If exists . . .
					if (ms_plbPlayers != NULL)
						{
						// Must be listbox.
						ASSERT(ms_plbPlayers->m_type == RGuiItem::ListBox);
						// Get rid of existing entries.
						ms_plbPlayers->RemoveAll();
						}

					// If exists . . .
					if (ms_pguiChatText != NULL)
						{
						// Must be edit.
						ASSERT(ms_pguiChatText->m_type == RGuiItem::Edit);
						// Limit text.
						( (REdit*)ms_pguiChatText)->m_sMaxText	= Net::MaxChatSize - 1;
						}

					// If exists . . .
					if (ms_pmbCoopLevels)
						{
						// Must be multibtn.
						ASSERT(ms_pmbCoopLevels->m_type == RGuiItem::MultiBtn);
						// Set state to last choice.
						ms_pmbCoopLevels->m_sState	= (ms_bCoopLevels == false) ? 1 : 2;
						// Recompose with new state.
						ms_pmbCoopLevels->Compose();
						}

					// If exists . . .
					if (ms_pmbCoopMode)
						{
						// Must be multibtn.
						ASSERT(ms_pmbCoopMode->m_type == RGuiItem::MultiBtn);
						// Set state to last choice.
						ms_pmbCoopMode->m_sState	= (ms_bCoopMode == false) ? 2 : 1;
						// Recompose with new state.
						ms_pmbCoopMode->Compose();
						}

					// Fill level browser listbox.
					ShowLevels();

					// Set title text.
					ms_pguiRoot->SetText(
						"%s [%s]", 
						ms_pguiRoot->m_szText, 
						g_GameSettings.m_szPlayerName);
					ms_pguiRoot->Compose();

					break;
					}
				case DLG_BROWSER:
					{
					// Upload browser linkage.
					UploadLinks(ms_aglBrowserLinkage, ms_pguiRoot);

					// If exists . . .
					if (ms_plbHostBrowse)
						{
						// Must be listbox.
						ASSERT(ms_plbHostBrowse->m_type == RGuiItem::ListBox);
						// Get rid of existing entries.
						ms_plbHostBrowse->RemoveAll();
						}
					break;
					}
				}

			// Center.
			ms_pguiRoot->Move(
				g_pimScreenBuf->m_sWidth / 2 - ms_pguiRoot->m_im.m_sWidth / 2,
				g_pimScreenBuf->m_sHeight / 2 - ms_pguiRoot->m_im.m_sHeight / 2);

			// Make visible.
			ms_pguiRoot->SetVisible(TRUE);

			// Prepare GUI processor.
			ms_pgDoGui.m_sFlags	= RProcessGui::NoCleanScreen;

			ms_pgDoGui.Prepare(ms_pguiRoot, ms_pguiOk, ms_pguiCancel);
			}
		else
			{
			TRACE("SetupDlg(): Failed to load .gui file!\n");
			}
		}
	else
		{
		TRACE("SetupDlg(): Failed to allocate RDlg!\n");
		sRes = -1;
		}

	// If any errors . . .
	if (sRes != 0)
		{
		DlgBeGone();
		}

	return sRes;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Get dialog resource
//
//////////////////////////////////////////////////////////////////////////////
int16_t DlgGetRes(											// Returns 0 if successfull, non-zero otherwise
	RGuiItem* pgui)										// I/O: Pointer to gui item
	{
	int16_t sResult = 0;

	// Release resources first (just in case)
	DlgReleaseRes(pgui);

	// Allocate and load new resources.  We get the name of the file (which
	// is ASSUMED to have NO PATH!!) from the gui itself, then tack on the
	// path we need and get the resource from the resource manager.
	char szFile[RSP_MAX_PATH * 2];
	sprintf(szFile, "%s%s", GUI_DIR, pgui->m_szBkdResName);

	if (rspGetResource(&g_resmgrShell, szFile, &pgui->m_pimBkdRes) == 0)
		{
		// Set palette
		ASSERT(pgui->m_pimBkdRes->m_pPalette != NULL);
		ASSERT(pgui->m_pimBkdRes->m_pPalette->m_type == RPal::PDIB);
		rspSetPaletteEntries(
			0,
			230,
			pgui->m_pimBkdRes->m_pPalette->Red(0),
			pgui->m_pimBkdRes->m_pPalette->Green(0),
			pgui->m_pimBkdRes->m_pPalette->Blue(0),
			pgui->m_pimBkdRes->m_pPalette->m_sPalEntrySize);

		// Update hardware palette.
		rspUpdatePalette();
		}
	else
		{
		sResult = -1;
		TRACE("DlgGetRes(): Failed to open file '%s'\n", FullPathVD(szFile));
		}

	return sResult;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Release dialog resource
//
//////////////////////////////////////////////////////////////////////////////
void DlgReleaseRes(										// Returns 0 if successfull, non-zero otherwise
	RGuiItem* pgui)										// I/O: Pointer to gui item
	{
	rspReleaseResource(&g_resmgrShell, &pgui->m_pimBkdRes);
	}


//////////////////////////////////////////////////////////////////////////////
//
// Process GUI tree through one iteration.
//
//////////////////////////////////////////////////////////////////////////////
static DLG_ACTION UpdateDialog(						// Returns dialog action
	RGuiItem*	pguiRoot,								// In:  GUI to process via user input.
	bool			bReset)									// In:  If false, does not reset any
																// GUIs before returning their action.
																// Note that this means that the next
																// time through, we'll probably return
																// the same action.
	{
	// Get next input event.
	RInputEvent	ie;
	// Make sure we start with no event.
	ie.type	= RInputEvent::None;
	rspGetNextInputEvent(&ie);

	// Block minus sign right here (note that this will keep players 
	// from being able to use '-' in chat strings).
	if (ie.type == RInputEvent::Key)
		{
		switch (ie.lKey & 0x0000FFFF)
			{
			case '-':
				ie.type	= RInputEvent::None;
				break;
			}
		}

	// When we lose the focus, this might need to be updated.
	// Should we do it everytime?
	rspNameBuffers(&g_pimScreenBuf);

	// Process GUI through an iteration.
	int32_t	lPressedId	= ms_pgDoGui.DoModeless(pguiRoot, &ie, g_pimScreenBuf);

	// If OK chosen or enter pressed . . .
	if (lPressedId == GUI_ID_OK || (ie.type == RInputEvent::Key && (ie.lKey & 0x0000FFFF) == '\r') )
		{
		// If there's a focus . . .
		if (RGuiItem::ms_pguiFocus)
			{
			// If in chatbox . . .
			if (RGuiItem::ms_pguiFocus == ms_pguiChatText)
				{
				// Send chat.
				RSP_SAFE_GUI_REF_VOID(ms_pguiChatSend, SetClicked(TRUE) );
				}
			else if (RGuiItem::ms_pguiFocus == ms_pguiRetry)
				{
				RSP_SAFE_GUI_REF_VOID(ms_pguiRetry, SetClicked(TRUE) );
				}
			else
				{
				// OK.
				RSP_SAFE_GUI_REF_VOID(ms_pguiOk, SetClicked(TRUE) );
				}
			}
		else
			{
			// OK.
			RSP_SAFE_GUI_REF_VOID(ms_pguiOk, SetClicked(TRUE) );
			}
		}

	// Return proper action based on what the user clicked on
	DLG_ACTION action = DLG_NOTHING;
	if (RSP_SAFE_GUI_REF(ms_pguiOk, IsClicked()))
		{
		if (bReset)
			{
			RSP_SAFE_GUI_REF_VOID(ms_pguiOk, SetClicked(FALSE));
			}
		
		action = DLG_OK;
		}

	if (RSP_SAFE_GUI_REF(ms_pguiCancel, IsClicked()))
		{
		if (bReset)
			{
			RSP_SAFE_GUI_REF_VOID(ms_pguiCancel, SetClicked(FALSE));
			}

		action = DLG_CANCEL;
		}

	if (RSP_SAFE_GUI_REF(ms_pguiRetry, IsClicked() ) )
		{
		if (bReset)
			{
			RSP_SAFE_GUI_REF_VOID(ms_pguiRetry, SetClicked(FALSE) );
			}

		action	= DLG_RETRY;
		}

	if (RSP_SAFE_GUI_REF(ms_pguiChatSend, IsClicked()))
		{
		if (bReset)
			{
			if (ms_pguiChatSend)
				{
				ms_pguiChatSend->SetClicked(FALSE);

				// If focus is on the chat send . . .
				if (RGuiItem::ms_pguiFocus == ms_pguiChatSend && ms_pguiChatText)
					{
					// Switch back to the edit...makes sense on the user interface, I think.
					RGuiItem::SetFocus(ms_pguiChatText);
					}
				}
			}

		action = DLG_CHAT;
		}

	if (RSP_SAFE_GUI_REF(ms_pguiDisconnectPlayer, IsClicked() ) )
		{
		if (bReset)
			{
			RSP_SAFE_GUI_REF_VOID(ms_pguiDisconnectPlayer, SetClicked(FALSE) );
			}

		action	= DLG_DISCONNECT_PLAYER;
		}

	// If no other action . . .
	if (action == DLG_NOTHING)
		{
		// Temporarily timed based. ***
		int32_t	lCurTime	= rspGetMilliseconds();
		if (lCurTime > ms_lNextOptionsUpdateTime)
			{
			if (bReset)
				{
				ms_lNextOptionsUpdateTime	= lCurTime + OPTIONS_SEND_FREQUENCY;
				}

			action	= DLG_OPTIONS_UPDATED;
			}
		}

	if (ms_pmbCoopLevels)
		{
		// If not pressed . . .
		if (ms_pmbCoopLevels->m_sState > 0)
			{
			bool	bCoopLevels	= (ms_pmbCoopLevels->m_sState == 2) ? true : false;

			// If status has changed . . .
			if (bCoopLevels != ms_bCoopLevels)
				{
				// Set new value.
				ms_bCoopLevels	= bCoopLevels;

				// Repaginate.
				ShowLevels();

				// If showing deathmatch levels . . .
				if (bCoopLevels == false && ms_pmbCoopMode)
					{
					// Since cooperative mode in deathmatch levels makes little
					// sense, let's automagically switch to deathmatch mode for
					// convenience sake.
					ms_pmbCoopMode->m_sState	= 2;
					ms_pmbCoopMode->Compose();
					}
				}
			}
		}

	return action;
	}

//////////////////////////////////////////////////////////////////////////////
//
// Update hosts listbox for browser.
//
//////////////////////////////////////////////////////////////////////////////
static int16_t UpdateListBox(					// Returns 0 on success.
	RListBox*	plb,								// In:  Browser listbox.
	CNetBrowse::Hosts* phostslistPersist,	// In:  Hosts.
	CNetBrowse::Hosts* phostslistAdded,		// In:  Hosts to add to listbox.
	CNetBrowse::Hosts* phostslistDropped)	// In:  Hosts to drop from listbox.
	{
	int16_t	sResult	= 0;	// Assume success.

	if (plb)
		{
		CNetBrowse::Hosts::Pointer	i;
		bool	bRepaginate	= false;
		
		// Look for unGUIed entries . . .
		for (i = phostslistPersist->GetHead(); i; i = phostslistPersist->GetNext(i))
			{
			CNetBrowse::CHost* phost = &(phostslistPersist->GetData(i) );
			// If not yet GUIed . . .
			if ( !(phost->m_u32User) )
				{
				RGuiItem*	pgui	= plb->AddString(phost->m_acName);
				if (pgui)
					{
					// Activate shadow parameters.
					MakeMoreReadable(pgui);
					pgui->Compose();
					// Point GUI at entry.
					pgui->m_ulUserData	= (U64)phost;
					// Successfully added entry.
					phost->m_u32User	= (U64)pgui;
					// Note that we updated the dialog and will need to re-adjust
					// fields and recompose.
					bRepaginate	= true;
					}
				else
					{
					TRACE("UpdateListBox():  Failed to add a host to the listbox.\n");
//					sResult	= -1;	// Error?
					}
				}
			}

		// For whatever it's worth, let's do dropped first so it'll be a little
		// faster.  On second thought, let's not.  It just seems a bit scary.  Like,
		// if a host gets added and then dropped on the same iteration, it will not
		// be in the listbox and I was using that conidition to hopefully flag bugs.

		// Note that we use the m_u32User field of the host structure to store a pointer
		// to the corresponding GUI item.  Since we know these host items get copied
		// from the added list to the main list and then, possibly, to the dropped list
		// this value will remain with the host all the way to the dropped list.
		while (phostslistDropped->GetHead())
			{
			// Get pointer to first host in list
			U32 u32User = phostslistDropped->GetHeadData().m_u32User;

			// We should have already been using this.
			ASSERT(u32User);
			if (u32User)
				{
				// Remove the corresponding GUI list entry from the listbox.
				plb->RemoveItem((RGuiItem*)(u32User));
				// Note that we updated the dialog and will need to re-adjust
				// fields and recompose.
				bRepaginate	= true;
				}

			// Remove first host in list
			phostslistDropped->RemoveHead();
			}

		if (bRepaginate)
			{
			plb->AdjustContents();
			}

		// If there is a selection . . .
		if (plb->GetSel() )
			{
			// Currently, we view this as a choice.  Let's simply set the OK button
			// so it'll be easy to switch back and forth between these two methods.
			RSP_SAFE_GUI_REF_VOID(ms_pguiOk, SetClicked(TRUE) );
			}

		// Empty the added list, which we don't use, but we don't want it to keep
		// growing either, and it's our responsibility to empty it.
		while (phostslistAdded->GetHead())
			phostslistAdded->RemoveHead();
		}
	else
		{
		TRACE("UpdateListBox():  No listbox to update.\n");
		sResult	= -1;
		}

	return sResult;
	}

//////////////////////////////////////////////////////////////////////////////
//
// Add a console message.
//
//////////////////////////////////////////////////////////////////////////////
static void AddConsoleMsg(	// Returns nothing.
	bool	bChat,				// In:  true for a chat message, or false for others (like net status).
	const char* pszFrmt,		// In:  sprintf style formatting.
	...)							// In:  Optional arguments based on context of pszFrmt.
	{
	if (ms_plbNetConsole != NULL)
		{
		char szOutput[MAX_STATUS_STR];

		va_list varp;
		va_start(varp, pszFrmt);    
		vsprintf(szOutput, pszFrmt, varp);
		va_end(varp);

		U32	u32TextColor	= ms_plbNetConsole->m_u32TextColor;

		char szMsg[MAX_STATUS_STR];
		// If it's a chat message . . .
		if (bChat)
			{
			// Verbatim is good (already includes name and such).
			strcpy(szMsg, szOutput);
			}
		else
			{
			// Otherwise, add optional prefix.
			sprintf(szMsg, "%s%s", g_pszNetStatusMsgPrefix, szOutput);
			// And use alternate color.
			u32TextColor		= NET_STATUS_MSG_COLOR_INDEX;
			}

		bool	bRepaginate	= false;	// true to repaginate the listbox.

		// If this one will put us over . . .
		if (ms_lNumConsoleEntries >= MAX_CHAT_STRINGS)
			{
			// Get the oldest chat.
			RGuiItem*	pguiOldestConsoleMsg	= ms_plbNetConsole->GetFirst();
			if (pguiOldestConsoleMsg)
				{
				// Remove it.
				ms_plbNetConsole->RemoveItem(pguiOldestConsoleMsg);
				// Repaginate.
				bRepaginate	= true;
				}
			}

		RGuiItem*	pguiConsoleMsg	= ms_plbNetConsole->AddString(szMsg);
		if (pguiConsoleMsg)
			{
			// Another chat.
			ms_lNumConsoleEntries++;
			// Store the old border thickness so we know how much we can reduce
			// these.
			int16_t	sOrigTotalBorderThickness	= pguiConsoleMsg->GetTopLeftBorderThickness() + pguiConsoleMsg->GetBottomRightBorderThickness();
			// No lines.
			pguiConsoleMsg->m_sBorderThickness	= 0;
			// Adjust color.
			pguiConsoleMsg->m_u32TextColor		= u32TextColor;
			// Activate shadow parameters.
			MakeMoreReadable(pguiConsoleMsg);
			// Recreate without space for border lines . . .
			if (pguiConsoleMsg->Create(
				pguiConsoleMsg->m_sX, 
				pguiConsoleMsg->m_sY,
				// We want to keep these as small as possible so we can fit as many as possible.
				// Subtract the border thickness since we don't use it but add 1 for text shadow effect.
				pguiConsoleMsg->m_im.m_sWidth - sOrigTotalBorderThickness + 1,
				pguiConsoleMsg->m_im.m_sHeight - sOrigTotalBorderThickness + 1,
				pguiConsoleMsg->m_im.m_sDepth) == 0)
				{
				// We cannot click on these.
				pguiConsoleMsg->m_sActive	= FALSE;
				pguiConsoleMsg->SetActive(FALSE);
				// Repaginate now, now.
				ms_plbNetConsole->AdjustContents();
				// Ensure the new item is visible.
				ms_plbNetConsole->EnsureVisible(pguiConsoleMsg);
				}
			else
				{
				// This is useless then.
				delete pguiConsoleMsg;
				pguiConsoleMsg	= NULL;
				}
			}
		else
			{
			// If we need to repaginate anyways . . .
			if (bRepaginate)
				{
				// Repaginate now even though we failed to add a new string.
				ms_plbNetConsole->AdjustContents();
				}
			}
		}
	}


//////////////////////////////////////////////////////////////////////////////
//
// Get descriptive text associated with specified error message
//
//////////////////////////////////////////////////////////////////////////////
extern const char* NetErrorText(						// Returns pointer to text
	NetMsg* pmsg)											// In:  Error message
	{
	static char szStaticErrorText[512];
	char* pText = "";
	if (pmsg->msg.nothing.ucType == NetMsg::ERR)
		{
		switch (pmsg->msg.err.error)
			{
			case NetMsg::NoError:
				pText = g_pszNetStat_NoError;
				break;
			case NetMsg::ReceiveError:
				pText = g_pszNetStat_ReceiveError;
				break;
			case NetMsg::InQFullError:
				pText = g_pszNetStat_InQFullError;
				break;
			case NetMsg::OutQFullError:
				pText = g_pszNetStat_OutQFullError;
				break;
			case NetMsg::SendError:
				pText = g_pszNetStat_SendError;
				break;
			case NetMsg::InQReadError:
				pText = g_pszNetStat_InQReadError;
				break;
			case NetMsg::OutQWriteError:
				pText = g_pszNetStat_OutQWriteError;
				break;
			case NetMsg::ConnectionError:
				pText = g_pszNetStat_ConnectionError;
				break;
			case NetMsg::TimeoutError:
				pText = g_pszNetStat_TimeoutError;
				break;
			case NetMsg::ListenError:
				pText = g_pszNetStat_ListenError;
				break;
			case NetMsg::CantConnectError:
				pText = g_pszNetStat_ConnectError;
				break;
			case NetMsg::ConnectTimeoutError:
				pText = g_pszNetStat_ConnectTimeoutError;
				break;
			case NetMsg::ServerVersionMismatchError:
				pText = szStaticErrorText;
				sprintf(pText, g_pszNetStat_ServerVersionMismatchError_lu_lu, pmsg->msg.err.ulParam, CNetMsgr::CurVersionNum & ~CNetMsgr::MacVersionBit);
				break;
			case NetMsg::ClientVersionMismatchError:
				pText = szStaticErrorText;
				sprintf(pText, g_pszNetStat_ClientVersionMismatchError_lu_lu, pmsg->msg.err.ulParam, CNetMsgr::CurVersionNum & ~CNetMsgr::MacVersionBit);
				break;
			case NetMsg::LoginDeniedError:
				pText = g_pszNetStat_LoginDeniedError;
				break;
			case NetMsg::JoinDeniedError:
				pText = g_pszNetStat_JoinDeniedError;
				break;
			case NetMsg::CantOpenPeerSocketError:
				pText = g_pszNetStat_CantOpenPeerSocketError;
				break;
			case NetMsg::ServerPlatformMismatchError:
				pText = g_pszNetStat_ServerPlatformMismatchError;
				break;
			case NetMsg::ClientPlatformMismatchError:
				pText = g_pszNetStat_ClientPlatformMismatchError;
				break;
			default:
				pText = g_pszNetStat_UnknownError;
				break;
			}
		}
	return pText;
	}

//////////////////////////////////////////////////////////////////////////////
//
// Get the realm filename from the realm title, using the INI.
//
//////////////////////////////////////////////////////////////////////////////
static int16_t GetRealmFileFromRealmTitle(	// Returns 0, if found; non-zero
														// otherwise.
	bool	bCoopLevel,								// In:  true, if a coop level; false, if deathmatch level.
	char*	pszRealmTitle,							// In:  Realm title.
	char* pszRealmFileName,						// Out: Realm filename.
	int16_t sMaxLen)									// In:  Max space available at 
														// pszRealmFileName.
	{
	int16_t	sResult	= 0;	// Assume success.

	RPrefs prefsRealm;
	// Try opening the realms.ini file on the HD path first, if that fails go to the CD
	sResult = prefsRealm.Open(FullPathHD(g_GameSettings.m_pszRealmPrefsFile), "rt");
	if (sResult != 0)
		sResult = prefsRealm.Open(FullPathCD(g_GameSettings.m_pszRealmPrefsFile), "rt");
	if (sResult == 0)
		{
		// Try each realm section until we find the title we're looking for
		// or we find an empty entry.
		// Multiplayer sections are named "RealmNet1, "RealmNet2", etc.
		// Multiplayer realm entry is always "Realm".
		// The title is always "Title".
		int16_t	sRealmNum	= 1;
		char	szRealmTitle[512];
		char	szSection[512];
		bool	bFound	= false;
		do
			{
			// Form section name.
			sprintf(
				szSection, 
				"Realm%sNet%d", 
				bCoopLevel ? "Coop" : "", 
				sRealmNum++);

			// Safety; renitialize.
			szRealmTitle[0]	= '\0';

			// Get the title for this net realm.
			prefsRealm.GetVal(szSection, "Title", "", szRealmTitle);

			// If this is the title of the realm we're looking for . . .
			if (rspStricmp(szRealmTitle, pszRealmTitle) == 0)
				{
				// Found it; get filename.
				// Note that there's no real way to use the sMaxLen.
				prefsRealm.GetVal(szSection, "Realm", "", pszRealmFileName);

				// Done.
				bFound	= true;
				}

			} while (szRealmTitle[0] != '\0' && bFound == false);

		// If we didn't find it . . .
		if (bFound == false)
			{
			// Let the caller know.
			sResult	= 1;
			}
		}

	return sResult;
	}

//////////////////////////////////////////////////////////////////////////////
//
// Client has been dropped
//
//////////////////////////////////////////////////////////////////////////////
static void OnDroppedMsg(
	CNetClient*	pnet,			// In:  Network interface.
	NetMsg*		pmsg)			// In:  Dropped msg from client to remove.
	{
	ASSERT(pmsg->msg.nothing.ucType == NetMsg::DROPPED);

	// Print message while player's info is still in our database
	if (pmsg->msg.dropped.id == Net::InvalidID)
		AddConsoleMsg(false, "%s", g_pszClientStat_YouWereDropped);
	else
		AddConsoleMsg(false, g_pszClientStat_SomeoneDropped_s, pnet->GetPlayerName(pmsg->msg.dropped.id));

	// Update number of players displayed.
	RGuiItem*	pguiConnected	= ms_pguiRoot->GetItemFromId(GUI_ID_PLAYERS_STATIC1);
	RSP_SAFE_GUI_REF_VOID(pguiConnected, SetText(g_pszNetDlg_ConnectedPlayers_d, pnet->GetNumPlayers()));
	RSP_SAFE_GUI_REF_VOID(pguiConnected, Compose());
	pguiConnected	= ms_pguiRoot->GetItemFromId(GUI_ID_PLAYERS_STATIC2);
	RSP_SAFE_GUI_REF_VOID(pguiConnected, SetText(g_pszNetDlg_ConnectedPlayers_d, pnet->GetNumPlayers()));
	RSP_SAFE_GUI_REF_VOID(pguiConnected, Compose());

	// Get client's GUI . . .
	RGuiItem* pguiClient = ms_plbPlayers->GetItemFromId( int32_t(pmsg->msg.dropped.id));
	if (pguiClient != NULL)
		{
		// Remove the item.
		ms_plbPlayers->RemoveItem(pguiClient);
		ms_plbPlayers->AdjustContents();
		}
	else
		{
		TRACE("RemoveClient(): We didn't even know of this client!!\n");
		}
	}


//////////////////////////////////////////////////////////////////////////////
//
// Player has joined
//
//////////////////////////////////////////////////////////////////////////////
static int16_t OnJoinedMsg(	// Returns 0 on success.
	CNetClient*	pnet,			// In:  Network interface.
	NetMsg*		pmsg,			// In:  Joined msg from client to add.
	bool			bServer)		// In:  true if in server mode; false if client.
	{
	int16_t	sRes	= 0;	// Assume success.

	ASSERT(pmsg->msg.nothing.ucType == NetMsg::JOINED);
	
	uint8_t	ucColorIndex	= pmsg->msg.joined.ucColor;
	if (ucColorIndex >= CGameSettings::ms_sNumPlayerColorDescriptions)
		ucColorIndex	= 0;

	// Add info to listbox.
	char	szPlayer[256];
	sprintf(szPlayer, "%s   (%s)", pmsg->msg.joined.acName, CGameSettings::ms_apszPlayerColorDescriptions[ucColorIndex]);

	// Update number of players displayed.
	RGuiItem*	pguiConnected	= ms_pguiRoot->GetItemFromId(GUI_ID_PLAYERS_STATIC1);
	RSP_SAFE_GUI_REF_VOID(pguiConnected, SetText(g_pszNetDlg_ConnectedPlayers_d, pnet->GetNumPlayers()));
	RSP_SAFE_GUI_REF_VOID(pguiConnected, Compose() );
	pguiConnected	= ms_pguiRoot->GetItemFromId(GUI_ID_PLAYERS_STATIC2);
	RSP_SAFE_GUI_REF_VOID(pguiConnected, SetText(g_pszNetDlg_ConnectedPlayers_d, pnet->GetNumPlayers()));
	RSP_SAFE_GUI_REF_VOID(pguiConnected, Compose() );

	RGuiItem* pguiClient = ms_plbPlayers->AddString(szPlayer);
	if (pguiClient != NULL)
		{
		// Let's be able to identify this client by its net ID.
		pguiClient->m_lId	= (int32_t)pmsg->msg.joined.id;

		// Don't allow the user to select these in client mode . . .
		if (bServer == false)
			{
			pguiClient->m_sActive	= FALSE;
			pguiClient->SetActive(FALSE);
			}

		// Activate shadow parameters.
		MakeMoreReadable(pguiClient);
		pguiClient->Compose();

		ms_plbPlayers->AdjustContents();
		ms_plbPlayers->EnsureVisible(pguiClient);
		}
	else
		{
		TRACE("OnJoinedMsg(): ms_plbPlayers->AddString() failed.\n");
		sRes = -1;
		}

	return sRes;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Player has changed info
//
//////////////////////////////////////////////////////////////////////////////
static int16_t OnChangedMsg(	// Returns 0 on success.
	CNetClient*	pnet,			// In:  Network interface.
	NetMsg*		pmsg)			// In:  Changed msg
	{
	int16_t	sRes	= 0;	// Assume success.

	ASSERT(pmsg->msg.nothing.ucType == NetMsg::CHANGED);

	TRACE("OnChangedMsg(): Changes are not yet refelected in the gui's!\n");

	return sRes;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Incoming chat message
//
//////////////////////////////////////////////////////////////////////////////
static void OnChatMsg(
	CNetClient*	pnet,				// In:  Network interface.
	NetMsg*		pmsg)				// In:  Chat msg.
	{
	ASSERT(pmsg->msg.nothing.ucType == NetMsg::CHAT);
	AddConsoleMsg(true, "%s", pmsg->msg.chat.acText);
	}


//////////////////////////////////////////////////////////////////////////////
//
// Handles SetupGame message.
//
//////////////////////////////////////////////////////////////////////////////
static void OnSetupGameMsg(
	CNetClient*	pnet,				// In:  Network interface.
	NetMsg*		pmsg)				// In:  Message.
	{
	// Paginate into user displayable single string.
	if (ms_pguiOptions)
		{

		// Check whether this message contains the same realm info as the last such
		// message, if there was one.  In other words, is there new realm info?
		bool bNewRealm = false;
		if (ms_bGotSetupMsg)
			{
			if ((pmsg->msg.setupGame.sRealmNum != ms_sSetupRealmNum) ||
				(rspStricmp(pmsg->msg.setupGame.acRealmFile, ms_szSetupRealmFile) != 0))
				{
				bNewRealm = true;
				}
			}
		else
			{
			bNewRealm = true;
			}

		// If it's new, save it for next time
		if (bNewRealm)
			{
			ms_sSetupRealmNum = pmsg->msg.setupGame.sRealmNum;
			strcpy(ms_szSetupRealmFile, pmsg->msg.setupGame.acRealmFile);
			ms_bGotSetupMsg = true;
			}

		// Determine whether the selected realm is available
		bool bAvailable = false;
		#ifdef ENABLE_PLAY_SPECIFIC_REALMS_ONLY
			// If there's only specific realms available, we simply check for
			// the hardwired values.
			if (pmsg->msg.setupGame.sRealmNum > -1)
				{
				if (pmsg->msg.setupGame.sRealmNum == SPECIFIC_MP_REALM_NUM)
					bAvailable = true;
				}
			else
				{
				if (rspStricmp(pmsg->msg.setupGame.acRealmFile, SPECIFIC_MP_REALM_TEXT) == 0)
					bAvailable = true;
				}
		#else
			// If it's a full version of the game, we still need to see if the specified
			// file is available because the host may be trying to use an add-on realm
			// that wasn't on the original CD.
			if (pmsg->msg.setupGame.sRealmNum > -1)
				{
				// Convert realm number to file name
				char szFile[RSP_MAX_PATH];
				if (Play_GetRealmInfo(
					true,					// Multiplayer
					pmsg->msg.setupGame.sCoopLevels ? true : false,	// Cooperative or Deathmatch levels
					false,				// Not gauntlet
					false,				// Not new single player Add On levels
					pmsg->msg.setupGame.sRealmNum,
					pmsg->msg.setupGame.sDifficulty,
					szFile,
					sizeof(szFile)) == 0)
					{
					// Check if file is available
					if (CRealm::DoesFileExist(szFile))
						bAvailable = true;
					}
				}
			else
				{
				// acRealmFile, due to a bizzarre twist of events, is never a filename
				// but, rather, the title of the realm.  The only way we can get a filename
				// from this title is to scan the NetRealm's in the INI.
				char	szRealmFileName[RSP_MAX_PATH];
				if (GetRealmFileFromRealmTitle(
					pmsg->msg.setupGame.sCoopLevels ? true : false,	// Cooperative or Deathmatch levels
					pmsg->msg.setupGame.acRealmFile,
					szRealmFileName,
					sizeof(szRealmFileName) ) == 0)
					{
					// Check if file is available
					if (CRealm::DoesFileExist(szRealmFileName))
						bAvailable = true;
					}
				}
		#endif

		// If level is available, display info about it.  Otherwise, say it isn't available!
		if (bAvailable)
			{
			char	szCoop[256] = "";
			if (pmsg->msg.setupGame.sCoopLevels != 0)
				{
				strcpy(szCoop, "Cooperative ");
				}

			char	szRealm[256];
			if (pmsg->msg.setupGame.sRealmNum > -1)
				{
				// Use number.
				sprintf(szRealm, "Level %hd", pmsg->msg.setupGame.sRealmNum);
				}
			else
				{
				// Use string.
				sprintf(szRealm, "\"%s\"", pmsg->msg.setupGame.acRealmFile);
				}

			char	szPlayMode[256];
			if (pmsg->msg.setupGame.sCoopMode)
				{
				strcpy(szPlayMode, "Cooperative");
				}
			else
				{
				strcpy(szPlayMode, "Deathmatch");
				}

			char	szTimeLimit[256];
			if (pmsg->msg.setupGame.sTimeLimit > 0)
				{
				sprintf(szTimeLimit, "a time limit of %hd", pmsg->msg.setupGame.sTimeLimit);
				}
			else
				{
				sprintf(szTimeLimit, "no time limit");
				}

			char	szKillLimit[256];
			if (pmsg->msg.setupGame.sKillLimit > 0)
				{
				sprintf(szKillLimit, "a kill limit of %hd", pmsg->msg.setupGame.sKillLimit);
				}
			else
				{
				sprintf(szKillLimit, "no kill limit");
				}

			ms_pguiOptions->SetText(
				"Host has selected %s%s in %s mode on difficulty %hd with %s and %s.",
				szCoop,
				szRealm,
				szPlayMode,
				pmsg->msg.setupGame.sDifficulty,
				szTimeLimit,
				szKillLimit);
			}
		else
			{
			// Tell the local user that the selected level is not available
			ms_pguiOptions->SetText("Host has selected a level you don't have!");

			// Send a text message to all players (we'd like to send it to just the host,
			// but we don't support that, and maybe it's nice that the other players see
			// it, too).  The message complains that the selected level is not available.
			// Note that we only send this when the realm info has changed, so as to avoid
			// sending an endless stream of the same messages over and over.
			if (bNewRealm)
				{
				char szTmp[1024];
				#ifdef ENABLE_PLAY_SPECIFIC_REALMS_ONLY
					sprintf(szTmp, "%s\"%s\" only has the \""SPECIFIC_MP_REALM_TEXT"\" hood -- please pick it!",
						g_pszNetStatusMsgPrefix,
						pnet->GetPlayerName(pnet->GetID()));
					pnet->SendText(szTmp);
				#else
					sprintf(szTmp, "%s\"%s\" does not have the selected hood -- please pick another one!",
						g_pszNetStatusMsgPrefix,
						pnet->GetPlayerName(pnet->GetID()));
					pnet->SendText(szTmp);
				#endif
				}
			}

		// Compose options GUI with word wrap preserving original word wrap status.
		ComposeOptions();
		}
	}


//////////////////////////////////////////////////////////////////////////////
//
// Explain the fact that the procol the user chose is not supported
//
//////////////////////////////////////////////////////////////////////////////
void ProtoNotSupported(void)
	{
	// Check if there's only one protocol or more than one
	if (RSocket::FirstProtocol + 1 == RSocket::NumProtocols)
		{
		// Only one protocol
		rspMsgBox(
			RSP_MB_BUT_OK | RSP_MB_ICN_INFO,
			g_pszAppName,
			g_pszNetOnlyProtocolUnsupported_s,
			RSocket::GetProtoName());
		}
	else
		{
		// More than one protocol
		rspMsgBox(
			RSP_MB_BUT_OK | RSP_MB_ICN_INFO,
			g_pszAppName,
			g_pszNetProtocolUnsupported_s,
			RSocket::GetProtoName());
		}
	}


//////////////////////////////////////////////////////////////////////////////
//
// Do network game dialog
//
//////////////////////////////////////////////////////////////////////////////
extern int16_t DoNetGameDialog(							// Returns 0 if successfull, non-zero otherwise.
	CNetClient*	pclient,									// I/O: Client interface
	bool bBrowse,											// In:  Whether to browse (true) or connect (false)
	CNetServer*	pserver,									// I/O: Server interface or NULL if not server
	NetMsg* pmsgOut)										// Out: NetMsg::NOTHING or NetMsg::START_GAME
	{
	ASSERT(pclient != NULL);

	int16_t	sResult = 0;									// Assume success.

	// Under Win95 with DirectX, certain problems have come up due to a
	// combination of our hogging the CPU and DirectX adding to that hogging,
	// and us taking over the screen via DirectX, all of which is a problem
	// when the dialup-networking dialog tries to display itself.  In an
	// attempt to alleviate some of this, we go to a lower-level of CPU hogging
	// during the network dialogs, and restore the level afterwards.
	rspSetDoSystemMode(RSP_DOSYSTEM_TOLERATEOS);

	// Init globals
	ms_pguiRoot			= NULL;
	ms_pguiOk			= NULL;
	ms_pguiCancel		= NULL;
	ms_plbPlayers		= NULL;
	ms_plbNetConsole	= NULL;
	ms_pguiChatText	= NULL;
	ms_pguiChatSend	= NULL;
	ms_plbLevelBrowse	= NULL;
	ms_pmbCoopLevels	= NULL;
	ms_pmbCoopMode		= NULL;
	ms_pguiRetry		= NULL;
	ms_lWatchdogTime	= 0;
	ms_bNetBlockingAbort = false;

	// We haven't received a setup msg yet
	ms_bGotSetupMsg = false;

	ClearNetProb();

	// Make sure vars with built in flagging get reflected properly.


	// No time limit is flagged as 0 or negative
	if (g_GameSettings.m_sHostTimeLimit > 0)
		{
		ms_bTimeLimit	= true;
		}
	else
		{
		ms_bTimeLimit	= false;
		g_GameSettings.m_sHostTimeLimit	= -g_GameSettings.m_sHostTimeLimit;
		}
	
	// No kill limit is flagged as 0 or negative
	if (g_GameSettings.m_sHostKillLimit > 0)
		{
		ms_bKillLimit	= true;
		}
	else
		{
		ms_bKillLimit	= false;
		g_GameSettings.m_sHostKillLimit	= -g_GameSettings.m_sHostKillLimit;
		}

	// Save current mouse cursor level and then force it to be visible
	int16_t sCursorLevel = rspGetMouseCursorShowLevel();
	rspSetMouseCursorShowLevel(1);

	// Clear any events that might be in the queue
	rspClearAllInputEvents();

	// *************************** TEMP
//	bBrowse	= true;
	// *************************** TEMP

	// If we're browsing, this loop continues until the user aborts or starts.
	// If we're not browsing, this loop only goes through once.
	bool bAbort = false;
	bool bStart = false;
	do	{
		// Call this periodically to let it know we're not locked up
		NetBlockingWatchdog();

		// Default to returning a NetMsg::NOTHING
		pmsgOut->msg.nothing.ucType = NetMsg::NOTHING;

		// If there's a server, start it up
		if (pserver)
			sResult = pserver->Startup(g_GameSettings.m_usServerPort, g_GameSettings.m_szHostName,	&NetBlockingCallback);
		if (sResult == 0)
			{

			// Host address
			RSocket::Address addressHost;

			// If we're browsing, do it before the client dialog since it uses a dialog of its own
			if (bBrowse)
				sResult = BrowseForHost(pserver, &addressHost);
			if (sResult == 0)
				{

				// Setup dialog in client or server mode, as appropriate
				sResult	= SetupDlg(pserver ? FullPathHD(SERVER_GUI) : FullPathVD(CLIENT_GUI), pserver ? DLG_SERVER : DLG_CLIENT);
				if (sResult == 0)
					{
					// Display "startup" messages
					if (pserver)
						AddConsoleMsg(false, "%s", g_pszServerStat_Startup);
					else
						AddConsoleMsg(false, g_pszClientStat_Startup);

					// Update the dialog so it shows up on the screen.  We ignore the
					// return since we aren't ready to deal with it here.  This seems
					// okay since the dialog has just shown up, so nobody (except Jeff)
					// could possibly hit a key or mouse button on the first frame.
					UpdateDialog(ms_pguiRoot, true);

					// If we didn't browse for a host, we still need to find one
					if (!bBrowse)
						{
						if (pserver)
							{
							// Try to find the local server
							sResult = BrowseForSelf(pserver, &addressHost);
							}
						else
							{
							// The local client tries to find a remote server
							sResult = FindSpecificSystem(&addressHost);
							}
						}
					if (sResult == 0)
						{

						// This loop is used for when the user hits the "RETRY" button on the client dialog
						bool bRetry = false;
						do {
							// Clear retry flag each time so we don't accidentally get caught in a loop
							bRetry = false;

							// Startup client
							pclient->Startup(&NetBlockingCallback);

							// Start the (asynchronous) process of joining the specified host.  We
							// specifically check for the "protocol not supported" error and handle
							// that as a special case, because users are likely to screw that up.
							// Any other errors will be discovered via our normal GetMsg() loop.
							sResult = pclient->StartJoinProcess(
								&addressHost,
								g_GameSettings.m_szPlayerName,
								g_GameSettings.m_sPlayerColorIndex,
								0,
								g_GameSettings.m_sNetBandwidth);
							if (sResult != RSocket::errNotSupported)
								{

								//------------------------------------------------------------------------------
								// This may appear to be a rather bizarre loop, and maybe it is, but it seemed
								// like a really good idea at the time...
								//
								// It handles three primary tasks.  First, if this machine is a server, it does
								// all the server stuff.  Then, it does the client stuff (remember that a server
								// is always a client, but a client is not necessarily a server).  Finally, it
								// does the dialog and user-input stuff, which again is slightly different
								// depending on whether it's a client or a server.
								//
								// The alternative approach was to have separate functions to handle the client
								// and server ends.  It was originally that way, but there was so much
								// similarity between the two that it seemed better to merge them, thereby
								// avoiding having to maintain two very similar sets of code.
								//
								// A key point about this loop is that you should NEVER use a 'break' to get
								// out of the loop.  In fact, you should rarely exit the loop in any kind of
								// direct manner.  Instead, you should always try to wait until the client
								// and server (if any) have been allowed to "gracefully" finish whatever it
								// is they need to get done.
								//
								// Note that if the user clicks the "ABORT" button in the dialog, we don't
								// immediately end the loop, either.  We simply set the flags and hope the
								// loop will end itself soon enough.  If, after a certain amount of time, the
								// loop hasn't ended, the user can click "ABORT" again to end, and this time
								// we end immediately.  At some point, this should perhaps be replaced by a
								// timer which automatically ends the loop after a certain amount of time.
								//------------------------------------------------------------------------------
								bool bEndClientCleanly = false;
								bool bEndServerCleanly = false;
								bool bServerDone = pserver ? false : true;
								bool bClientDone = false;
								bool bUserAbortNow = false;
								int32_t lCancelDelay;
								DLG_ACTION action;
								NetMsg msg;
								while (!(bClientDone && bServerDone && (bAbort || bStart || bRetry)) && !bUserAbortNow)
 									{
									// //It overrdies the rendering of the menu (sdl2) :(
									//UpdateSystem();

									// Call this periodically to let it know we're not locked up
									NetBlockingWatchdog();
									
									//------------------------------------------------------------------------------
									// Do dialog and any other user-input stuff
									//------------------------------------------------------------------------------

									// Update GUI
									action = UpdateDialog(ms_pguiRoot, true);

									// If user wants to quit, simulate a cancel.  Note that this is NOT an event
									// but a flag, so once it starts, we'll continue to get CANCEL actions each
									// time we get to this point.  This is exactly what we want, since this type
									// of quit indicates that the user doesn't want to wait around to quit.
									if (rspGetQuitStatus() || NetBlockingWasAborted())
										action = DLG_CANCEL;

									// Handle action
									switch (action)
										{
										// Nothing to do
										case DLG_NOTHING:
											break;

										// OK was pressed.  This only exists on server dialog!  Note that we don't
										// allow OK to be used if either it or Cancel were already used.
										case DLG_OK:
											// Must be server. . .
											if (pserver)
												{
												// Make sure neither OK nor Cancel were pressed, and that we have at least 1 client
												if (!bStart && !bAbort && pserver->GetNumberOfClients())
													{
													// Download GUI vals.
													DownloadLinks(ms_aglServerLinkage, ms_pguiRoot);

													// Feedback
													PlaySample(g_smidMenuItemSelect, SampleMaster::UserFeedBack);
													AddConsoleMsg(false, "%s", g_pszNetStat_Starting);

													// Get pointer to game selection GUI
													RGuiItem* pguiSel = RSP_SAFE_GUI_REF(ms_plbLevelBrowse, GetSel());

													// Start game using specified settings
													pserver->StartGame(
														pclient->GetID(),
														#ifdef ENABLE_PLAY_SPECIFIC_REALMS_ONLY
															-1,
															SPECIFIC_MP_REALM_FILE,
														#else
															RSP_SAFE_GUI_REF(pguiSel, m_lId),
															"",
														#endif
														g_GameSettings.m_sDifficulty,
														g_GameSettings.m_sHostRejuvenate,
														ms_bTimeLimit ? g_GameSettings.m_sHostTimeLimit : -g_GameSettings.m_sHostTimeLimit,
														ms_bKillLimit ? g_GameSettings.m_sHostKillLimit : -g_GameSettings.m_sHostKillLimit,
														ms_bCoopLevels ? 1 : 0,
														ms_bCoopMode ? 1 : 0,
														g_GameSettings.m_sNetTimePerFrame,
														g_GameSettings.m_sNetMaxFrameLag);

													// End server cleanly (client will end when it gets start message)
													bEndServerCleanly = true;
													}
												}
											break;

										// Cancel was pressed.  Note that in server mode, we allow cancel to be
										// pressed even after OK was pressed.  We merely send another message
										// to the clients saying to abort the game that was already started.
										case DLG_CANCEL:
											// If cancel was already pressed, we ignore additional cancel's until
											// the timer has expired, at which point they can hit cancel again.
											// The idea is to give the cancel process time to finish cleanly.
											if (bAbort)
												{
												if ((rspGetMilliseconds() - lCancelDelay) > CANCEL_DELAY_TIME)
													{
													// Feedback sound
													PlaySample(g_smidMenuItemSelect, SampleMaster::UserFeedBack);

													// User has aborted, exit immediately
													bUserAbortNow = true;
													}
												}
											else
												{
												// Pressed cancel, so set flag and init delay timer
												bAbort = true;
												lCancelDelay = rspGetMilliseconds();

												// Feedback
												AddConsoleMsg(false, "%s", g_pszNetStat_Aborting);
												PlaySample(g_smidMenuItemSelect, SampleMaster::UserFeedBack);

												if (pserver)
													{
													// Download GUI vals anyways for consistency.
													DownloadLinks(ms_aglServerLinkage, ms_pguiRoot);

													// Tell players to abort game
													pserver->AbortGame(NetMsg::UserAbortedGame);
													}
												else
													{
													// Drop out of game
													pclient->Drop();

													// Start with a clean slate (no RETRY button because user selected ABORT)
													CleanClientDlg(pclient, false);
													}

												// End server and client cleanly
												bEndServerCleanly = true;
												bEndClientCleanly = true;
												}
											break;

										// Chat was pressed.  We don't allow this if OK or Cancel were pressed.
										case DLG_CHAT:
											// Make sure neither Ok nor Cancel were pressed
											if (!bStart && !bAbort)
												{
												// Make sure text field exists
												if (ms_pguiChatText != NULL)
													{
													// See if there's any text
													if (ms_pguiChatText->m_szText[0] != '\0')
														{
														// Sent chat
														pclient->SendChat(ms_pguiChatText->m_szText);

														// Clear text
														ms_pguiChatText->SetText("");
														ms_pguiChatText->Compose();
														}
													}
												}
											break;

										// Disconnect player was pressed.  We don't allow this if OK or Cancel were pressed.
										case DLG_DISCONNECT_PLAYER:
											// Make sure neither Ok nor Cancel were pressed
											if (!bStart && !bAbort)
												{
												// If there's a selection . . .
												RGuiItem*	pguiPlayerSel	= ms_plbPlayers->GetSel();
												if (pguiPlayerSel)
													{
													Net::ID id = (uint8_t)pguiPlayerSel->m_lId;
													// Don't be a moron -- don't drop yourself
													if (id == pclient->GetID())
														{
														// Tell user he can't drop himself
														AddConsoleMsg(false, "%s", g_pszServerStat_CantDropSelf);
														}
													else
														{
														// Drop player (must get his name BEFORE he is dropped!)
														AddConsoleMsg(false, g_pszNetStat_AttemptToDrop_s, pserver->GetPlayerName(id));
														pserver->DropClient(id);
														}
													}
												}
											break;

										// Send an options update.  We don't allow this if OK or Cancel were pressed.
										case DLG_OPTIONS_UPDATED:
											if (pserver && !bStart && !bAbort)
												{
												// Get current settings into their variables.
												DownloadLinks(ms_aglServerLinkage, ms_pguiRoot);

												// Get pointer to game selection GUI
												RGuiItem* pguiSel = RSP_SAFE_GUI_REF(ms_plbLevelBrowse, GetSel());

												// Setup game
												pserver->SetupGame(
													#ifdef ENABLE_PLAY_SPECIFIC_REALMS_ONLY
														-1,
														SPECIFIC_MP_REALM_TEXT,
													#else
														pguiSel ? -1                : 0,
														pguiSel ? pguiSel->m_szText : "",
													#endif
													g_GameSettings.m_sDifficulty,
													g_GameSettings.m_sHostRejuvenate,
													ms_bTimeLimit ? g_GameSettings.m_sHostTimeLimit : -g_GameSettings.m_sHostTimeLimit,
													ms_bKillLimit ? g_GameSettings.m_sHostKillLimit : -g_GameSettings.m_sHostKillLimit,
													ms_bCoopLevels ? 1 : 0,
													ms_bCoopMode ? 1 : 0);

												}
											break;

										case DLG_RETRY:
											if (!bStart && !bAbort)
												{
												// Clean the slate (without RETRY since they just hit it and may not need it again)
												CleanClientDlg(pclient, false);

												// Feedback
												PlaySample(g_smidMenuItemSelect, SampleMaster::UserFeedBack);
												AddConsoleMsg(false, "%s", g_pszClientStat_Retrying);
												AddConsoleMsg(false, g_pszClientStat_Startup);

												// End server and client cleanly
												bEndServerCleanly = true;
												bEndClientCleanly = true;

												// Set retry flag
												bRetry = true;
												}
											break;

										default:
											TRACE("DoNetGameDialog(): Unknown dialog action!\n");
											break;
										}

									//------------------------------------------------------------------------------
									// Do server stuff.
									//
									// Note that bServerDone should rarely be set to true directly.  Instead, set
									// bEndServerCleanly to true, which will try to end the server cleanly, and will
									// eventually result in bServerDone being set to true.
									//
									// It's okay to ignore incoming messages when trying to end because they will
									// still be received and buffered, they just won't be processed here.  Instead,
									// they'll be processed in the game loop.  Of course, if the game never actually
									// gets started they won't ever be processed, but then it doesn't matter.
									//------------------------------------------------------------------------------

									if (pserver && !bServerDone)
										{
										pserver->Update();

										// Check if we're trying to end
										if (bEndServerCleanly)
											{
											// If there isn't anything more to send, then we're done
											if (!pserver->IsMoreToSend())
												bServerDone = true;
											}
										else
											{
											// Process messages
											pserver->GetMsg(&msg);
											switch(msg.msg.nothing.ucType)
												{
												case NetMsg::ERR:
													if (msg.ucSenderID == Net::InvalidID)
														{
														// A server occurred occurred
														AddConsoleMsg(false, NetErrorText(&msg));

														// Play a sound of badness
														PlaySample(g_smidEmptyWeapon, SampleMaster::UserFeedBack);

														switch (msg.msg.nothing.ucType)
															{
															// These messages are NOT so horrible and don't
															// require us to clean up and be done.
															// They are merely notifications.
															case NetMsg::ServerVersionMismatchError:
															case NetMsg::ServerPlatformMismatchError:
																break;
															
															// These messages are so horrible and don't
															// require us to clean up and be done.
															default:
																// End server and client cleanly
																bEndServerCleanly = true;
																bEndClientCleanly = true;
																break;
															}
														}
													else if (msg.ucSenderID == pclient->GetID())
														{
														// The error occurred on the local client.  We registered the
														// local client with the server, so it will have aborted the game.
														AddConsoleMsg(false, NetErrorText(&msg));

														// Play a sound of badness
														PlaySample(g_smidEmptyWeapon, SampleMaster::UserFeedBack);

														// End server and client cleanly
														bEndServerCleanly = true;
														bEndClientCleanly = true;
														}
													else
														{
														// The error occurred on a remote client, so the server will
														// have dropped that client.
														AddConsoleMsg(false, g_pszServerStat_PlayerErr);
														}
													break;

												default:
													break;
												}
											}
										}

									//------------------------------------------------------------------------------
									// Do client stuff
									//
									// Note that bClientDone should rarely be set to true directly.  Instead, set
									// bEndClientCleanly to true, which will try to end the client cleanly, and will
									// eventually result in bClientDone being set to true.
									//------------------------------------------------------------------------------

									if (!bClientDone)
										{
										pclient->Update();

										// Check if we're trying to end
										if (bEndClientCleanly)
											{
											// If there isn't anything more to send, then we're done
											if (!pclient->IsMoreToSend())
												bClientDone = true;
											}
										else
											{
											// Assume no problems
											int16_t sProblem = 0;

											// Process messages from server
											pclient->GetMsg(&msg);
											switch(msg.msg.nothing.ucType)
												{
												case NetMsg::NOTHING:
													break;

												case NetMsg::ERR:
													AddConsoleMsg(false, NetErrorText(&msg));

													// Attempt to drop nicely
													pclient->Drop();

													// End server and client cleanly
													bEndServerCleanly = true;
													bEndClientCleanly = true;

													// Play a sound of badness and clean the slate (and show RETRY button)
													PlaySample(g_smidEmptyWeapon, SampleMaster::UserFeedBack);
													CleanClientDlg(pclient, true);
													break;

												case NetMsg::STAT:
													switch (msg.msg.stat.status)
														{
														case NetMsg::Opened:
															AddConsoleMsg(false, "%s", g_pszClientStat_Opened);
															break;

														case NetMsg::Connected:
															AddConsoleMsg(false, "%s", g_pszClientStat_Connected);
															break;

														case NetMsg::LoginAccepted:
															// If we are the server's local client, register ourself so
															// that it realizes that if there's an error on our connection,
															// it will abort the whole game.
															if (pserver)
																pserver->SetLocalClientID(pclient->GetID());
															AddConsoleMsg(false, g_pszClientStat_LoginAccepted_hd, (int16_t)pclient->GetID());
															break;

														case NetMsg::JoinAccepted:
															AddConsoleMsg(false, "%s", g_pszClientStat_JoinAccepted);
															break;

														default:
															break;
														}
													break;

												case NetMsg::JOINED:
													if (OnJoinedMsg(pclient, &msg, pserver ? true : false) != 0)
														{
														// A program error occurred, so tell them something vague
														AddConsoleMsg(false, g_pszNetStat_ProgramError);

														// Attempt to drop nicely
														pclient->Drop();

														// End server and client cleanly
														bEndServerCleanly = true;
														bEndClientCleanly = true;

														// Play a sound of badness and clean the slate (and show RETRY button)
														PlaySample(g_smidEmptyWeapon, SampleMaster::UserFeedBack);
														CleanClientDlg(pclient, true);
														}
													break;
												
												case NetMsg::DROPPED:
													OnDroppedMsg(pclient, &msg);
													// If we were dropped, end immediately
													if (msg.msg.dropped.id == Net::InvalidID)
														{
														// Play a sound of badness and clean the slate  (and show RETRY button)
														PlaySample(g_smidEmptyWeapon, SampleMaster::UserFeedBack);
														CleanClientDlg(pclient, true);

														bClientDone = true;
														}
													break;

												case NetMsg::CHAT:
													OnChatMsg(pclient, &msg);
													break;

												case NetMsg::SETUP_GAME:
													OnSetupGameMsg(pclient, &msg);
													break;

												case NetMsg::START_GAME:
													// Return this message to caller
													*pmsgOut = msg;

													// Game has been started
													bStart = true;

													// End immediately (no need to wait)
													bClientDone = true;
													break;

												case NetMsg::ABORT_GAME:
													AddConsoleMsg(false, "%s", g_pszClientStat_ServerAborted);

													// Play a sound of badness and clean the slate (and show RETRY button)
													PlaySample(g_smidEmptyWeapon, SampleMaster::UserFeedBack);
													CleanClientDlg(pclient, true);

													// End immediately (no need to wait)
													bClientDone = true;
													break;

												default:
													AddConsoleMsg(false, "%s", g_pszNetStat_UnhandledMsg);
													break;
												}
											}
										}

									} // while()
								}
							else
								{
								// Display msg box that says the protocol is not supported
								ProtoNotSupported();
								}

							// If we're not starting, shutdown client
							if (!bStart)
								pclient->Shutdown();

							} while (bRetry && !sResult);
						}

					// Get rid of dialog
					DlgBeGone();

					// Call this periodically to let it know we're not locked up
					NetBlockingWatchdog();
					}
				else
					{
					TRACE("DoNetGameDialog(): Failed to setup dialog.\n");
					}
				}

			// If not starting, shutdown server
			if (!bStart && pserver)
				pserver->Shutdown();
			}
		else
			{
			// Handle the "protocol not supported" error as a special case because users
			// are likely to screw that up.
			if (sResult == RSocket::errNotSupported)
				{
				// Display msg box that says the protocol is not supported
				ProtoNotSupported();
				}
			}

		} while (!sResult && (bBrowse && !bAbort && !bStart));

	// Call this one last time on the way out
	NetBlockingWatchdog();

	// Make sure vars with built in flagging get reflected properly.
	if (ms_bTimeLimit == false)
		{
		// Flag no time limit as a negative or zero.
		g_GameSettings.m_sHostTimeLimit	= -g_GameSettings.m_sHostTimeLimit;
		}
	
	if (ms_bKillLimit == false)
		{
		// Flag no kill limit as a negative or zero.
		g_GameSettings.m_sHostKillLimit	= -g_GameSettings.m_sHostKillLimit;
		}

	// Clear any events that might be in the queue
	rspClearAllInputEvents();

	// Restore mouse cursor show level
	rspSetMouseCursorShowLevel(sCursorLevel);


	// Go back to normal CPU mode
	#if defined(_DEBUG)
		// Wake CPU.
		rspSetDoSystemMode(RSP_DOSYSTEM_TOLERATEOS);
	#else
		// Return CPU to us.
		rspSetDoSystemMode(RSP_DOSYSTEM_HOGCPU);
	#endif

	return sResult;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Browse for a host.
//
// This is normally only used in client-only mode, but it is easier to test
// and debug if we can also use it in client-server mode.  That's why this
// takes a pserver pointer.
//
//////////////////////////////////////////////////////////////////////////////
static int16_t BrowseForHost(
	CNetServer*	pserver,									// I/O: Server interface or NULL if none
	RSocket::Address* paddress)						// Out: Address returned here (if successfull)
	{
	int16_t sResult = 0;

	// Start with empty list of hosts
	CNetBrowse::Hosts hostsAll;
	CNetBrowse::Hosts hostsAdded;
	CNetBrowse::Hosts hostsDropped;

	NetBlockingWatchdog();

	// Create browser and start it up
	CNetBrowse browse;
	sResult = browse.Startup(g_GameSettings.m_usServerPort, &NetBlockingCallback);
	if (sResult == 0)
		{
		sResult = SetupDlg(FullPathVD(BROWSER_GUI), DLG_BROWSER);
		if (sResult == 0)
			{
			// Since we don't let RProcessGUI draw cleaned up the screen, we should.
			rspUpdateDisplay();

			DLG_ACTION action	= DLG_NOTHING;
			// Loop until error, user abort, or user choice . . .
			while ((sResult == 0) && action != DLG_OK && action != DLG_CANCEL)
				{
				//It overrdies the rendering of the menu (sdl2) :(
				//UpdateSystem();
				// Update watchdog timer for net blocking.
				NetBlockingWatchdog();
				// Update server interface, if available.
				if (pserver)
					pserver->Update();

				// Check for new or lost host games.
				browse.Update(&hostsAll, &hostsAdded, &hostsDropped);

				// Update listbox via added and dropped hosts lists.
				sResult = UpdateListBox(ms_plbHostBrowse, &hostsAll, &hostsAdded, &hostsDropped);
				if (sResult == 0)
					{
					// Update the dialog (user input and GUI output).
					action	= UpdateDialog(ms_pguiRoot, true);
					}

				// If quitting . . .
				if (rspGetQuitStatus() != FALSE)
					sResult = 1;
				}

			// If no error . . .
			if (sResult == 0)
				{
				switch (action)
					{
					case DLG_OK:
						{
						// Play feedback sound
						PlaySample(g_smidMenuItemSelect, SampleMaster::UserFeedBack);

						// Get selection . . .
						RGuiItem*	pguiSel	= ms_plbHostBrowse->GetSel();
						// If there's no selection . . .
						if (pguiSel == NULL)
							{
							// Take the first.
							pguiSel	= ms_plbHostBrowse->GetFirst();
							}

						// If tehre's a selection . . .
						if (pguiSel)
							{
							// Get corresponding host.
							CNetBrowse::CHost* phost = (CNetBrowse::CHost*)(pguiSel->m_ulUserData);
							ASSERT(phost);
							// Get host address.
							*paddress = phost->m_address;
							// Success.
							}
						else
							{
							TRACE("BrowseForHost():  No host selected.\n");
							sResult	= -1;
							}
						break;
						}

					case DLG_CANCEL:
						// Play feedback sound
						PlaySample(g_smidMenuItemSelect, SampleMaster::UserFeedBack);

						// Cancelled.
						sResult	= 1;
						break;

					default:
						TRACE("BrowseForHost(): Unknown action.\n");
						sResult	= 1;
						break;
					}
				}

			// Done with dialog.
			DlgBeGone();
			}

		// Stop browsing
		NetBlockingWatchdog();
		browse.Shutdown();
		}
	else
		{
		// Handle the "protocol not supported" error as a special case because users
		// are likely to screw that up.
		if (sResult == RSocket::errNotSupported)
			{
			// Display msg box that says the protocol is not supported
			ProtoNotSupported();
			}
		}

	return sResult;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Try to connect to specified host
//
//////////////////////////////////////////////////////////////////////////////
static int16_t FindSpecificSystem(
	RSocket::Address* paddress)						// Out: Address returned here (if successfull)
	{
	int16_t sResult = 0;

	// Lookup the specified host (by name or dotted address) and port
	sResult = CNetBrowse::LookupHost(
		g_GameSettings.m_szServerName,
		g_GameSettings.m_usServerPort, 
		paddress);
	if (sResult == 0)
		{
		// Success!
		}
	else
		{
		rspMsgBox(
			RSP_MB_BUT_OK | RSP_MB_ICN_INFO,
			g_pszAppName,
			"The specified computer ('%s') could not be found.  Please verify that the specified name or address is correct.",
			g_GameSettings.m_szServerName);
		}

	return sResult;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Try to find the local server.  This is necessary because there isn't any
// foolproof method by which to simply lookup the local computer's address.
// Instead, we browse for ourselves, just like any other client would.
//
//////////////////////////////////////////////////////////////////////////////
static int16_t BrowseForSelf(
	CNetServer*	pserver,									// I/O: Server interface
	RSocket::Address* paddress)						// Out: Address returned here (if successfull)
	{
	ASSERT(pserver);

	int16_t sResult = 0;

	// Start with empty list of hosts
	CNetBrowse::Hosts hostsAll;
	CNetBrowse::Hosts hostsAdded;
	CNetBrowse::Hosts hostsDropped;

	NetBlockingWatchdog();

	// Create browser and start it up
	bool bFoundSelf = false;
	CNetBrowse browse;
	sResult = browse.Startup(g_GameSettings.m_usServerPort, &NetBlockingCallback);
	if (sResult == 0)
		{
		// Wait for our own broadcast  
		int32_t lTime = rspGetMilliseconds() + Net::BroadcastDropTime;
		while (!bFoundSelf && (rspGetMilliseconds() < lTime))
			{
			UpdateSystem();
			NetBlockingWatchdog();
			pserver->Update();
			browse.Update(&hostsAll, &hostsAdded, &hostsDropped);

			// Try to find ourself in the list
			for (CNetBrowse::Hosts::Pointer p = hostsAll.GetHead(); p; p = hostsAll.GetNext(p))
				{
				CNetBrowse::CHost* phost;
				phost = &hostsAll.GetData(p);
				if ((strcmp(phost->m_acName, pserver->GetHostName()) == 0) && (phost->m_lMagic == pserver->GetHostMagic()))
					{
					// Return this host's address
					*paddress = phost->m_address;
					bFoundSelf = true;
					break;
					}
				}
			}

		// If we didn't find ourself, set the error flag
		if (!bFoundSelf)
			{
			sResult = -1;
			TRACE("BrowseForSelf(): Couldn't find myself!\n");
			}

		// Stop browsing
		NetBlockingWatchdog();
		browse.Shutdown();
		}


	// If this failed, put up a msgbox
	if (sResult != 0)
		{
		rspMsgBox(
			RSP_MB_BUT_OK | RSP_MB_ICN_INFO,
			g_pszAppName,
			"This computer's network address could not be determined.  If this is a multi-homed host, you may need to disable all but one address.");
		}

	return sResult;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Net blocking watchdog.  Call this periodically to let the watchdog know
// that the program hasn't locked up.
//
//////////////////////////////////////////////////////////////////////////////
extern void NetBlockingWatchdog(void)
	{
	// Reset timer to current time
	ms_lWatchdogTime = rspGetMilliseconds();
	
	// If net blocking had expired, then clear it so the net prob gui goes
	// away (since we got here, we're obviously not blocking anymore)
	if (m_bNetWatchdogExpired)
		{
		// Clear flag
		m_bNetWatchdogExpired = false;

		// Erase net prob gui
		RGuiItem* ptxt	= GetNetProbGUI();
		if (ptxt)
			{
			// This will PROBABLY work, but it does assume that something else
			// was drawn to the buffer after the last time we drew the net gui.
			// If nothing was drawn to the buffer, the gui will still be there!
			rspUpdateDisplay(ptxt->m_sX, ptxt->m_sY, ptxt->m_im.m_sWidth, ptxt->m_im.m_sHeight);
			}
		}
	}


//////////////////////////////////////////////////////////////////////////////
//
// Check if a blocked network operation was aborted.
//
//////////////////////////////////////////////////////////////////////////////
extern bool NetBlockingWasAborted(void)
	{
	return ms_bNetBlockingAbort;
	}


//////////////////////////////////////////////////////////////////////////////
//
// Net blocking callback
//
//////////////////////////////////////////////////////////////////////////////
static int16_t NetBlockingCallback(void)				// Returns 0 to continue normally, 1 to abort
	{
	// We only need to grab this ptr once (it is guaranteed not to move).
	// Once we have this pointer to the Key status array, we can use it to
	// check on a key's status.  The important thing would be NOT to clear
	// any key's status so we don't affect the input module (input.cpp) or
	// the play loop (play.cpp:PlayRealm()).
	static U8*	pau8KeyStatus	= rspGetKeyStatusArray();

	// Assume we won't abort
	int16_t	sAbort = 0;

	// It's always a good idea to do this
	UpdateSystem();

	// System-specific quit always aborts immediately
	if (rspGetQuitStatus())
		sAbort = 1;

	// If the watchdog hasn't already expired, then check it.  If it has
	// already expired, then we need to see if the user hit the abort key.
	if (!m_bNetWatchdogExpired)
		{
		// If the watchdog function hasn't been called in a too-long time, then we
		// assume the network stuff is blocking (although it could be that someone
		// forgot to call the watchdog function) and we display the net problem gui.
		if ((rspGetMilliseconds() - ms_lWatchdogTime) > g_GameSettings.m_lNetMaxBlockingTime)
			{
			// Set flag to indicate that there is a problem.  This servers two
			// purposes: (1) it let's us know that the net prob gui is being
			// displayed and we should check for the abort key, and (2) it let's
			// other parts of the program determine whether or not to draw the
			// net prob gui on top of whatever else is being drawn to the screen.
			m_bNetWatchdogExpired	= true;
			}
		}

	// If watchdog is expired, draw the net prob gui and check for an abort key press
	if (m_bNetWatchdogExpired)
		{
		// Display net problem gui
		RGuiItem* ptxt	= GetNetProbGUI();
		if (ptxt)
			{
			// Set to display general error and abort instructions
			ptxt->SetText("%s", g_pszNetProb_General);
			ptxt->Compose();
			
			// Center it so it gets erased by whatever menu or dialog is being displayed
			ptxt->Move(
				(g_pimScreenBuf->m_sWidth / 2) - (ptxt->m_im.m_sWidth / 2),
				(g_pimScreenBuf->m_sHeight / 2) - (ptxt->m_im.m_sHeight / 2));

			// Create temporary image of what's currently in the buffer
			bool bGotImage = false;
			RImage image;
			if (image.CreateImage(ptxt->m_im.m_sWidth, ptxt->m_im.m_sHeight, ptxt->m_im.m_type) == 0)
				{
				rspLockBuffer();
				rspBlit(g_pimScreenBuf, &image, ptxt->m_sX, ptxt->m_sY, 0, 0, image.m_sWidth, image.m_sHeight);
				bGotImage = true;
				rspUnlockBuffer();
				}

			// Note that the GUI locks the buffer, if appropriate.
			ptxt->Draw(g_pimScreenBuf);
			rspUpdateDisplay(ptxt->m_sX, ptxt->m_sY, ptxt->m_im.m_sWidth, ptxt->m_im.m_sHeight);

			if (bGotImage)
				{
				rspLockBuffer();
				rspBlit(&image, g_pimScreenBuf, 0, 0, ptxt->m_sX, ptxt->m_sY, image.m_sWidth, image.m_sHeight);
				rspUnlockBuffer();
				}
			}

		// Check for the abort key
		if (pau8KeyStatus[NET_PROB_GUI_ABORT_SK_KEY])
			sAbort = 1;
		}

	// If aborting, set our own flag, too
	if (sAbort)
		{
		// Set flag
		ms_bNetBlockingAbort = true;
		}

	return sAbort;
	}

//////////////////////////////////////////////////////////////////////////////
//
// Initialize the net problems GUI.
// Note that this is nearly instantaneous (no file access) if it has already
// been called.  That is, calling this twice in a row is fine.  Just make
// sure you call KillNetProbGUI() when done (although, even that is not
// essential).
//
//////////////////////////////////////////////////////////////////////////////
extern int16_t InitNetProbGUI(void)
	{
	int16_t	sRes	= 0;	// Assume success.

	KillNetProbGUI();

	sRes	= rspGetResource(&g_resmgrShell, NET_PROB_GUI_FILE, &ms_ptxtNetProb);

	if (sRes == 0)
		{
		// Set some intial stuff.
		ms_ptxtNetProb->m_sTextEffects			= RGuiItem::Shadow;
		ms_ptxtNetProb->m_u32TextShadowColor	= NET_PROB_TEXT_SHADOW_COLOR_INDEX;
		ms_ptxtNetProb->m_sX							= NET_PROB_GUI_X;
		ms_ptxtNetProb->m_sY							= NET_PROB_GUI_Y;
		// Set generic initial text.
		ms_ptxtNetProb->SetText("%s", g_pszNetProb_General);
		ms_ptxtNetProb->Compose();
		}
	else
		{
		TRACE("InitNetProbGUI(): Error loading Net Prob GUI \"%s\".\n", 
			NET_PROB_GUI_FILE);
		}

	return sRes;
	}

//////////////////////////////////////////////////////////////////////////////
//
// Kill the net problems GUI.
//
//////////////////////////////////////////////////////////////////////////////
extern void KillNetProbGUI(void)
	{
	if (ms_ptxtNetProb)
		{
		rspReleaseResource(&g_resmgrShell, &ms_ptxtNetProb);
		}
	}

//////////////////////////////////////////////////////////////////////////////
//
// Get the net prob GUI which is used to notify the user of network problems.
// You can move it, draw it, change its text, or whatever.  It's just up to 
// you to avoid having a problem with other things updating its settings while
// you are.
// Note that this is automagically drawn to the screen via the blocking 
// callback.
//
//////////////////////////////////////////////////////////////////////////////
extern RTxt* GetNetProbGUI(void)
	{
	return ms_ptxtNetProb;
	}

//////////////////////////////////////////////////////////////////////////////
//
// Determine whether there is a net problem.  Set via blocking callback.
// Cleared by you when you call ClearNetProb().
//
//////////////////////////////////////////////////////////////////////////////
extern bool IsNetProb(void)	// Returns true, if net problem; false otherwise.
	{
	return m_bNetWatchdogExpired;
	}

extern void ClearNetProb(void)
	{
	m_bNetWatchdogExpired = false;
	}


///////////////////////////////////////////////////////////////////////////////
// EOF
///////////////////////////////////////////////////////////////////////////////