File: controller.c

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

static const char rcs_id[] = "$Header: /home/jcb/newmj/RCS/controller.c,v 11.49 2007/05/22 13:38:31 jcb Exp $";

#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "controller.h"
#include "scoring.h"

#include "sysdep.h"

#include "version.h"

/* extra data in players */
typedef struct {
  /* option settings */
  int options[PONumOptions];
  /* this variable is set to one to indicate that the player
     has been disconnected or otherwise out of touch, and therefore needs
     to be told the current state of the game. */
  int disconnected;
  int protversion; /* protocol version supported by this player */
  int localtimeouts; /* 1 if this player has requested LocalTimeouts */
} PlayerExtras;

#define popts(p) ((PlayerExtras *)(p->userdata))->options
#define pextras(p) ((PlayerExtras *)(p->userdata))

/* this is The Game that we will use */

Game *the_game = NULL;

int num_connected_players;
#define NUM_PLAYERS 4

int first_id = 0; /* id assigned to first player to connect */

/* This array stores information about current connections.
   When a new connection arrives, we use the first free slot.
*/
#define MAX_CONNECTIONS 8
struct {
  int inuse; /* slot in use */
  SOCKET skt; /* the system level socket of this connection. */
  PlayerP player; /* player, if any */
  int seqno; /* sequence number of messages on this connection */
  PMsgMsg *cm; /* stored copy of the player's connect message */
} connections[MAX_CONNECTIONS];


/* This is the fd of the socket on which we listen */
SOCKET socket_fd;

/* This is the master set of fds on which we are listening
   for events. If we're on some foul system that doesn't have
   this type, it is sysdep.h's responsibility to make sure we do.
*/

fd_set event_fds;

/* this is used by auxiliary functions to pass back an error message */
char *failmsg;

/* This is a logfile, if specified */
FILE *logfile = NULL;

/* This is the name of a game option file */
char *optfilename = NULL;

/* forward declarations */
static void despatch_line(int cnx, char *line);
static int close_connection(int cnx);
static int new_connection(SOCKET skt); /* returns new connection number */
static void setup_maps(int cnx, PlayerP p);
static void remove_from_maps(int cnx);
static void send_packet(int cnx,CMsgMsg *m, int logit); /* not much used except in next two */
static void _send_id(int id,CMsgMsg *m, int logit);
static void _send_all(Game *g,CMsgMsg *m);
static void _send_others(Game *g, int id,CMsgMsg *m);
static void _send_seat(Game *g, seats s, CMsgMsg *m);
static void _send_other_seats(Game *g, seats s, CMsgMsg *m);
/* always casting is boring, so ... */
/* send_id logs (if logging is enabled */
#define send_id(id,m) _send_id(id,(CMsgMsg *)(m),1)
#define send_all(g,m) _send_all(g,(CMsgMsg *)(m))
#define send_others(g,id,m) _send_others(g,id,(CMsgMsg *)(m))
#define send_seat(g,s,m) _send_seat(g,s,(CMsgMsg *)(m))
#define send_other_seats(g,s,m) _send_other_seats(g,s,(CMsgMsg *)(m))
static void resend(int id,CMsgMsg *m);
static int load_state(Game *g);
static char *save_state(Game *g, char *filename);
static void save_and_exit(void); /* save if save-on-exit, and quit */
static int load_wall(char *wfname, Game *g);
static int id_to_cnx(int id);
static int cnx_to_id(int cnx);
static void clear_history(Game *g);
static void history_add(Game *g, CMsgMsg *m);

/* N.B. we do not use the game_id_to_player function, since
   we don't always have players in a game.
*/
static PlayerP id_to_player(int id);

/* A convenience definition. */
#define id_to_seat(id) game_id_to_seat(the_game,id)
/* and another */
#define handle_cmsg(g,m) game_handle_cmsg(g,(CMsgMsg *)m)

static int start_hand(Game *g);
static void check_claims(Game *g);
static void send_infotiles(PlayerP p);
static void score_hand(Game *g, seats s);
static void washout(char *reason);
static void handle_cnx_error(int cnx);

static int loadstate = 0; /* if we have to load state */
static int randomseats = 0; /* assign seats randomly */
static int noidrequired = 0; /* allow arbitrary joining on resumption */
static int nomanager = 0; /* forbid managers */
static char *wallfilename = NULL; /*file to load wall from*/
static char loadfilename[1024]; /* file to load game from */
static int debug = 0; /* allow debugging messages */
static int usehist = 1; /* if we keep history to allow resumption */
static int end_on_disconnect = 0; /* end game (gracefully) on disconnect */
/* penalties for disconnection */
static int disconnect_penalty_end_of_round = 0;
static int disconnect_penalty_end_of_hand = 0;
static int disconnect_penalty_in_hand = 0;
static int exit_on_disconnect = 0; /* if we die on losing a player */
static int save_on_exit = 0; /* save on exit other than at end of game */
static int localtimeouts = 0; /* are we using local timeouts ? */

static void usage(char *pname,char *msg) {
  fprintf(stderr,"%s: %s\nUsage: %s [ --server ADDR ]"
"  [ --timeout N ]\n"
"  [ --pause N ]\n"
"  [ --random-seats ]\n"
"  [ --debug ]\n"
"  [ --disconnect-penalties N1,N2,N3 ]\n"
"  [ --end-on-disconnect ]\n"
"  [ --exit-on-disconnect ]\n"
"  [ --save-on-exit ]\n"
"  [ --option-file FILE ]\n"
"  [ --load-game FILE ]\n"
"  [ --no-id-required ]\n"
"  [ --no-manager ]\n"
"  [ --logfile FILE]\n"
"  [ --no-special-scores ]\n"
"  [ --seed N ]\n"
"  [ --wallfile FILE ]\n"
"  [ --nohist ]\n",
	  pname,msg,pname);
  exit(1);
}

/* This global is used to specify a timeout for claims
   in milliseconds. If it is non-zero on entry to the select
   call, then it will be used as the timeout for select; and if
   data is read before timeout, it will be adjusted appropriately
   for the next call. If a select expires due to timeout, then
   the timeout_handler is called. */
static void timeout_handler(Game *g);
static int timeout = 0;
/* this is the user level timeout in seconds.*/
static int timeout_time = 15;
/* this function extracts the timeout_time from a game
   according the Timeout and TimeoutGrace options, and
   the passed in value of localtimeouts */
static int get_timeout_time(Game *g,int localtimeouts);
/* this is the minimum time between discards and draws,
   keep the game down to human speed */
static int min_time = 0; /* deciseconds */
/* and this is the value requested on the command line */
static int min_time_opt = 0;
/* A player has disconnected, and we're cleaning up the
   mess. Used to keep the game going during MahJonging */
static int end_on_disconnect_in_progress = 0;
/* This is for a hack: if we get two savestate requests while
   a hand is completed, on the second one we save the history of 
   the hand, rather than just the game state. So this variable
   gets incremented when save_state is called in handcomplete,
   and is reset by start_hand.
*/
static int save_state_hack = 0;


int main(int argc, char *argv[]) {
  char *address = ":5000";
  char *logfilename = NULL;
  int seed = 0;
  int nfds; 
  struct timeval timenow, timethen, timetimeout;
  fd_set rfds, efds;
  int i;

  /* options. I should use getopt ... */
  for (i=1;i<argc;i++) {
    if ( strcmp(argv[i],"--nohist") == 0 ) {
      usehist = 0;
    } else if ( strcmp(argv[i],"--debug") == 0 ) {
      debug = 1;
    } else if ( strcmp(argv[i],"--random-seats") == 0 ) {
      randomseats = 1;
    } else if ( strcmp(argv[i],"--no-id-required") == 0 ) {
      noidrequired = 1;
    } else if ( strcmp(argv[i],"--no-manager") == 0 ) {
      nomanager = 1;
    } else if ( strcmp(argv[i],"--disconnect-penalties") == 0 ) {
      if ( ++i == argc ) usage(argv[0],"missing argument to --disconnect-penalties");
      sscanf(argv[i],"%d,%d,%d",
	&disconnect_penalty_in_hand,
	&disconnect_penalty_end_of_hand,
	&disconnect_penalty_end_of_round);
    } else if ( strcmp(argv[i],"--end-on-disconnect") == 0 ) {
      end_on_disconnect = 1;
    } else if ( strcmp(argv[i],"--exit-on-disconnect") == 0 ) {
      exit_on_disconnect = 1;
    } else if ( strcmp(argv[i],"--save-on-exit") == 0 ) {
      save_on_exit = 1;
    } else if ( strcmp(argv[i],"--no-special-scores") == 0 ) {
      no_special_scores = 1;
    } else if ( strcmp(argv[i],"--address") == 0 ) {
      /* N.B. the --address option is retained only for backward compatibility */
      if ( ++i == argc ) usage(argv[0],"missing argument to --address");
      address = argv[i];
    } else if ( strcmp(argv[i],"--server") == 0 ) {
      if ( ++i == argc ) usage(argv[0],"missing argument to --server");
      address = argv[i];
    } else if ( strcmp(argv[i],"--timeout") == 0 ) {
      if ( ++i == argc ) usage(argv[0],"missing argument to --timeout");
      timeout_time = atoi(argv[i]);
    } else if ( strcmp(argv[i],"--pause") == 0 ) {
      if ( ++i == argc ) usage(argv[0],"missing argument to --pause");
      min_time_opt = min_time = atoi(argv[i]); /* N.B. Time in deciseconds */
    } else if ( strcmp(argv[i],"--seed") == 0 ) {
      if ( ++i == argc ) usage(argv[0],"missing argument to --seed");
      seed = atoi(argv[i]);
    } else if ( strcmp(argv[i],"--logfile") == 0 ) {
      if ( ++i == argc ) usage(argv[0],"missing argument to --logfile");
      logfilename = argv[i];
    } else if ( strcmp(argv[i],"--option-file") == 0 ) {
      if ( ++i == argc ) usage(argv[0],"missing argument to --option-file");
      optfilename = argv[i];
    } else if ( strcmp(argv[i],"--load-game") == 0 ) {
      if ( ++i == argc ) usage(argv[0],"missing argument to --load-game");
      strmcpy(loadfilename,argv[i],1023);
      loadstate = 1;
    } else if ( strcmp(argv[i],"--wallfile") == 0 ) {
      if ( ++i == argc ) usage(argv[0],"missing argument to --wallfile");
      wallfilename = argv[i];
    } else usage(argv[0],"unknown option or argument");
  }

  if ( logfilename ) {
    if ( strcmp(logfilename,"-") == 0 ) {
      logfile = stdout;
    } else {
      logfile = fopen(logfilename,"a");
      if ( ! logfile ) {
	perror("couldn't open logfile");
	exit(1);
      }
    }
  }

  /* we don't want to get SIGPIPE */
  ignore_sigpipe();

  socket_fd = set_up_listening_socket(address);
  if ( socket_fd == INVALID_SOCKET ) {
    printf("FAILED: couldn't set up socket\n");
    perror("couldn't set up listening socket");
    exit(1);
  }
  printf("OK: %s\n",address);
  fflush(stdout);

  /* stick it in the connection list */
  new_connection(socket_fd);
  
  /* seed the random number generator */
  rand_seed(seed);

  /* initialize data */
  num_connected_players = 0;

  /* malloc space for the game and four players.
     We will shortly load the state if we're resuming; if we're not
     resuming, initialization happens later */
  the_game = (Game *) malloc(sizeof(Game));
  if ( the_game == NULL ) {
    warn("Couldn't malloc game structure");
    exit(1);
  }
  memset((void *)the_game,0,sizeof(Game));
  the_game->userdata = malloc(sizeof(GameExtras));
  if ( the_game->userdata == NULL ) {
    warn("Couldn't malloc game extra structure");
    exit(1);
  }
  gextras(the_game)->histcount = gextras(the_game)->prehistcount = 0;
  gextras(the_game)->caller = (PlayerP) malloc(sizeof(Player));
  if ( gextras(the_game)->caller == NULL ) {
    warn("Couldn't malloc game extra structure");
    exit(1);
  }


  for ( i=0 ; i < NUM_SEATS ; i++ ) {
    void *tmp;
    if ( (the_game->players[i] = (PlayerP) malloc(sizeof(Player)))
	 == NULL ) {
      warn("couldn't malloc player structure");
      exit(1);
    }
    memset((void *)the_game->players[i],0,sizeof(Player));
    if ( (tmp = malloc(sizeof(PlayerExtras)))
	 == NULL ) {
      warn("couldn't malloc player options");
      exit(1);
    }
    memset((void *)tmp,0,sizeof(PlayerExtras));
    set_player_userdata(the_game->players[i],tmp);
  }

  /* some game initialization happens here */
  the_game->protversion = PROTOCOL_VERSION; /* may be reduced by players */
  game_set_options_from_defaults(the_game);

  if ( loadstate ) {
    if ( load_state(the_game) == 0 ) {
      warn("Couldn't load the game state");
      loadstate = 0;
    }
  }

  /* enter the main loop */
  while ( 1 ) {
    struct timeval *tvp;
    rfds = efds = event_fds;

    tvp = NULL;
    if ( the_game->active && !the_game->paused && timeout > 0 ) {
      gettimeofday(&timethen,NULL);
      tvp = &timetimeout;
      tvp->tv_sec = timeout/1000; tvp->tv_usec = (timeout%1000)*1000;
    }
      
    nfds = select(32,&rfds,NULL,&efds,tvp); /* n, read, write, except, timeout */

    if ( tvp ) {
      gettimeofday(&timenow,NULL);
      timeout -= (timenow.tv_sec*1000 + timenow.tv_usec/1000)
	- (timethen.tv_sec*1000 + timethen.tv_usec/1000);
    }

    if ( nfds < 0 ) {
      perror("select failed");
      exit(1);
    }

    /* if the timeout has gone negative, that means that something
       is throwing input at us so fast we never get round to cancelling
       the timeout. This probably means something is in a loop. So
       call the timeout handler anyway */

    if ( nfds == 0 || timeout < 0 ) {
      timeout_handler(the_game);
      continue;
    }

    for ( i = 0 ; i < MAX_CONNECTIONS ; i++ ) {
      SOCKET fd;
      if ( ! connections[i].inuse ) continue;
      fd = connections[i].skt;

      if ( FD_ISSET(fd,&efds) ) {
	handle_cnx_error(i);
	continue;
      }
      if ( FD_ISSET(fd,&rfds) ) {
	if ( fd == socket_fd ) {
	  SOCKET newfd;

          newfd = accept_new_connection(fd);
	  if (newfd == INVALID_SOCKET) {
	    warn("failure in accepting connection");
	    exit(1);
	  }
	  /* if we are shutting down after a disconnect,
	     accept no more connections */
	  if ( end_on_disconnect_in_progress ) {
	    CMsgErrorMsg em;
	    em.type = CMsgError;
	    em.seqno = 0;
	    em.error = "Game shutting down; no reconnect allowed";
	    put_line(newfd,encode_cmsg((CMsgMsg *)&em));
	    closesocket(newfd);
	  } else
	  /* add to the connection list */
	  if ( new_connection(newfd) < 0) {
	    CMsgErrorMsg em;
	    em.type = CMsgError;
	    em.seqno = 0;
	    em.error = "Unable to accept new connections";
	    put_line(newfd,encode_cmsg((CMsgMsg *)&em));
	    closesocket(newfd);
	  }
	}
	else {
	  char *line;
	  /* get_line will fail if there is only a partial line
	     available. This is wrong, since it is possible for
	     lines to arrive fragmentedly (not that it should 
	     normally happen). However, it would also be wrong to
	     wait forever for a partial line to complete. There
	     should be a timeout.
	  */
	  /* get_line provides us with a pointer to the text line,
	     which we can mess with as we like, provided we don't
	     expect it to survive the next call to get_line
	  */
	  line = get_line(connections[i].skt); /* errors dealt with by despatch line */
	  /* except that we want to know the error code */
	  if ( line == NULL ) {
	    info("get_line returned null: %s",strerror(errno));
	  }
	  despatch_line(i,line);
	}
      }
    }
  }
}

/* function to act on Player Messages. NB it takes a connection number,
   not an id, since ids may be unassigned.
*/
static void handle_pmsg(PMsgMsg *pmp, int cnx);

/* despatch_line: process the line of input received on cnx. */

static void despatch_line(int cnx, char *line) {
  PMsgMsg *pmp;

  if ( logfile ) {
    fprintf(logfile,"<cnx%d %s",cnx,line);
  }

  if ( line == NULL ) {
    warn("receive error on cnx %d, player id %d\n",cnx, cnx_to_id(cnx));
    handle_cnx_error(cnx);
    return;
  }

  pmp = decode_pmsg(line);
  /* increment the sequence number */
  connections[cnx].seqno++;

  if ( pmp == NULL ) {
    CMsgErrorMsg em;
    em.type = CMsgError;
    em.error = "Protocol error";
    em.seqno = connections[cnx].seqno;
    send_packet(cnx,(CMsgMsg *)&em,1);
    warn("Protocol error on cnx %d, player id %d; ignoring\n",cnx, cnx_to_id(cnx));
    return;
  }

  handle_pmsg(pmp,cnx);
}

/* little function to check that the minimum time has passed 
   since the last tile moving activity.
   The argument multiplies the usual delay time between the current
   call and the next call. It's used to increase the delay after
   claim implementations. bloody emacs ' */
static void check_min_time(float factor) {
  static struct timeval disctime, timenow;
  static int min_time_this_time;
  if ( min_time_this_time > 0 ) {
    int n;
    if ( disctime.tv_sec > 0 ) { /* not firsttime */
      gettimeofday(&timenow,NULL);
      n = (timenow.tv_sec * 1000 + timenow.tv_usec/1000)
	- (disctime.tv_sec * 1000 + disctime.tv_usec/1000);
      n = 100*min_time_this_time - n;
      if ( n > 0 ) usleep(1000*n);
    }
    gettimeofday(&disctime,NULL);
  }
  min_time_this_time = (int)(min_time*factor);
}

static void handle_pmsg(PMsgMsg *pmp, int cnx) 
{

  /* We mustn't act on most requests if the game is not active.
     There's a race possible otherwise: we can suspend the game, and
     meanwhile a player sends a request: we then act on this, but it
     doesn't get into the history records of the suspended players. */
  if ( ! the_game->active ) {
    CMsgErrorMsg em;
    em.type = CMsgError;
    em.error = "Game not active";
    em.seqno = connections[cnx].seqno;
    switch ( pmp->type ) {
    case PMsgSaveState:
    case PMsgLoadState:
    case PMsgConnect:
    case PMsgRequestReconnect:
    case PMsgSetPlayerOption:
    case PMsgSendMessage:
    case PMsgQueryGameOption:
    case PMsgListGameOptions:
      break; /* these are OK */
    default:
      send_packet(cnx,(CMsgMsg *)&em,0);
      return;
    }
  }

  /* check for debugging messages */
  if ( ! debug && pmp->type >= DebugMsgsStart ) {
    CMsgErrorMsg em;
    em.type = CMsgError;
    em.seqno = connections[cnx].seqno;
    em.error = "Debugging not enabled";
    send_packet(cnx,(CMsgMsg *)&em,0);
    return;
  }

  switch ( pmp->type ) {
  case PMsgSaveState:
    { 
      PMsgSaveStateMsg *m = (PMsgSaveStateMsg *)pmp;
      CMsgErrorMsg em;
      PlayerP p; int id; seats seat;
      char *res;
      
      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);
      
      em.type = CMsgError;
      em.seqno = connections[cnx].seqno;
      
      if ( (res = save_state(the_game,m->filename)) ) {
	if ( the_game->protversion >= 1025 ) {
	  CMsgStateSavedMsg ssm;
	  ssm.type = CMsgStateSaved;
	  ssm.id = id;
	  ssm.filename = res;
	  send_all(the_game,&ssm);
	}
      } else {
	em.error = "Unable to save state";
	send_id(id,&em);
      }
      return;
    }
  case PMsgLoadState:
    {
      PMsgLoadStateMsg *m = (PMsgLoadStateMsg *) pmp;
      CMsgErrorMsg em;
      PlayerP p; int id; seats seat;
      
      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);
      
      em.type = CMsgError;
      em.seqno = connections[cnx].seqno;
      em.error = NULL; 

      /* I think we can load state any time before the game starts,
	 and only then */
      if ( protocol_version < 1038 ) {
	em.error = "Not all players support dynamic state loading";
      } else if ( game_has_started(the_game) ) {
	em.error = "Can't load game state when already playing";
      } else if ( m->filename == NULL || m->filename[0] == 0 ) {
	em.error = "No game file specified in LoadState";
      } else {
	int i;
	CMsgPlayerMsg pm;
	loadstate = 1;
	strmcpy(loadfilename,m->filename,1023);
	/* first delete all players from the clients */
	pm.type = CMsgPlayer;
	pm.name = NULL;
	for ( i = 0 ; i < MAX_CONNECTIONS ; i++ ) {
	  if ( connections[i].inuse && connections[i].player ) {
	    pm.id = connections[i].player->id;
	    send_all(the_game,&pm);
	  }
	}
	/* now remove from maps ... */
	for ( i = 0 ; i < MAX_CONNECTIONS ; i++ ) {
	  if ( connections[i].inuse && connections[i].player ) {
	    remove_from_maps(i);
	    num_connected_players--;
	  }
	}
	if ( ! load_state(the_game) ) {
	  em.error = "Loading game state failed";
	}
	the_game->active = 0;
	/* now reprocess connection messages */
	for ( i = 0 ; i < MAX_CONNECTIONS ; i++ ) {
	  if ( connections[i].inuse && connections[i].cm) {
	    handle_pmsg(connections[i].cm,i);
	  }
	}
      }
      if ( em.error ) {
	send_id(id,&em);
      }
      return;
    }
  case PMsgRequestReconnect:
    {
      CMsgReconnectMsg rm;
      CMsgErrorMsg em;
      PlayerP p; int id; seats seat;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      rm.type = CMsgReconnect;
      em.type = CMsgError;

      /* no reason to refuse, so far */
      
      /* first, stop play */
      { char msg[1024];
	CMsgStopPlayMsg spm;
	spm.type = CMsgStopPlay;
	sprintf(msg,"Player %s requested reconnect - please wait...",
		p->name);
	spm.reason = msg;
	send_all(the_game,&spm);
	the_game->active = 0;
      }

      /* now send the reconnect */
      send_id(id,&rm);

      /* remove player from maps and decrement player count */
      remove_from_maps(cnx);
      num_connected_players--;

      return;
    }
  case PMsgConnect:
    {
      PMsgConnectMsg *m = (PMsgConnectMsg *) pmp;
      PlayerP p = NULL;
      CMsgConnectReplyMsg cm;
      CMsgPlayerMsg thisplayer;
      CMsgGameMsg gamemsg;
      char *refusal = NULL;
      static int player_id = 0;
      int i;

      /* start filling in reply message */
      cm.type = CMsgConnectReply;
      cm.pvers = PROTOCOL_VERSION;
      if ( m->pvers/1000 != PROTOCOL_VERSION/1000 ) refusal = "Protocol major version mismatch";
      if ( num_connected_players == NUM_PLAYERS )
	refusal = "Already have players";
      /* it's reasonable to insist on a name being supplied */
      if ( m->name == NULL ) 
	refusal = "A non-empty name must be given";
      if ( cnx_to_id(cnx) >= 0 )
        refusal = "You already have a player ID";

      /* If we have a previous game state loaded, we need to associate
	 this player with one in the game. Match on ids */
      if ( loadstate && !refusal ) {
	/* if no id specified, match on names */
	if ( m->last_id != 0 ) {
	  for ( i = 0; i < NUM_SEATS
		  && m->last_id != the_game->players[i]->id ; i++ ) ;
	} else {
	  for ( i = 0; i < NUM_SEATS
		  && (strcmp(m->name,the_game->players[i]->name) != 0) ; i++ ) ;
	}
	/* if no id required, just match this to the first player
	   not currently connected */
	if ( i == NUM_SEATS && noidrequired ) {
	  for ( i = 0; i < NUM_SEATS 
		  && id_to_cnx(the_game->players[i]->id) >= 0 ; i++ );
	}
	if ( i == NUM_SEATS ) {
	  refusal = "Can't find you in the resumed game";
	} else {
	  /* better check that this player isn't already connected */
	  if ( id_to_cnx(m->last_id) >= 0 )
	    refusal = "Your id is already connected";
	  else {
	    p = the_game->players[i];
	    set_player_name(p,m->name); /* not preserved by saving */
	    setup_maps(cnx,p); /* set up maps between id and cnx etc*/
	    num_connected_players++;
	  }
	}
      } else if ( ! refusal) {
	/* ignore the lastid field, and assign this player a new
	   id */
	p = game_id_to_player(the_game,0); /* get free player structure */
	if ( p == NULL ) {
	  warn("can't get player structure; exiting");
	  exit(1);
	}
	initialize_player(p);
	num_connected_players++;
	set_player_id(p,++player_id);
	set_player_name(p,m->name);
	/* store the id of the first human player to connect.
	   This assumes that computer players are called Robot.. */
	if ( ! first_id 
	     && strncmp(p->name,"Robot",5) != 0 ) first_id = num_connected_players;
	setup_maps(cnx,p); /* set up maps between id and cnx etc*/
      }
      if (refusal) {
	cm.id = 0;
	cm.reason = refusal;
	send_packet(cnx,(CMsgMsg *)&cm,1);
	close_connection(cnx);
	return;
      }
      /* send the reply */
      cm.id = p->id;
      cm.reason = NULL;
      send_packet(cnx,(CMsgMsg *)&cm,1);

      /* store the protocol version of this player */
      pextras(p)->protversion = m->pvers;

      /* Yes, this is right: the fact that this player is connecting
	 means that it has been disconnected! */
      pextras(p)->disconnected = 1;

      /* keep a copy of the message if not already there */
      if ( connections[cnx].cm == NULL ) {
	connections[cnx].cm = pmsg_deepcopy(pmp);
      }

      /* Now we need to tell this player who's already here, and
	 tell the others about this one */
      thisplayer.type = CMsgPlayer;
      thisplayer.id = p->id;
      thisplayer.name = p->name;

      for ( i = 0; i < NUM_SEATS; i++ ) {
	CMsgPlayerMsg pm;
	PlayerP q;

	q = the_game->players[i];

	if ( q->id == 0 ) continue;
	
	if ( q->id == p->id ) continue;

	pm.type = CMsgPlayer;
	pm.id = q->id;
	pm.name = q->name;
	  
	send_packet(cnx,(CMsgMsg *)&pm,1);
	send_id(q->id,&thisplayer); /* fails harmlessly if not connected */
      }

      /* set the protocol version to the greatest supported version.
	 We inspect all players again in case somebody disconnected
	 before the game was set up */
      protocol_version = PROTOCOL_VERSION;
      for ( i = 0; i < NUM_SEATS ; i++ ) {
	PlayerP q = the_game->players[i];
	if ( q->id == 0 ) continue;
	if ( protocol_version > pextras(q)->protversion )
	  protocol_version = pextras(q)->protversion;
      }
      /* if not everybody is connected, just wait for the next */
      if ( num_connected_players < NUM_SEATS ) return;

      /* otherwise, set up the game state (if we aren't 
	 already in the middle of an interrupted game */

      if ( ! loadstate ) {
	GameOptionEntry goe;
	/* randomize the seats if desired */
	if ( randomseats ) {
	  int i,j,n;
	  PlayerP temp[NUM_SEATS];
	  for (i=0; i<NUM_SEATS; i++) temp[i] = the_game->players[i];
	  for (i=0; i<NUM_SEATS; i++) {
	    /* random number between 0 and seatsleft-1 */
	    n = rand_index(NUM_SEATS-(i+1));
	    /* skip already used */
	    j = 0;
	    while ( (!temp[j]) || j < n ) {
	      if ( !temp[j] ) n++;
	      j++;
	    }
	    the_game->players[i] = temp[j];
	    temp[j] = NULL;
	  }
	}
	the_game->state = HandComplete;
	the_game->player = noseat;
	the_game->round = EastWind;
	the_game->hands_as_east = 0;
	the_game->firsteast = the_game->players[east]->id;
	/* protocol_version has been maintained during the
	   connection process */
	the_game->protversion = protocol_version;
	the_game->manager = nomanager ? -1 : first_id;
	game_set_options_from_defaults(the_game);
	/* initialize the timeout time from the command line option */
	goe = *game_get_option_entry(the_game,GOTimeout,NULL);
	goe.value.optint = timeout_time;
	game_set_option(the_game,&goe);
	/* And I think we will have the normal dead wall as default,
	   rather than millington style */
	goe = *game_get_option_entry(the_game,GODeadWall16,NULL);
	if ( goe.enabled ) {
	  goe.value.optbool = 0;
	  game_set_option(the_game,&goe);
	}
	/* Now load the game option file, if there is one */
	if ( optfilename ) {
	  FILE *optfile;
	  char buf[1024];
	  optfile = fopen(optfilename,"r");
	  if ( optfile ) {
	    CMsgMsg *m;
	    while ( ! feof(optfile) ) {
	      fgets(buf,1024,optfile);
	      m = decode_cmsg(buf);
	      if ( ! m ) {
		warn("Error decoding game option file entry %s",buf);
	      } else {
		if ( handle_cmsg(the_game,m) < 0 ) {
		  warn("Error applying game option (%s)",the_game->cmsg_err);
		}
		cmsg_deepfree(m);
	      }
	    }
	  } else {
	    warn("couldn't open game option file %s (%s)",
		 optfilename,strerror(errno));
	  }
	}
      }
      the_game->cmsg_check = 1;

      gamemsg.type = CMsgGame;
      gamemsg.east = the_game->players[east]->id;
      gamemsg.south = the_game->players[south]->id;
      gamemsg.west = the_game->players[west]->id;
      gamemsg.north = the_game->players[north]->id;
      gamemsg.round = the_game->round;
      gamemsg.hands_as_east = the_game->hands_as_east;
      gamemsg.firsteast = the_game->firsteast;
      gamemsg.east_score = the_game->players[east]->cumulative_score;
      gamemsg.south_score = the_game->players[south]->cumulative_score;
      gamemsg.west_score = the_game->players[west]->cumulative_score;
      gamemsg.north_score = the_game->players[north]->cumulative_score;
      gamemsg.protversion = the_game->protversion;
      gamemsg.manager = the_game->manager;
      
      /* we only send the game message to the players who
	 have been disconnected. (In the usual case, this
	 is all players...) */

      for ( i=0 ; i < NUM_SEATS; i++ ) {
	PlayerP p = the_game->players[i];
	PMsgListGameOptionsMsg plgo;
	if ( ! pextras(p)->disconnected ) continue;

	send_id(p->id,&gamemsg);
	/* we also have to tell them the game options now, so that
	   they do any necessary setup corrrectly before the new
	   hand message. This is most easily done by faking a 
	   ListOptions request. */
	plgo.type = PMsgListGameOptions;
	plgo.include_disabled = 0;
	handle_pmsg((PMsgMsg *)&plgo,id_to_cnx(p->id));

	/* we don't actually clear the history records
	   until the NewHand message is sent. But we don't
	   want to send history for a complete hand.
	   However, if the game is paused, we need to tell the player so. */
	if ( the_game->state == HandComplete ) {
	  if ( the_game->paused ) {
	    CMsgPauseMsg pm;
	    CMsgPlayerReadyMsg prm;
	    int i;
	    pm.type = CMsgPause;
	    pm.exempt = 0;
	    pm.requestor = 0;
	    pm.reason = the_game->paused;
	    send_id(p->id,&pm);
	    prm.type = CMsgPlayerReady;
	    for ( i = 0; i < NUM_SEATS; i++ ) {
	      if ( the_game->ready[i] ) {
		prm.id = the_game->players[i]->id;
		send_id(p->id,&prm);
	      }
	    }
	  }
	}
      }
      /* now we need to send the history to disconnected players.*/
      if ( the_game->state != HandComplete ) {
	int j;
	if ( ! usehist ) {
	  CMsgErrorMsg em;
	  em.type = CMsgError;
	  em.seqno = connections[cnx].seqno;
	  em.error = "No history kept: resumption not supported";
	  send_all(the_game,&em);
	  warn(em.error);
	  exit(1);
	}
	for ( j=0; j < gextras(the_game)->histcount; j++ ) {
	  int sleeptime;
	  for ( i=0 ; i < NUM_SEATS; i++ ) {
	    PlayerP p = the_game->players[i];
	    if ( ! pextras(p)->disconnected ) continue;
	    resend(p->id,gextras(the_game)->history[j]);
	  }
	  /* this is an undocumented feature to make things 
	     a bit nicer for humans reconnecting: we'll 
	     unilaterally slow down the feed, by adding a 
	     0.15 second delay between items, or 1 second after
	     a claim implementation. */
	  switch ( gextras(the_game)->history[j]->type ) {
	  case CMsgPlayerPairs:
	  case CMsgPlayerChows:
	  case CMsgPlayerPungs:
	  case CMsgPlayerKongs:
	  case CMsgPlayerSpecialSet:
	    sleeptime = 1000; /* ms */
	    break;
	  default:
	    sleeptime = 150;
	  }
	  usleep(sleeptime*1000);
	}
      }
      /* and now mark those players connected again */
      for ( i=0 ; i < NUM_SEATS; i++ ) {
	PlayerP p = the_game->players[i];
	if ( ! pextras(p)->disconnected ) continue;
	pextras(p)->disconnected = 0;
      }

      /* Now we should tell somebody to do something. Namely:
	 In state HandComplete: tell everybody, and start a hand
	 if things aren't paused.
	 In state Dealing: everybody.
	 In Discarded, several players might want to do something,
	 so we don't specify the id.
	 Ditto in MahJonging.
         Otherwise, it's the player.
      */
      {
	CMsgStartPlayMsg sm;
	CMsgPauseMsg pm;
	sm.type = CMsgStartPlay;
	switch (the_game->state) {
	case HandComplete:
	case Dealing:
	case Discarded:
	case MahJonging:
	  sm.id = 0;
	  break;
	default:
	  sm.id = the_game->players[the_game->player]->id;
	  break;
	}
	/* now we should ask the players whether they are ready to
	   continue. We send the pause request *before* making the
	   game active */
	pm.type = CMsgPause;
	pm.reason = (the_game->state == HandComplete)
	  ? "to start hand" : "to continue play";
	pm.exempt = 0;
	pm.requestor = 0;
	handle_cmsg(the_game,&pm);
	send_all(the_game,&pm);
	send_all(the_game,&sm);
	/* and set the game active */
	the_game->active = 1;
      }


      /* now set loadstate */
      loadstate = 1;

      return;
    } /* end of case PMsgConnect */
  case PMsgRequestPause:
    { PMsgRequestPauseMsg *m = (PMsgRequestPauseMsg *)pmp;
      PlayerP p; int id; seats seat;
      CMsgPauseMsg pm;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      pm.type = CMsgPause;
      pm.exempt = 0;
      pm.requestor = id;
      pm.reason = m->reason;
      
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      if ( !(the_game->state == Discarding
	     || the_game->state == HandComplete) ) {
	em.error = "Not reasonable to pause at this point";
	send_id(id,&em);
	return;
      }
      
      send_all(the_game,&pm);
      break;
    } /* end of PMsgRequestPauseMsg */
  case PMsgSetPlayerOption:
    {
      PMsgSetPlayerOptionMsg *m = (PMsgSetPlayerOptionMsg *)pmp;
      PlayerP p; int id; seats seat;
      CMsgPlayerOptionSetMsg posm;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      posm.type = CMsgPlayerOptionSet;
      posm.option = m->option;
      posm.value = m->value;
      posm.text = m->text;
      posm.ack = 1;
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      if ( m->option == (unsigned)-1 ) m->option = POUnknown;
      if ( m->option == POUnknown ) em.error = "Unknown option";
      else switch ( m->option ) {
	/* validity checking  */
	/* boolean options */
      case POInfoTiles:
	if ( m->value < 0 || m->value > 1 ) em.error = "Bad value for InfoTiles";
	break;
      case POLocalTimeouts:
	/* This is a bit messy. As a matter of policy, we only allow
	   a client to do local timeouts if everybody else is too.
	   So we simply remember the requests, unless all have requested,
	   in which case we ack everybody. */
	/* if this is an ack, ignore it. We should only get acks
	   after we've forcibly set things to zero, and then
	   we don't care about the ack. */
	if ( m->ack ) break;
	/* if this is a request to start local timeouts: */
	if ( m->value ) {
	  int i,lt;
	  pextras(p)->localtimeouts = 1;
	  for ( i=0, lt=1; i < NUM_SEATS; i++ ) {
	    lt = (lt && pextras(the_game->players[i])->localtimeouts);
	  }
	  if ( ! lt ) return; /* just wait */
	  localtimeouts = 1;
	  timeout_time = get_timeout_time(the_game,localtimeouts);
	  for ( i=0; i < NUM_SEATS; i++ ) {
	    popts(the_game->players[i])[m->option] = 1;
	  }
	  send_all(the_game,&posm);
	  /* and that's it -- we don't want to drop through */
	  return;
	} else {
	  seats i;
	  /* request to disable local timeouts */
	  localtimeouts = 0;
	  timeout_time = get_timeout_time(the_game,localtimeouts);
	  pextras(p)->localtimeouts = 0;
	  /* instruct all the other players to drop local timeouts */
	  posm.ack = 0;
	  for ( i=0; i < NUM_SEATS; i++ ) {
	    if ( i != seat ) { send_seat(the_game,i,&posm); }
	  }
	  posm.ack = 1;
	  /* now drop through to ack and set this one. */
	}
	break;
	/* non-boolean options */
      case PODelayTime:
	/* players *can* request any positive value */
	if ( m->value < 0 ) em.error = "Bad value for DelayTime";
	break;
      default:
	;
      }
      if ( em.error ) {
	send_id(id,&em);
	return;
      }
      if ( ! m->ack ) { send_id(id,&posm); }
      popts(p)[m->option] = m->value;
      /* action may now be required */
      switch ( m->option ) {
	int i;
      case PODelayTime:
	/* find the highest value requested by any player, or option */
	min_time = min_time_opt;
	for ( i = 0; i < NUM_SEATS; i++ ) {
	  if ( popts(the_game->players[i])[PODelayTime] > min_time )
	    min_time = popts(the_game->players[i])[PODelayTime];
	}
	/* highest reasonable value is 5 seconds */
	if ( min_time > 50 ) min_time = 50;
	break;
      default:
	;
      }
      return;
    }
  case PMsgReady:
    {
      PlayerP p; int id; seats seat;
      CMsgPlayerReadyMsg prm;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      prm.type = CMsgPlayerReady;
      prm.id = id;
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      /* if the player is already ready, ignore this message */
      if ( the_game->ready[seat] ) return;

      if ( handle_cmsg(the_game,&prm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }

      send_all(the_game,&prm);

      /* if state is handcomplete and no longer pausing, 
	 start the next hand */
      if ( the_game->state == HandComplete && ! the_game->paused ) start_hand(the_game);
      /* and in the discarded or konging state, reinstate the timeout */
      if ( the_game->state == Discarded 
	   || (the_game->state == Discarding && the_game->konging ) )
	timeout = 1000*timeout_time;
      return;
    } /* end of case PMsgReady */
  case PMsgDeclareSpecial:
    {
      PMsgDeclareSpecialMsg *m = (PMsgDeclareSpecialMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgPlayerDeclaresSpecialMsg pdsm;
      CMsgPlayerDrawsMsg  pdlm; /* FIXME */
      int res;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      pdlm.id = pdsm.id = id;
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      pdsm.type = CMsgPlayerDeclaresSpecial;
      pdlm.type = CMsgPlayerDraws;
      em.error = NULL;

      /* Legality checking is done by handle cmsg, so
	 just set up the cmsg and apply it */
      pdsm.tile = m->tile;

      res = handle_cmsg(the_game,&pdsm);

      if ( res < -1 ) {
	warn("Consistency error: giving up");
	exit(1);
      }
      if ( res < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }
      check_min_time(1);
      send_all(the_game,&pdsm);
      if ( pdsm.tile == HiddenTile ) {
	/* if we've now started play (i.e. state == Discarding),
	   ask everybody (except east) if they're ready */
	if ( the_game->state == Discarding ) {
	  CMsgPauseMsg pm;
	  pm.type = CMsgPause;
	  pm.reason = "to start play";
	  pm.exempt = the_game->players[east]->id;
	  pm.requestor = 0;
	  if ( handle_cmsg(the_game,&pm) >= 0 ) {
	    send_all(the_game,&pm);
	  } else {
	    warn("Failed to pause at start of play: %s",the_game->cmsg_err);
	  }
	}
	return;
      }
      /* and now draw the replacement */
      if ( game_get_option_value(the_game,GOFlowersLoose,NULL) ) {
	pdlm.tile = game_peek_loose_tile(the_game);
	pdlm.type = CMsgPlayerDrawsLoose;
      } else {
	pdlm.tile = game_peek_tile(the_game);
	pdlm.type = CMsgPlayerDraws;
      }
      if ( pdlm.tile == ErrorTile ) {
	washout(NULL);
	return;
      }

      if ( the_game->state == Discarding ) {
	/* don't do this if declaring specials */
	/* stash a copy of the player, in case it goes mahjong */
	copy_player(gextras(the_game)->caller,p);
      }

      if ( handle_cmsg(the_game,&pdlm) < 0 ) {
	/* error should be impossible */
	warn("Consistency error: giving up");
	exit(1);
      }
      send_id(id,&pdlm);
      pdlm.tile = HiddenTile;
      check_min_time(1);
      send_others(the_game,id,&pdlm);
      send_infotiles(p);
      return;
      assert(0);
    } /* end of case PMsgDeclareSpecial */
  case PMsgDiscard:
    {
      PMsgDiscardMsg *m = (PMsgDiscardMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgPlayerDiscardsMsg pdm;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pdm.type = CMsgPlayerDiscards;
      pdm.id = id;
      pdm.tile = m->tile;
      pdm.discard = the_game->serial+1;
      pdm.calling = m->calling;
      if ( handle_cmsg(the_game,&pdm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }
      check_min_time(1);
      send_all(the_game,&pdm);
      send_infotiles(p);
      /* set the timeout */
      timeout = 1000*timeout_time;
      return;
    } /* end of case PMsgDiscard */
  case PMsgNoClaim:
    {
      PMsgNoClaimMsg *m = (PMsgNoClaimMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgPlayerDoesntClaimMsg pdcm;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pdcm.type = CMsgPlayerDoesntClaim;
      pdcm.id = id;
      pdcm.discard = m->discard;
      pdcm.timeout = 0;

      if ( handle_cmsg(the_game,&pdcm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }
      /* handle_cmsg ignores noclaims in wrong state, so
	 we need to check it */
      if ( ! (the_game->state == Discarded 
	   || ( (the_game->state == Discarding 
		 || the_game->state == DeclaringSpecials)
		&& the_game->konging ) ) ) return;
      /* acknowledge to the player only */
      send_id(id,&pdcm);
      /* if all claims received, process */
      check_claims(the_game);
      return;
    } /* end of case PMsgNoClaim */
  case PMsgPung:
    {
      PMsgPungMsg *m = (PMsgPungMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      if ( the_game->state != MahJonging ) {
	CMsgPlayerClaimsPungMsg pcpm;
	pcpm.type = CMsgPlayerClaimsPung;
	pcpm.id = id;
	pcpm.discard = m->discard;
	if ( handle_cmsg(the_game,&pcpm) < 0 ) {
	  em.error = the_game->cmsg_err;
	  send_id(id,&em);
	  return;
	}
	send_all(the_game,&pcpm);
	/* if all claims received, process */
	check_claims(the_game);
	return;
      } else { /* MahJonging */
	CMsgPlayerPungsMsg ppm;

	ppm.type = CMsgPlayerPungs;
	ppm.id = id;
	ppm.tile = the_game->tile;
	
	if ( handle_cmsg(the_game,&ppm) < 0 ) {
	  em.error = the_game->cmsg_err;
	  send_id(id,&em);
	  return;
	}
	check_min_time(1);
	send_all(the_game,&ppm);
	send_infotiles(p);
	/* if that came from a dangerous discard, tell the other players */
	if ( game_flag(the_game,GFDangerousDiscard) ) {
	  CMsgDangerousDiscardMsg ddm;
	  ddm.type = CMsgDangerousDiscard;
	  ddm.id = the_game->players[the_game->supplier]->id;
	  ddm.discard = the_game->serial;
	  ddm.nochoice = game_flag(the_game,GFNoChoice);
	  send_all(the_game,&ddm);
	}
	/* do scoring if we've finished */
	if ( pflag(p,HandDeclared) ) score_hand(the_game,seat);
	return;
      }
    } /* end of case PMsgPung */
  case PMsgPair:
    {
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgPlayerPairsMsg ppm;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      ppm.type = CMsgPlayerPairs;
      ppm.id = id;
      ppm.tile = the_game->tile;

      if ( handle_cmsg(the_game,&ppm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }
      check_min_time(1);
      send_all(the_game,&ppm);
      send_infotiles(p);
      /* if that came from a dangerous discard, tell the other players */
      if ( game_flag(the_game,GFDangerousDiscard) ) {
	CMsgDangerousDiscardMsg ddm;
	ddm.type = CMsgDangerousDiscard;
	ddm.id = the_game->players[the_game->supplier]->id;
	ddm.discard = the_game->serial;
	ddm.nochoice = game_flag(the_game,GFNoChoice);
	send_all(the_game,&ddm);
      }
      /* do scoring if we've finished */
      if ( pflag(p,HandDeclared) ) score_hand(the_game,seat);
      return;
    } /* end of case PMsgPair */
  case PMsgSpecialSet:
    {
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgPlayerSpecialSetMsg pssm;
      char tiles[100];
      int i;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pssm.type = CMsgPlayerSpecialSet;
      pssm.id = id;
      pssm.tile = the_game->tile;
	
      tiles[0] = '\000';
      for ( i = 0; i < p->num_concealed; i++ ) {
	if ( i > 0 ) strcat(tiles," ");
	strcat(tiles,tile_code(p->concealed[i]));
      }
      pssm.tiles = tiles;

      if ( handle_cmsg(the_game,&pssm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }
      send_all(the_game,&pssm);
      send_infotiles(p);
      /* do scoring if we've finished */
      if ( pflag(p,HandDeclared) ) score_hand(the_game,seat);
      return;
    } /* end of case PMsgSpecialSet */
  case PMsgFormClosedPair:
    {
      PMsgFormClosedPairMsg *m = (PMsgFormClosedPairMsg *) pmp;
      CMsgPlayerFormsClosedPairMsg pfcpm;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pfcpm.type = CMsgPlayerFormsClosedPair;
      pfcpm.id = id;
      pfcpm.tile = m->tile;

      if ( handle_cmsg(the_game,&pfcpm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }
      check_min_time(1);
      send_all(the_game,&pfcpm);
      send_infotiles(p);
      /* do scoring if we've finished */
      if ( pflag(p,HandDeclared) ) score_hand(the_game,seat);
      return;
    } /* end of case PMsgFormClosedPair */
  case PMsgFormClosedSpecialSet:
    {
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgPlayerFormsClosedSpecialSetMsg pfcssm;
      char tiles[100];
      int i;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pfcssm.type = CMsgPlayerFormsClosedSpecialSet;
      pfcssm.id = id;
      tiles[0] = '\000';
      for ( i = 0; i < p->num_concealed; i++ ) {
	if ( i > 0 ) strcat(tiles," ");
	strcat(tiles,tile_code(p->concealed[i]));
      }
      pfcssm.tiles = tiles;

      if ( handle_cmsg(the_game,&pfcssm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }
      check_min_time(1);
      send_all(the_game,&pfcssm);
      send_infotiles(p);
      /* do scoring if we've finished */
      if ( pflag(p,HandDeclared) ) score_hand(the_game,seat);
      return;
    } /* end of case PMsgFormClosedSpecialSet */
  case PMsgFormClosedPung:
    {
      PMsgFormClosedPungMsg *m = (PMsgFormClosedPungMsg *) pmp;
      CMsgPlayerFormsClosedPungMsg pfcpm;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pfcpm.type = CMsgPlayerFormsClosedPung;
      pfcpm.id = id;
      pfcpm.tile = m->tile;

      if ( handle_cmsg(the_game,&pfcpm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }

      check_min_time(1);
      send_all(the_game,&pfcpm);
      send_infotiles(p);
      /* do scoring if we've finished */
      if ( pflag(p,HandDeclared) ) score_hand(the_game,seat);
      return;
    } /* end of case PMsgFormClosedPung */
  case PMsgFormClosedChow:
    {
      PMsgFormClosedChowMsg *m = (PMsgFormClosedChowMsg *) pmp;
      CMsgPlayerFormsClosedChowMsg pfccm;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pfccm.type = CMsgPlayerFormsClosedChow;
      pfccm.id = id;
      pfccm.tile = m->tile;
	
      if ( handle_cmsg(the_game,&pfccm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }

      check_min_time(1);
      send_all(the_game,&pfccm);
      send_infotiles(p);
      /* do scoring if we've finished */
      if ( pflag(p,HandDeclared) ) score_hand(the_game,seat);
      return;
    } /* end of case PMsgFormClosedChow */
  case PMsgKong:
    {
      PMsgKongMsg *m = (PMsgKongMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgPlayerClaimsKongMsg pckm;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pckm.type = CMsgPlayerClaimsKong;
      pckm.id = id;
      pckm.discard = m->discard;
      if ( handle_cmsg(the_game,&pckm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }
      send_all(the_game,&pckm);
      /* if all claims received, process */
      check_claims(the_game);
      return;
    } /* end of case PMsgKong */
  case PMsgChow:
    {
      PMsgChowMsg *m = (PMsgChowMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgPlayerClaimsChowMsg pccm;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pccm.type = CMsgPlayerClaimsChow;
      pccm.id = id;
      pccm.discard = m->discard;
      pccm.cpos = m->cpos;

      if ( the_game->state == Discarded ) {
	/* special case: if chowpending is set, then this claim should
	   be to specify the previously unspecified position
	   after we've told the player that its claim has
	   succeeded.
	   So implement the chow and announce */
	if ( the_game->chowpending ) {
	  CMsgPlayerChowsMsg pcm;
	  
	  pcm.type = CMsgPlayerChows;
	  pcm.id = id;
	  pcm.tile = the_game->tile;
	  pcm.cpos = m->cpos;
	  if ( handle_cmsg(the_game,&pcm) < 0 ) {
	    em.error = the_game->cmsg_err;
	    send_id(id,&em);
	    return;
	  }
	  check_min_time(1);
	  send_all(the_game,&pcm);
	  return;
	}
	if ( handle_cmsg(the_game,&pccm) < 0 ) {
	  em.error = the_game->cmsg_err;
	  send_id(id,&em);
	  return;
	}
	send_all(the_game,&pccm);
	/* if all claims received, process */
	check_claims(the_game);
	return;
      } else { /* This had better be mahjonging */
	CMsgPlayerChowsMsg pcm;

	pcm.type = CMsgPlayerChows;
	pcm.id = id;
	pcm.tile = the_game->tile;
	pcm.cpos = m->cpos;
	if ( handle_cmsg(the_game,&pcm) < 0 ) {
	  em.error = the_game->cmsg_err;
	  send_id(id,&em);
	  return;
	}
	/* if any pos, just tell the player */
	if ( m->cpos == AnyPos ) {
	  send_id(id,&pcm);
	} else {
	  check_min_time(1);
	  send_all(the_game,&pcm);
	  send_infotiles(p);
	  /* if that came from a dangerous discard, tell the other players */
	  if ( game_flag(the_game,GFDangerousDiscard) ) {
	    CMsgDangerousDiscardMsg ddm;
	    ddm.type = CMsgDangerousDiscard;
	    ddm.id = the_game->players[the_game->supplier]->id;
	    ddm.discard = the_game->serial;
	    ddm.nochoice = game_flag(the_game,GFNoChoice);
	    send_all(the_game,&ddm);
	  }
	  if ( pflag(p,HandDeclared) ) score_hand(the_game,seat);
	}
	return;
      }
    } /* end of case PMsgChow */
  case PMsgDeclareWashOut:
    {
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      /* at present, we don't have any rules allowing a player
	 to declare a washout */
      em.error = "Can't declare a Wash-Out";
      send_id(id,&em);
      return;
    } /* end of case PMsgDeclareWashOut */
  case PMsgMahJong:
    {
      PMsgMahJongMsg *m = (PMsgMahJongMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgPlayerClaimsMahJongMsg pcmjm;
      CMsgPlayerMahJongsMsg pmjm;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;
      pcmjm.type = CMsgPlayerClaimsMahJong;
      pcmjm.id = id;
      pmjm.type = CMsgPlayerMahJongs;
      pmjm.id = id;

      if ( the_game->state == Discarded
	   || ((the_game->state == Discarding
		|| the_game->state == DeclaringSpecials)
	       && the_game->konging ) ) {
	pcmjm.discard = m->discard;
	if ( handle_cmsg(the_game,&pcmjm) < 0 ) {
	  em.error = the_game->cmsg_err;
	  send_id(id,&em);
	  return;
	}
	send_all(the_game,&pcmjm);
	/* if all claims received, process */
	check_claims(the_game);
	return;
      } else { /* this should be discarding */
	pmjm.tile = the_game->tile; /* that's the tile drawn */
	if ( handle_cmsg(the_game,&pmjm) < 0 ) {
	  em.error = the_game->cmsg_err;
	  send_id(id,&em);
	  return;
	}
	send_all(the_game,&pmjm);
	/* the players will now start declaring their hands */
	return;
      }
    } /* end of case PMsgMahJong */
  case PMsgDeclareClosedKong:
    {
      PMsgDeclareClosedKongMsg *m = (PMsgDeclareClosedKongMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgPlayerDeclaresClosedKongMsg pdckm;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      pdckm.id = id;
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      pdckm.type = CMsgPlayerDeclaresClosedKong;
      em.error = NULL;

      pdckm.tile = m->tile;
      pdckm.discard = the_game->serial+1;

      if ( handle_cmsg(the_game,&pdckm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }

      check_min_time(1);
      send_all(the_game,&pdckm);
      send_infotiles(p);

      /* now we need to wait for people to try to rob the kong */
      timeout = 1000*timeout_time;
      return;

    } /* end of case PMsgDeclareClosedKong */
  case PMsgAddToPung:
    {
      PMsgAddToPungMsg *m = (PMsgAddToPungMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgPlayerAddsToPungMsg patpm;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      patpm.id = id;
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      patpm.type = CMsgPlayerAddsToPung;
      em.error = NULL;

      patpm.tile = m->tile;
      patpm.discard = the_game->serial+1;
      if ( handle_cmsg(the_game,&patpm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }

      check_min_time(1);
      send_all(the_game,&patpm);
      send_infotiles(p);

      /* now we need to wait for people to try to rob the kong */
      timeout = 1000*timeout_time;
      return;

      assert(0);
    } /* end of case PMsgAddToPung */
  case PMsgQueryMahJong:
    {
      PMsgQueryMahJongMsg *m = (PMsgQueryMahJongMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgCanMahJongMsg cmjm;
      MJSpecialHandFlags mjf;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      cmjm.type = CMsgCanMahJong;
      cmjm.tile = m->tile;
      mjf = 0;
      if ( (int)game_get_option_value(the_game,GOSevenPairs,NULL) )
	mjf |= MJSevenPairs;
      cmjm.answer = player_can_mah_jong(p,m->tile,mjf);
      send_id(id,&cmjm);
      return;
    }
  case PMsgShowTiles:
    {
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgPlayerShowsTilesMsg pstm;

      id = cnx_to_id(cnx);
      p = id_to_player(id);
      seat = id_to_seat(id);

      /* fill in basic fields of possible replies */
      pstm.id = id;
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      pstm.type = CMsgPlayerShowsTiles;
      em.error = NULL;

      /* if there are no concealed tiles, just ignore the message;
	 this can only happen from the mahjonging player or by duplication */
      if ( p->num_concealed > 0 ) {
	char tiles[100];
	int i;
	
	tiles[0] = '\000';
	for ( i = 0; i < p->num_concealed; i++ ) {
	  if ( i > 0 ) strcat(tiles," ");
	  strcat(tiles,tile_code(p->concealed[i]));
	}
	pstm.tiles = tiles;
	if ( handle_cmsg(the_game,&pstm) < 0 ) {
	  em.error = the_game->cmsg_err;
	  send_id(id,&em);
	  return;
	}
	check_min_time(1);
	send_all(the_game,&pstm);
	score_hand(the_game,seat);
	return;
      }
      return;
    } /* end of case PMsgShowTiles */
  case PMsgSetGameOption:
    {
      PMsgSetGameOptionMsg *m = (PMsgSetGameOptionMsg *)pmp;
      PlayerP p; int id;
      CMsgErrorMsg em;
      CMsgGameOptionMsg gom;
      GameOptionEntry *goe;

      id = cnx_to_id(cnx);

      /* fill in basic fields of possible replies */
      gom.type = CMsgGameOption;
      gom.id = id;
      p = id_to_player(id);
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      /* do we have the option ? */
      goe = game_get_option_entry(the_game,GOUnknown,m->optname);

      if ( ! goe ) {
	em.error = "Trying to set unknown option";
	send_id(id,&em);
	return;
      }
      /* if the option is actually unknown or end, ignore it */
      if ( goe->option == GOUnknown || goe->option == GOEnd ) break;

      if ( goe->enabled == 0 ) {
	em.error = "Option not available in this game";
	send_id(id,&em);
	return;
      }

      gom.optentry = *goe;

      switch ( goe->type ) {
      case GOTBool:
	if ( sscanf(m->optvalue,"%d",&gom.optentry.value.optbool) == 0 ) {
	  em.error = "No boolean value found for option";
	  send_id(id,&em);
	  return;
	}
	if ( gom.optentry.value.optbool != 0 
	     && gom.optentry.value.optbool != 1 ) {
	  em.error = "No boolean value found for option";
	  send_id(id,&em);
	  return;
	}
	break;
      case GOTNat:
	if ( sscanf(m->optvalue,"%u",&gom.optentry.value.optnat) == 0 ) {
	  em.error = "No integer value found for option";
	  send_id(id,&em);
	  return;
	}
	break;
      case GOTInt:
	if ( sscanf(m->optvalue,"%d",&gom.optentry.value.optint) == 0 ) {
	  em.error = "No integer value found for option";
	  send_id(id,&em);
	  return;
	}
	break;
      case GOTScore:
	if ( sscanf(m->optvalue,"%d",&gom.optentry.value.optscore) == 0 ) {
	  em.error = "No score value found for option";
	  send_id(id,&em);
	  return;
	}
	break;
      case GOTString:
	strmcpy(gom.optentry.value.optstring,
            m->optvalue,
            sizeof(gom.optentry.value));
	break;
      }

      /* specific validity checking not done by handle_cmsg */
      if ( gom.optentry.option == GOTimeout
	   && gom.optentry.value.optint < 0 ) {
	em.error = "Can't set negative timeout!";
	send_id(id,&em);
	return;
      }

      if ( handle_cmsg(the_game,&gom) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
      }
      send_all(the_game,&gom);
      if ( gom.optentry.option == GOTimeout
	   || gom.optentry.option == GOTimeoutGrace ) {
	timeout_time = get_timeout_time(the_game,localtimeouts);
      }
      break;
    }
  case PMsgQueryGameOption:
    {
      PMsgQueryGameOptionMsg *m = (PMsgQueryGameOptionMsg *)pmp;
      int id;
      CMsgErrorMsg em;
      CMsgGameOptionMsg gom;
      GameOptionEntry *goe;

      id = cnx_to_id(cnx);

      /* fill in basic fields of possible replies */
      gom.type = CMsgGameOption;
      gom.id = 0;
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      goe = game_get_option_entry(the_game,GOUnknown,m->optname);
      if ( goe == NULL ) {
	em.error = "Option not known";
	send_id(id,&em);
	return;
      }
      gom.optentry = *goe;
      send_id(id,&gom);
      break;
    }
  case PMsgListGameOptions:
    {
      PMsgListGameOptionsMsg *m = (PMsgListGameOptionsMsg *)pmp;
      int id;
      CMsgGameOptionMsg gom;
      GameOptionEntry *goe;
      unsigned int i;

      id = cnx_to_id(cnx);

      /* fill in basic fields of possible replies */
      gom.type = CMsgGameOption;
      gom.id = 0;

      /* this relies on the fact that we know our option table
	 contains only known options in numerical order. This
	 would not necessarily be the case for clients, but it
	 is for us, since we don't allow unknown options to be set */
      for ( i = 1 ; i <= GOEnd ; i++ ) {
	goe = &the_game->option_table.options[i];
	if ( !goe->enabled && ! m->include_disabled ) continue;
	gom.optentry = *goe;
	send_id(id,&gom);
      }
      break;
    }
  case PMsgChangeManager:
    {
      PMsgChangeManagerMsg *m = (PMsgChangeManagerMsg *)pmp;
      int id;
      CMsgChangeManagerMsg cmm;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);

      /* fill in basic fields of possible replies */
      cmm.type = CMsgChangeManager;
      cmm.id = id;
      cmm.manager = m->manager;
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      if ( handle_cmsg(the_game,&cmm) < 0 ) {
	em.error = the_game->cmsg_err;
	send_id(id,&em);
	return;
      }
      send_all(the_game,&cmm);
      break;
    }
  case PMsgSendMessage:
    {
      PMsgSendMessageMsg *m = (PMsgSendMessageMsg *)pmp;
      int id;
      CMsgMessageMsg mm;
      CMsgErrorMsg em;

      id = cnx_to_id(cnx);

      mm.type = CMsgMessage;
      mm.sender = id;
      mm.addressee = m->addressee;
      mm.text = m->text;
      em.type = CMsgError;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      if ( mm.addressee == 0 ) {
	send_all(the_game,&mm);
      } else {
	if ( id_to_cnx(mm.addressee) < 0 ) {
	  em.error = "Addressee not found in game";
	  send_id(id,&em);
	  return;
	} else {
	  send_id(mm.addressee,&mm);
	}
      }
      break;
    }
  case PMsgSwapTile:
    {
      PMsgSwapTileMsg *m = (PMsgSwapTileMsg *) pmp;
      PlayerP p; int id; seats seat;
      CMsgErrorMsg em;
      CMsgSwapTileMsg stm;
      int i;

      id = cnx_to_id(cnx);

      /* fill in basic fields of possible replies */
      stm.type = CMsgSwapTile;
      stm.id = m->id;
      stm.oldtile = m->oldtile;
      stm.newtile = m->newtile;
      p = id_to_player(stm.id);
      seat = id_to_seat(stm.id);
      em.type = CMsgError ;
      em.seqno = connections[cnx].seqno;
      em.error = NULL;

      if ( p == NULL ) {
	em.error = "SwapTile: no such player";
	send_id(id,&em);
	return;
      }

      /* find the new tile in the wall. Because this is only used
	 for debugging and testing, we don't care that we're diving
	 inside the game structure!
	 Look for the tile from the end, so as to avoid depleting
	 the early wall.
      */
      for ( i = the_game->wall.dead_end-1 ;
	    the_game->wall.tiles[i] != m->newtile 
	      && i >= the_game->wall.live_used ;
	    i-- ) ;
      if ( i < the_game->wall.live_used ) em.error = "No new tile in wall";
      else {
	if ( handle_cmsg(the_game,&stm) < 0 ) {
	  em.error = the_game->cmsg_err;
	} else {
	  send_id(stm.id,&stm);
	  the_game->wall.tiles[i] = stm.oldtile;
	}
      }
      if ( em.error )
	send_id(id,&em);
      return;
    } /* end of case PMsgSwapTile */
  }
}



/* setup_maps: we need to be able to map between connections,
   player structures, and player ids.
   player to id is in the player structure, so we need the others.
   It's a pity we can't declare private variables here.
*/

/* set up data for a new connection */
static int new_connection(SOCKET skt) {
  int i;

  for (i= 0; i < MAX_CONNECTIONS; i++) {
    if ( connections[i].inuse ) continue;
    connections[i].inuse = 1;
    connections[i].skt = skt;
    connections[i].player = NULL;
    connections[i].seqno = 0;
    /* add to the event set */
    FD_SET(skt,&event_fds);
    return i;
  }
  warn("No space for new connection");
  return -1;
}

/* close connection */
static int close_connection(int cnx) {
  if ( connections[cnx].player ) {
    /* clear maps and decrement counter */
    remove_from_maps(cnx);
    num_connected_players--;
  }
  FD_CLR(connections[cnx].skt,&event_fds);
  closesocket(connections[cnx].skt);
  connections[cnx].inuse = 0;
  return 1;
}
static int cnx_to_id(int cnx) {
  PlayerP p;

  p = connections[cnx].player;
  return p ? p->id : -1;
}

static int id_to_cnx(int id) {
  int i;

  i = 0;
  while ( i < MAX_CONNECTIONS ) {
    if ( connections[i].inuse
	 && connections[i].player
	 && connections[i].player->id == id ) return i;
    i++;
  }
  return -1;
}

static PlayerP id_to_player(int id) {
  int f;

  f = id_to_cnx(id);
  if ( f < 0 ) return NULL;
  return connections[f].player;
}

static void setup_maps(int cnx, PlayerP p) {
  connections[cnx].player = p;
}

static void remove_from_maps(int cnx) {
  connections[cnx].player = (PlayerP) 0;
}

/* send_packet: send the given packet out on the given cnx, perhaps logging */
static void send_packet(int cnx,CMsgMsg *m, int logit) {
  char *l;

  if ( cnx < 0 ) return;

  l = encode_cmsg(m);
  if ( l == NULL ) {
    /* this shouldn't happen */
    warn("send_packet: protocol conversion failed");
    /* in fact, it so much shouldn't happen that we'll dump core */
    assert(0);
    return;
  }
  if ( logit && logfile ) {
    fprintf(logfile,">cnx%d %s",cnx,l);
    fflush(logfile);
  }
  if ( put_line(connections[cnx].skt,l) < 0 ) {
    warn("send_packet: write on cnx %d failed",cnx);
    /* maybe we should shutdown the descriptor here? */
    return;
  }
}

/* send player id a packet. Maybe log it.
   Enter the packet into the player's history, if appropriate */
static void _send_id(int id,CMsgMsg *m,int logit) {
  int cnx = id_to_cnx(id);
  if ( cnx < 0 ) return;
  send_packet(cnx,m,logit);
  if ( usehist && logit && the_game->active ) {
    history_add(the_game,m);
  } 
}

/* send to all players in a game, logging one copy */
static void _send_all(Game *g,CMsgMsg *m) {
  _send_id(g->players[east]->id,m,1);
  _send_id(g->players[south]->id,m,0);
  _send_id(g->players[west]->id,m,0);
  _send_id(g->players[north]->id,m,0);
}

/* send to all players in a game EXCEPT the id. Don't log it. */
static void _send_others(Game *g, int id,CMsgMsg *m) {
  if ( g->players[east]->id != id ) _send_id(g->players[east]->id,m,0);
  if ( g->players[south]->id != id ) _send_id(g->players[south]->id,m,0);
  if ( g->players[west]->id != id ) _send_id(g->players[west]->id,m,0);
  if ( g->players[north]->id != id ) _send_id(g->players[north]->id,m,0);
}

/* send to a particular seat in a game. Logit. */
static void _send_seat(Game *g, seats s, CMsgMsg *m) {
  _send_id(g->players[s]->id,m,1);
}

/* send to seats other than s.
   Don't log it: a more informative copy will have gone to
   another player. */
static void _send_other_seats(Game *g, seats s, CMsgMsg *m) {
  seats i;
  for ( i = 0 ; i < NUM_SEATS ; i++ )
    if ( i != s ) _send_id(g->players[i]->id,m,0);
}


/* finish the game: send GameOver message, and print scores */
static void finish_game(Game *g) {
  seats i,j;
  CMsgGameOverMsg gom;
  gom.type = CMsgGameOver;
  send_all(g,&gom);
  fprintf(stdout,"Game over. Final scores:\n");
  /* May as well print these in the order of original easts */
  for (i=0;i<NUM_SEATS;i++) {
    j = (i+1)%NUM_SEATS;
    fprintf(stdout,"%5d (%-20s)  %5d\n",
      g->players[j]->id,
      g->players[j]->name,
      g->players[j]->cumulative_score);
  }
#ifdef WIN32
  sleep(10); /* give the client time to close the connection */
#endif
  exit(0);
}

/* start_hand: start a new hand.
   The game should be in state HandComplete.
   Send a NewHand message to each player.
   Shuffle and build the new wall.
   Deal the initial tiles to each player.
   Draw east's 14th tile.
   Enter state DeclaringSpecials, with player set to east.

   Return 1 on success.
   On error, return 0, and put human readable explanation in
   global variable failmsg.
*/

static int start_hand(Game *g) {
  int stack,wall;
  CMsgNewHandMsg cm;

  cm.type = CMsgNewHand;

  if ( g->state != HandComplete ) {
    failmsg = "start_hand called when hand not complete.";
    return 0;
  }

  save_state_hack = 0; /* see explanation by variable declaration */

  cm.east = g->players[east]->id; /* assume no change */

  /* Does the deal rotate? */
  if ( g->player != noseat /* there was a mah jong */
       && (g->player != east /* and either it wasn't east */
	   || g->hands_as_east == 13)) { /* or this was east's 13th win */
    
    /* does the round change? (the current south will be the next east;
       if that is the firsteast, the round changes) */
    if ( g->players[south]->id == g->firsteast ) {
      CMsgNewRoundMsg nrm;
      
      if ( g->round == NorthWind ) {
	finish_game(g);
      }
      nrm.round = next_wind(g->round);
      nrm.type = CMsgNewRound;
      handle_cmsg(g,&nrm);
      send_all(g,&nrm);
    }
    /* rotate the seats. The new east is the current south */
    cm.east = g->players[south]->id;
  }

  /* we haven't yet processed the newhand message */

  clear_history(g);

  /* now set up the prehistory: game message and options */
  {
    CMsgGameMsg gamemsg;
    CMsgGameOptionMsg gom;
    GameOptionEntry *goe;
    int i;
 
    gamemsg.type = CMsgGame;
    gamemsg.east = g->players[east]->id;
    gamemsg.south = g->players[south]->id;
    gamemsg.west = g->players[west]->id;
    gamemsg.north = g->players[north]->id;
    gamemsg.round = g->round;
    gamemsg.hands_as_east = g->hands_as_east;
    gamemsg.firsteast = g->firsteast;
    gamemsg.east_score = g->players[east]->cumulative_score;
    gamemsg.south_score = g->players[south]->cumulative_score;
    gamemsg.west_score = g->players[west]->cumulative_score;
    gamemsg.north_score = g->players[north]->cumulative_score;
    gamemsg.protversion = g->protversion;
    gamemsg.manager = g->manager;

    gextras(g)->prehistory[gextras(g)->prehistcount++] = cmsg_deepcopy((CMsgMsg *)&gamemsg);
   
    gom.type = CMsgGameOption;
    gom.id = 0;
  
    /* this relies on the fact that we know our option table
       contains only known options in numerical order. This
       would not necessarily be the case for clients, but it
       is for us, since we don't allow unknown options to be set */
    for ( i = 1 ; i <= GOEnd ; i++ ) {
      goe = &g->option_table.options[i];
      gom.optentry = *goe;
      gextras(g)->prehistory[gextras(g)->prehistcount++] = cmsg_deepcopy((CMsgMsg *)&gom);
    }
  }

  /* process and send a new hand msg */
  if ( wallfilename ) {
    if ( load_wall(wallfilename,g) == 0 ) {
      warn("Unable to load wall");
      exit(1);
    }
  } else {
    /* set up the wall. Should this be done by the game routine?
       I think not, on the whole. */
    random_tiles(g->wall.tiles,(int)game_get_option_value(g,GOFlowers,NULL));
  }
  /* we're also supposed to choose the place where the deal starts.
     Just for fun, we'll follow the real procedure. */
  wall = 1+rand_index(5) + 1+rand_index(5);
  stack = wall + 1+rand_index(5) + 1+rand_index(5);
  stack++; /* the dice give the end of the dead wall */
  if ( stack > (g->wall.size/NUM_SEATS)/2 ) {
    stack -= (g->wall.size/NUM_SEATS)/2;
    wall++;
  }

  cm.start_wall = (wall-1) % NUM_SEATS;
  cm.start_stack = stack -1; /* convert from 1 counting to 0 counting */
  if ( handle_cmsg(g,&cm) < 0 ) {
    warn("handle_cmsg of NewHand message return error; dumping core");
    abort();
    }
  send_all(g,&cm);
  
  /* deal out the tiles into deal messages.
     We will actually deal in the traditional way: if we ever get
     round to implementing a semi-random shuffle, instead of a really
     random re-deal, this will make a difference.
  */
  { CMsgPlayerDrawsMsg pdm;
  int i,j;
  seats s;
  pdm.type = CMsgPlayerDraws;

  for ( j=0; j < 3; j++ ) {
    for ( s=east; s<=north; s++) {
      check_min_time(1);
      pdm.id = g->players[s]->id;
      for ( i = 0; i < 4; i++ ) {
	pdm.tile = game_draw_tile(g);
	send_id(pdm.id,&pdm);
	player_draws_tile(g->players[s],pdm.tile);
	pdm.tile = HiddenTile;
	send_others(g,pdm.id,&pdm);
      }
    }
  }
  for ( s=east; s<=north; s++) {
    check_min_time(1);
    pdm.id = g->players[s]->id;
    pdm.tile = game_draw_tile(g);
    send_id(pdm.id,&pdm);
    player_draws_tile(g->players[s],pdm.tile);
    pdm.tile = HiddenTile;
    send_others(g,pdm.id,&pdm);
  }
  /* at this point, we should copy east to the caller slot in case
     it wins with heaven's blessing; otherwise scoring.c will be
     unhappy. (Yes, this happened.) */
  copy_player(gextras(g)->caller,g->players[east]);

  s=east;
  pdm.id = g->players[s]->id;
  pdm.tile = game_draw_tile(g);
  check_min_time(1);
  send_id(pdm.id,&pdm);
  player_draws_tile(g->players[s],pdm.tile);
  pdm.tile = HiddenTile;
  send_others(g,pdm.id,&pdm);
  }

  /* send out info messages */
  send_infotiles(g->players[east]);
  send_infotiles(g->players[south]);
  send_infotiles(g->players[west]);
  send_infotiles(g->players[north]);

  /* Enter the next state and return */
  g->state = DeclaringSpecials;
  g->player = east;
  return 1;
}



/* timeout_handler: force no claims to be sent, and
   then check claims */
static void timeout_handler(Game *g) {
  seats i;
  CMsgPlayerDoesntClaimMsg pdcm;

  if ( g->state != Discarded
       && ! ( g->state == Discarding && g->konging ) ) {
    warn("timeout_handler called in unexpected state");
    return;
  }

  pdcm.type = CMsgPlayerDoesntClaim;
  pdcm.discard = g->serial;
  pdcm.timeout = 1;
  for ( i=0; i < NUM_SEATS; i++ ) {
    if ( i == g->player ) continue;
    if ( g->claims[i] != UnknownClaim ) continue;
    pdcm.id = g->players[i]->id;
    handle_cmsg(g,&pdcm);
    send_id(pdcm.id,&pdcm);
  }
  check_claims(g);
}


/* check_claims: when a player makes a claim on the discard,
   (or tries to rob a kong)
   we need to check whether all claims have been lodged, and
   if so, process them. This function does that */

static void check_claims(Game *g) {
  seats i, s, ds;
  CMsgClaimDeniedMsg cdm;

  if ( g->state != Discarded
       && ! ( (g->state == Discarding 
	       || g->state == DeclaringSpecials) 
	      && g->konging ) ) {
    warn("check_claims: called in wrong game state");
    return;
  }

  /* ds is the seat of the discarder/konger */
  ds = g->player;

  /* return if not all claims are lodged */
  for ( i = 0 ; i < NUM_SEATS ; i++ )
    if ( i != ds && g->claims[i] == UnknownClaim ) return;

  /* if we are in a chowpending state, return silently now: it must be
     a duplicate claim that triggered this */
  if ( g->chowpending ) {
    info("check_claim: Duplicate claim received, ignoring");
    return;
  }

  /* OK, process. First, cancel timeout */
  timeout = 0;

  /* s will be the successful claim */
  s = noseat ;
  /* is there a mah-jong? */
  for ( i = 0 ; i < NUM_SEATS ; i++ )
    if ( g->claims[(ds+i)%NUM_SEATS]
	  == MahJongClaim ) { s = (ds+i)%NUM_SEATS ; break ; }

  /* is there a kong? */
  if ( s == noseat )
    for ( i = 0 ; i < NUM_SEATS ; i++ )
      if ( g->claims[(ds+i)%NUM_SEATS]
	   == KongClaim ) { s = (ds+i)%NUM_SEATS ; break ; }

  /* is there a pung ? */
  if ( s == noseat )
    for ( i = 0 ; i < NUM_SEATS ; i++ )
      if ( g->claims[(ds+i)%NUM_SEATS]
	   == PungClaim ) { s = (ds+i)%NUM_SEATS ; break ; }
  
  /* or is there a chow? */
  if ( s == noseat )
    if ( g->claims[(ds+1)%NUM_SEATS]
	   == ChowClaim ) { s = (ds+1)%NUM_SEATS ; }

  /* finished checking; now process */

  if ( s == noseat ) {
    if ( g->state == Discarded ) {
      /* no claim; play passes to the next player, who draws */
      CMsgPlayerDrawsMsg m;
      s = (ds+1)%NUM_SEATS;
      m.type = CMsgPlayerDraws;
      m.id = g->players[s]->id;
      /* peek at the tile: we'll pass the CMsg to the game
	 to handle state changes */
      m.tile = game_peek_tile(g);
      
      if ( m.tile == ErrorTile ) {
	/* run out of wall; washout */
	washout(NULL);
	return;
      }
    
      /* stash a copy of the player, in case it goes mahjong */
      copy_player(gextras(g)->caller,g->players[s]);
      
      if ( handle_cmsg(g,&m) < 0 ) {
	warn("Consistency error drawing tile");
	abort();
      }
      check_min_time(1);
      send_seat(g,s,&m);
      m.tile = HiddenTile;
      send_other_seats(g,s,&m);
      send_infotiles(g->players[s]);
      return;
    } else {
      /* the player formed a kong, and (surprise) nobody tried to 
	 rob it */
      CMsgPlayerDrawsLooseMsg pdlm;

      pdlm.type = CMsgPlayerDrawsLoose;
      pdlm.id = g->players[ds]->id;
      /* find the loose tile. */
      pdlm.tile = game_peek_loose_tile(the_game);
      if ( pdlm.tile == ErrorTile ) {
	washout(NULL);
	return;
      }

      /* stash a copy of the player, in case it goes mahjong */
      copy_player(gextras(g)->caller,g->players[ds]);

      if ( handle_cmsg(the_game,&pdlm) < 0 ) {
	/* error should be impossible */
	warn("Consistency error: giving up");
	exit(1);
      }
      check_min_time(1);
      send_id(pdlm.id,&pdlm);
      pdlm.tile = HiddenTile;
      send_others(the_game,pdlm.id,&pdlm);
      send_infotiles(g->players[ds]);
      return;
    }
  }

  if ( g->claims[s] == ChowClaim ) {
    /* there can be no other claims, so just implement this one */
    CMsgPlayerChowsMsg pcm;

    pcm.type = CMsgPlayerChows;
    pcm.id = g->players[s]->id;
    pcm.tile = g->tile;
    pcm.cpos = g->cpos;

    /* if the cpos is AnyPos, then we instruct the player (only)
       to send in another chow claim, and just wait for it */
    if ( pcm.cpos == AnyPos ) {
      if ( handle_cmsg(g,&pcm) < 0 ) {
	CMsgErrorMsg em;
	em.type = CMsgError;
	em.seqno = connections[id_to_cnx(pcm.id)].seqno;
	em.error = g->cmsg_err;
	send_id(pcm.id,&em);
	return;
      }
      send_id(pcm.id,&pcm);
      return;
    }

    /* stash a copy of the player, in case it goes mahjong */
    copy_player(gextras(g)->caller,g->players[s]);

    if ( handle_cmsg(g,&pcm) < 0 ) {
      warn("Consistency error: failed to implement claimed chow.");
      exit(1);
    }

    check_min_time(2);
    send_all(g,&pcm);
    send_infotiles(g->players[s]);
    /* if that came from a dangerous discard, tell the other players */
    if ( game_flag(the_game,GFDangerousDiscard) ) {
      CMsgDangerousDiscardMsg ddm;
      ddm.type = CMsgDangerousDiscard;
      ddm.discard = the_game->serial;
      ddm.id = g->players[g->supplier]->id;
      ddm.nochoice = game_flag(g,GFNoChoice);
      send_all(the_game,&ddm);
    }
    return;
  }

  /* In the remaining cases, there may be other claims; send
     denial messages to them */
  cdm.type = CMsgClaimDenied;
  cdm.reason = "There was a prior claim";
  
  for ( i = 0 ; i < NUM_SEATS ; i++ ) {
    if ( i != ds && i != s && g->claims[i] != NoClaim) {
      cdm.id = g->players[i]->id;
      send_id(cdm.id,&cdm);
    }
  }

  if ( g->claims[s] == PungClaim ) {
    CMsgPlayerPungsMsg ppm;

    ppm.type = CMsgPlayerPungs;
    ppm.id = g->players[s]->id;
    ppm.tile = g->tile;

    /* stash a copy of the player, in case it goes mahjong */
    copy_player(gextras(g)->caller,g->players[s]);

    if ( handle_cmsg(g,&ppm) < 0 ) {
      warn("Consistency error: failed to implement claimed pung.");
      exit(1);
    }

    check_min_time(2);
    send_all(g,&ppm);
    send_infotiles(g->players[s]);
    /* if that came from a dangerous discard, tell the other players */
    if ( game_flag(the_game,GFDangerousDiscard) ) {
      CMsgDangerousDiscardMsg ddm;
      ddm.type = CMsgDangerousDiscard;
      ddm.id = g->players[g->supplier]->id;
      ddm.discard = the_game->serial;
      ddm.nochoice = game_flag(g,GFNoChoice);
      send_all(the_game,&ddm);
    }
    return;
  }

  if ( g->claims[s] == KongClaim ) {
    CMsgPlayerKongsMsg pkm;
    CMsgPlayerDrawsLooseMsg pdlm;

    pdlm.type = CMsgPlayerDrawsLoose;
    pkm.type = CMsgPlayerKongs;
    pdlm.id = pkm.id = g->players[s]->id;
    pkm.tile = g->tile;

    if ( handle_cmsg(g,&pkm) < 0 ) {
      warn("Consistency error: failed to implement claimed kong.");
      exit(1);
    }

    check_min_time(2);
    send_all(g,&pkm);

    /* find the loose tile. */
    pdlm.tile = game_peek_loose_tile(g);
    if ( pdlm.tile == ErrorTile ) {
      washout(NULL);
      return;
    }

    /* stash a copy of the player, in case it goes mahjong */
    copy_player(gextras(g)->caller,g->players[s]);

    if ( handle_cmsg(the_game,&pdlm) < 0 ) {
      /* error should be impossible */
      warn("Consistency error: giving up");
      exit(1);
    }
    check_min_time(1);
    send_id(pdlm.id,&pdlm);
    pdlm.tile = HiddenTile;
    send_others(g,pdlm.id,&pdlm);
    send_infotiles(g->players[s]);
    return;
  }

  if ( g->claims[s] == MahJongClaim ) {
    /* stash a copy of the player before it grabs the discard */
    copy_player(gextras(g)->caller,g->players[s]);

    if ( g->state == Discarded ) {
      /* the normal situation */
      CMsgPlayerMahJongsMsg pmjm;
      
      pmjm.type = CMsgPlayerMahJongs;
      pmjm.id = g->players[s]->id;
      pmjm.tile = HiddenTile;
      
      if ( handle_cmsg(g,&pmjm) < 0 ) {
	/* this should be impossible */
	CMsgErrorMsg em;
	em.type = CMsgError;
	em.seqno = connections[id_to_cnx(pmjm.id)].seqno;
	em.error = g->cmsg_err;
	send_id(pmjm.id,&em);
	return;
      }
      send_all(g,&pmjm);
      return;
    } else {
      /* the kong's been robbed */
      CMsgPlayerRobsKongMsg prkm;

      prkm.type = CMsgPlayerRobsKong;
      prkm.id = g->players[s]->id;
      prkm.tile = g->tile;

      if ( handle_cmsg(g,&prkm) < 0 ) {
	/* this should be impossible */
		CMsgErrorMsg em;
	em.type = CMsgError;
	em.seqno = connections[id_to_cnx(prkm.id)].seqno;
	em.error = g->cmsg_err;
	send_id(prkm.id,&em);
	return;
      }
      check_min_time(2);
      send_all(g,&prkm);
      return;
    }
  }

  /* NOTREACHED */
}


/* This function sends an InfoTiles message about the given player
   to all players who are receiving info tiles */
static void send_infotiles(PlayerP p) {
  static CMsgInfoTilesMsg itm;
  PlayerP q;
  static char buf[128];
  int i;

  itm.type = CMsgInfoTiles;
  itm.id = p->id;
  if ( popts(p)[POInfoTiles] ) {
    player_print_tiles(buf,p,0);
    itm.tileinfo = buf;
    send_id(itm.id,&itm);
  }
  player_print_tiles(buf,p,1);
  for ( i = 0 ; i < NUM_SEATS ; i++ ) {
    q = the_game->players[i];
    if ( q != p && popts(q)[POInfoTiles] ) {
      send_id(q->id,&itm);
    }
  }
}


/* Save state in the file.
   The state is saved as a sequence of CMsgs.
   First, four Players;
   then a Game;
   then GameOptions;
   then if a hand is in progress,
   Wall
   NewHand 
   the history of the hand.
*/
static char *save_state(Game *g, char *filename) {
  int fd;
  int i,j; /* unsigned to suppress warnings */
  static char gfile[512]; 
  CMsgGameMsg gamemsg;
  CMsgGameOptionMsg gom;
  GameOptionEntry *goe;
  
  if ( filename && filename[0] ) {
    char *f;
    /* strip any directories, for security */
    f = strrchr(filename,'/');
    if ( f ) filename = f+1;
    f = strrchr(filename,'\\');
    if ( f ) filename = f+1;
    strmcpy(gfile,filename,500);
    /* if it doesn't already end with .mjs, add it */
    if ( strlen(gfile) < 4 || strcmp(gfile+strlen(gfile)-4,".mjs") ) {
      strcat(gfile,".mjs");
    }
  } else {
    /* if we have no name already in use, construct one */
    if ( gfile[0] == 0 ) {
      if ( loadfilename[0] ) {
	strmcpy(gfile,loadfilename,510);
      } else {
	struct tm *ts;
	time_t t;
	int i;
	struct stat junk;
	t = time(NULL);
	ts = localtime(&t);
	i = 0;
	while ( i < 10 ) {
	  sprintf(gfile,"game-%d-%02d-%02d-%d.mjs",
	    ts->tm_year+1900,ts->tm_mon+1,ts->tm_mday,i);
	  if ( stat(gfile,&junk) != 0 ) break;
	  i++;
	}
      }
    }
  }
  fd = open(gfile,O_WRONLY|O_CREAT|O_TRUNC,0777);
  if ( fd < 0 ) {
    warn("Unable to write game state file: %s",strerror(errno));
    return 0;
  }
  for ( i = 0; i < NUM_SEATS; i++ ) {
    CMsgPlayerMsg pm;
    PlayerP q;
    
    q = g->players[i];
    if ( q->id == 0 ) continue;
    pm.type = CMsgPlayer;
    pm.id = q->id;
    pm.name = q->name;
    fd_put_line(fd,encode_cmsg((CMsgMsg *)&pm));
  }

  /* Normally, we write out a game message describing the current
     state of the game, and then the history. However, if this
     is the second time we've been called at the end of the same
     hand, we need to print the prehistory instead. */
  if ( g->state == HandComplete ) save_state_hack++;

  if ( save_state_hack > 1 ) {
    int j;
    for ( j=0; j < gextras(g)->prehistcount; j++ ) {
      fd_put_line(fd,encode_cmsg(gextras(g)->prehistory[j]));
    }
  } else {
    gamemsg.type = CMsgGame;
    gamemsg.east = g->players[east]->id;
    gamemsg.south = g->players[south]->id;
    gamemsg.west = g->players[west]->id;
    gamemsg.north = g->players[north]->id;
    gamemsg.round = g->round;
    gamemsg.hands_as_east = g->hands_as_east;
    gamemsg.firsteast = g->firsteast;
    gamemsg.east_score = g->players[east]->cumulative_score;
    gamemsg.south_score = g->players[south]->cumulative_score;
    gamemsg.west_score = g->players[west]->cumulative_score;
    gamemsg.north_score = g->players[north]->cumulative_score;
    gamemsg.protversion = g->protversion;
    gamemsg.manager = g->manager;
    
    fd_put_line(fd,encode_cmsg((CMsgMsg *)&gamemsg));
    
    gom.type = CMsgGameOption;
    gom.id = 0;
    
    /* this relies on the fact that we know our option table
       contains only known options in numerical order. This
       would not necessarily be the case for clients, but it
       is for us, since we don't allow unknown options to be set */
    for ( i = 1 ; i <= GOEnd ; i++ ) {
      goe = &g->option_table.options[i];
      gom.optentry = *goe;
      fd_put_line(fd,encode_cmsg((CMsgMsg *)&gom));
    }
  }

  /* We are saving state for resumption here, so we do not need
     to save the history of a complete hand */
  if ( g->state != HandComplete || save_state_hack > 1 ) {
    CMsgWallMsg wm;
    char wall[MAX_WALL_SIZE*3+1];
    wm.type = CMsgWall;
    wm.wall = wall;
    wall[0] = 0;
    for ( i = 0 ; i < g->wall.size ; i++ ) {
      if ( i ) strcat(wall," ");
      strcat(wall,tile_code(g->wall.tiles[i]));
    }
    fd_put_line(fd,encode_cmsg((CMsgMsg *)&wm));
  
    for ( j=0; j < gextras(g)->histcount; j++ ) {
      fd_put_line(fd,encode_cmsg(gextras(g)->history[j]));
    }
  }

  close(fd);
  return gfile;
}

/* Load the state into the (pre-allocated) game pointed to by g.
   N.B. The player structures must also be allocated.
*/
static int load_state(Game *g) {
  int fd;
  char *l;
  CMsgMsg *m;
  int manager = 0;

  fd = open(loadfilename,O_RDONLY);
  if ( fd < 0 ) {
    warn("unable to open game state file: %s",strerror(errno));
    return 0;
  }
  
  clear_history(g);
  g->cmsg_check = 1;
  while ( (l = fd_get_line(fd)) ) {
    m = decode_cmsg(l);
    if ( ! m ) {
      warn("Bad cmsg in game state file, line %s",l);
      return 0;
    }
    if ( game_handle_cmsg(g,m) < 0 ) {
      warn("Error handling cmsg: line %s, error %s",l,g->cmsg_err);
      return 0;
    }
    /* if the game has a manager, clear it temporarily, so that
       the gameoptions we're about to process do get processed */
    if ( m->type == CMsgGame ) {
      manager = g->manager;
      g->manager = 0;
    }
    history_add(g,m);
  }

  /* reinstate manager */
  g->manager = manager;
  close(fd);
  /* We need to copy the timeout option value from the resumed game */
  timeout_time = get_timeout_time(g,localtimeouts);
  return 1;
}

/* This function is responsible for handling the scoring.
   It is called in the following circumstances:
   The mahjonging player has made all their sets, or
   a non-mahjonging player has issued a ShowTiles message
   (the showing of the tiles will already have been done).
   It then (a) computes the score for the hand, together
   with a text description of the computation, and announces
   it.
   (b) if all players are now declared, computes the settlements,
   announces the net change for each player, together with
   a text description of the calculation; implements the settlements;
   and moves to the state HandComplete, incrementing hands_as_east
   if necessary.
   If the game is being terminated early because of disconnect,
   it will finish the game at Settlement.
   Arguments: g is the game, s is the *seat* of the player on
   which something has happened.
*/
static void score_hand(Game *g, seats s) {
  PlayerP p = g->players[s];
  Score score;
  char buf[1000], tmp[100];
  static char *seatnames[] = { "East ", "South", "West ", "North" };
  static int changes[NUM_SEATS];
  CMsgHandScoreMsg hsm;
  CMsgSettlementMsg sm;
  seats i,j;
  int m;
  int cannon=0;
  seats cannoner = noseat;
  bool eastdoubles;
  bool loserssettle;
  bool discarderdoubles;

  buf[0] = 0;
  score = score_of_hand(g,s);
  hsm.type = CMsgHandScore;
  hsm.id = p->id;
  hsm.score = score.value;
  hsm.explanation = score.explanation;

  send_all(g,&hsm);

  if ( s == g->player ) {
    psetflag(p,MahJongged);
  }
  set_player_hand_score(p,score.value);

  /* have we scored all the players ? */
  for (i=0; i < NUM_SEATS; i++)
    if ( g->players[i]->hand_score < 0 ) return;

  /* now compute the settlements. East pays and receives double, etc? */
  eastdoubles = (bool) game_get_option_value(g,GOEastDoubles,NULL);
  loserssettle = (bool) game_get_option_value(g,GOLosersSettle,NULL);
  discarderdoubles = (bool) game_get_option_value(g,GODiscDoubles,NULL);

  for ( i = 0; i < NUM_SEATS; i++ ) changes[i] = 0;

  /* first the winner; let's re-use s and p */
  s = g->player;
  p = g->players[s];

  /* Firstly, check to see if somebody let off a cannon. At this point,
     we assume we know that the dflags field is a bit field! */
  for ( i = 0; i < NUM_SEATS; i++ ) {
    if ( i == s ) continue;
    if ( p->dflags[i] & p->dflags[s] ) {
      /* Only one person can be liable, so let's have a little
	 consistency check */
      if ( cannon ) {
	warn("Two people found letting off a cannon!");
	exit(1);
      }
      cannon=1;
      cannoner=i;
    }
  }

  if ( cannon ) {
    sprintf(tmp,"%s let off a cannon\n\n",seatnames[cannoner]);
    strcat(buf,tmp);
  }
  for ( i = 0; i < NUM_SEATS; i++ ) {
    if ( i == s ) continue;
    m = g->players[s]->hand_score;
    if ( eastdoubles && i*s == 0 ) m *= 2; /* sneaky test for one being east */
    /* singaporean rules: discarder pays double, on self-draw
       (including loose - query, is this right?) everybody pays double */
    if ( discarderdoubles
      && (g->whence != FromDiscard
	|| i == g->supplier) ) m *= 2;
    changes[s] += m; changes[cannon ? cannoner : i] -= m;
    sprintf(tmp,"%s pays %s",seatnames[cannon ? cannoner : i],seatnames[s]);
    strcat(buf,tmp);
    if ( cannon && cannoner != i ) {
      sprintf(tmp," (for %s)",seatnames[i]);
      strcat(buf,tmp);
    }
    sprintf(tmp," %5d\n",m);
    strcat(buf,tmp);
  }
  sprintf(tmp,"%s GAINS %5d\n\n",seatnames[s],changes[s]);
  strcat(buf,tmp);

  /* and now the others */
  for ( i = 0; i < NUM_SEATS; i++ ) {
    if ( i == s ) continue;
    for ( j = i+1; j < NUM_SEATS; j++ ) {
      if ( j == s ) continue;
      if ( cannon ) continue;
      if ( ! loserssettle ) continue;
      m = g->players[i]->hand_score - g->players[j]->hand_score;
      if ( eastdoubles && i*j == 0 ) m *= 2;
      changes[i] += m; changes[j] -= m;
      if ( m > 0 ) {
	sprintf(tmp,"%s pays %s %5d\n",seatnames[j],seatnames[i],m);
      } else if ( m < 0 ) {
	sprintf(tmp,"%s pays %s %5d\n",seatnames[i],seatnames[j],-m);
      } else {
	sprintf(tmp,"%s and %s are even\n",seatnames[i],seatnames[j]);
      }
      strcat(buf,tmp);
    }
    sprintf(tmp,"%s %s %5d\n\n",seatnames[i],
	    changes[i] >= 0 ? "GAINS" : "LOSES",
	    abs(changes[i]));
    strcat(buf,tmp);
  }
  
  sm.type = CMsgSettlement;
  sm.east = changes[east];
  sm.south = changes[south];
  sm.west = changes[west];
  sm.north = changes[north];
  sm.explanation = buf;
  handle_cmsg(g,&sm);
  send_all(g,&sm);
  
  /* finish game if terminating on disconnect */
  if ( end_on_disconnect_in_progress ) finish_game(g);

  /* otherwise pause for the next hand */
  {
    CMsgPauseMsg pm;
    pm.type = CMsgPause;
    pm.exempt = 0;
    pm.requestor = 0;
    pm.reason = "to start next hand";
    handle_cmsg(g,&pm);
    send_all(g,&pm);
  }
}

/* implement washout. The argument is the reason for the washout;
   if NULL, the default reason of "wall exhausted" is assumed. */
static void washout(char *reason) {
  CMsgPauseMsg pm;
  CMsgWashOutMsg wom;
  wom.type = CMsgWashOut;
  if ( reason ) wom.reason = reason;
  else wom.reason = "wall exhausted";
  handle_cmsg(the_game,&wom);
  send_all(the_game,&wom);
  /* if ShowOnWashout is set, show all tiles */
  if ( (bool) game_get_option_value(the_game,GOShowOnWashout,NULL) ) {
    int i;
    PlayerP p;
    CMsgPlayerShowsTilesMsg pstm;
    
    /* fill in basic fields of possible replies */
    pstm.type = CMsgPlayerShowsTiles;
    
    for ( i = 0; i < NUM_SEATS; i++ ) {
      p = the_game->players[i];
      
      /* if there are no concealed tiles, skip */
      if ( p->num_concealed > 0 ) {
	char tiles[100];
	int j;
	
	tiles[0] = '\000';
	for ( j = 0; j < p->num_concealed; j++ ) {
	  if ( j > 0 ) strcat(tiles," ");
	  strcat(tiles,tile_code(p->concealed[j]));
	}
	pstm.id = p->id;
	pstm.tiles = tiles;
	if ( handle_cmsg(the_game,&pstm) < 0 ) {
	  warn("Error handling cmsg in ShowOnWashout: error %s",the_game->cmsg_err);
	  return;
	}
	check_min_time(1);
	send_all(the_game,&pstm);
      }
    }
  }
  /* and now pause for the next hand */
  pm.type = CMsgPause;
  pm.exempt = 0;
  pm.requestor = 0;
  pm.reason = "to start next hand";
  handle_cmsg(the_game,&pm);
  send_all(the_game,&pm);
}

/* called for an error on an cnx. Removes the cnx,
   suspends the game if appropriate, etc */
static void handle_cnx_error(int cnx) {
  CMsgStopPlayMsg spm;
  char emsg[100];
  int id;
  /* for the moment, die noisily. Ultimately, just notify
     other players, and re-open the listening socket */
  if ( connections[cnx].skt == socket_fd ) {
    /* hard to see how this could happen, but ... */
    warn("Exception condition on listening fd\n");
    exit(1);
  }
  warn("Exception/eof on cnx %d, player %d\n",cnx, cnx_to_id(cnx));
  spm.type = CMsgStopPlay;
  /* We clear the player's entry before sending the message
     so that it fails harmlessly on the player's file instead
     of writing to a broken pipe. */
  id = cnx_to_id(cnx);
  /* we need to keep the connection in the table for use below.
     This will cause some writes to broken pipes, but we're
     ignoring those anyway */
  if ( id >= 0 ) {
    /* if the game hasn't yet started, and all the players support
       the necessary protocol version, we do not need to exit;
       we can just delete the disconnecting player.
       Of course, we don't need the disconnecting player to support
       the necessary protocol version, but I can't be bothered to
       do that.
       However, I think if --exit-on-disconnect is given, we
       should exit anyway, since the purpose of that option is
       to stop unwanted servers hanging around.
    */
    if ( the_game->round == UnknownWind 
      && ! exit_on_disconnect
      && protocol_version > 1034 ) {
      CMsgPlayerMsg pm;
      pm.type = CMsgPlayer;
      pm.id = id;
      pm.name = NULL;
      handle_cmsg(the_game,&pm);
      close_connection(cnx);
      send_all(the_game,&pm);
      return;
    }
    sprintf(emsg,"Lost connection to player %d%s",
	    id,exit_on_disconnect ? "quitting" : loadstate ? "; game suspended" : "");
    spm.reason = emsg;
    if ( ! end_on_disconnect ) {
      send_all(the_game,&spm);
      the_game->active = 0;
    } else {
      int washed_out = 0;
      int dcpen = 0; /* apply disconnection penalty ? */
      CMsgMessageMsg mm;
      mm.type = CMsgMessage;
      mm.sender = mm.addressee = 0;
      mm.text = emsg;
      sprintf(emsg,"Lost connection to player %d - ",id);
      /* to handle disconnection gracefully ... */
      if ( the_game->state == HandComplete ) {
	/* nothing to do at this point */
	strcat(emsg,"game will end now");
      } else if ( the_game->state == MahJonging ) {
	PlayerP p;
	seats s;
	/* if it's the mahjonging player we've lost, and they
	   haven't yet declared their hand, I think that's
	   just tough -- we don't want to do auto-declaration */
	s = id_to_seat(id);
	p = id_to_player(id);
	if ( the_game->player == s && !pflag(p,HandDeclared) ) {
	  CMsgWashOutMsg wom;
	  wom.type = CMsgWashOut;
	  wom.reason = "Lost the winner";
	  washed_out = 1;
	  handle_cmsg(the_game,&wom);
	  send_all(the_game,&wom);
	  strcat(emsg,"ending game");
	} else {
	  PMsgShowTilesMsg stm;
	  /* we have to continue processing, since other players
	     may continue to declare tiles. We fake a showtiles
	     for this player, and handle the end of game later */
	  end_on_disconnect_in_progress = 1;
	  if ( !pflag(p,HandDeclared) ) {
	    stm.type = PMsgShowTiles;
	    handle_pmsg((PMsgMsg *)&stm,cnx);
	  }
	  strcat(emsg,"game will end after scoring this hand");
	}
      } else {
	/* not much we can do except declare a washout */
	CMsgWashOutMsg wom;
	wom.type = CMsgWashOut;
	wom.reason = "Lost a player";
	handle_cmsg(the_game,&wom);
	send_all(the_game,&wom);
	strcat(emsg,"ending game");
	washed_out = 1;
      }
      send_all(the_game,&mm);
      /* do we need to apply a disconnection penalty?
	 If the state is MahJonging, then it's morally the
	 same as HandComplete. Well, not if it's the winner
	 who dc'ed, but we'll quietly pass over that.
	 The washouts will have set handcomplete, so we must
	 apply the usual logic */
	/* are we at the end of a hand ? */
      /* If the game hasn't actually got under way, we won't charge
	 a penalty */
      if ( the_game->state == HandComplete
	&& the_game->round == EastWind
	&& the_game->players[east]->id == the_game->firsteast
	&& the_game->hands_as_east == 0
	   && ! washed_out ) {
	dcpen = 0;
      } else if ( (the_game->state == HandComplete
	     || the_game->state == MahJonging)
	/* It's a pain that I can't test for this easily
	   at the *end* of a hand. Have to duplicate logic
	   elsewhere */
	&& the_game->player != noseat /* there was a mah jong */ ) {
	/* are we at the end of a round? */
	if ( (the_game->player != east /* and either it wasn't east */
	   || the_game->hands_as_east == 13) /* or this was east's 13th win */
	  /* does the round change? (the current south will be the next east;
	     if that is the firsteast, the round changes) */
	  && the_game->players[south]->id == the_game->firsteast ) {
	  if ( the_game->round == NorthWind ) {
	    /* end of game. No penalty can apply */
	  } else {
	    dcpen = disconnect_penalty_end_of_round;
	  }
	} else {
	  /* in middle of round, but end of hand */
	  dcpen = disconnect_penalty_end_of_hand;
	}
      } else {
	dcpen = disconnect_penalty_in_hand;
      }
      if ( dcpen > 0 ) {
	info("Disconnect penalty for player %d: %d",id,dcpen);
	change_player_cumulative_score(id_to_player(id),-dcpen);
      }
      /* if we have nothing further to do, we should end the game */
      if ( ! end_on_disconnect_in_progress ) {
	finish_game(the_game);
      }
    }
    timeout = 0; /* clear timeout */
  }
  if ( exit_on_disconnect ) save_and_exit() ;
  /* and close the offending connection */
  close_connection(cnx);
}

/* loads a wall from a file; puts stack and wall of start in last two
   arguments */
static int load_wall(char *wfname, Game *g) {
  FILE *wfp;
  int i;
  char tn[5];
  Tile t;

  wfp = fopen(wfname,"r");
  if ( wfp == NULL ) {
    warn("couldn't open wall file");
    return 0;
  }
  for ( i = 0 ; i < g->wall.size ; i++ ) {
    fscanf(wfp,"%2s",tn);
    t = tile_decode(tn);
    if ( t == ErrorTile ) {
      warn("Error parsing wall file");
      return 0;
    }
    g->wall.tiles[i] = t;
  }
  return 1;
}

/* resend: given a player id and a message, send it to the player
   if appropriate, censoring as required. */
static void resend(int id, CMsgMsg *m)
{
  switch ( m->type ) {
    /* The following messages are always sent */
  case CMsgNewHand:
  case CMsgPlayerDeclaresSpecial:
  case CMsgPause:
  case CMsgPlayerReady:
  case CMsgPlayerDiscards:
  case CMsgDangerousDiscard:
  case CMsgPlayerClaimsPung:
  case CMsgPlayerPungs:
  case CMsgPlayerFormsClosedPung:
  case CMsgPlayerClaimsKong:
  case CMsgPlayerKongs:
  case CMsgPlayerDeclaresClosedKong:
  case CMsgPlayerAddsToPung:
  case CMsgPlayerRobsKong:
  case CMsgPlayerClaimsChow:
  case CMsgPlayerChows:
  case CMsgPlayerFormsClosedChow:
  case CMsgWashOut:
  case CMsgPlayerClaimsMahJong:
  case CMsgPlayerMahJongs:
  case CMsgPlayerPairs:
  case CMsgPlayerFormsClosedPair:
  case CMsgPlayerShowsTiles:
  case CMsgPlayerSpecialSet:
  case CMsgPlayerFormsClosedSpecialSet:
  case CMsgHandScore:
  case CMsgSettlement:
    send_id(id,m);
    break;
    /* The following messages are sent only to the player concerned */
  case CMsgPlayerDoesntClaim:
    if ( id == ((CMsgPlayerDoesntClaimMsg *)m)->id ) send_id(id,m);
    break;
  case CMsgSwapTile:
    if ( id == ((CMsgSwapTileMsg *)m)->id ) send_id(id,m);
    break;
    /* The following messages are sent as is to the player concerned,
       and with censoring to other players */
  case CMsgPlayerDraws:
    if ( id == ((CMsgPlayerDrawsMsg *)m)->id ) {
      send_id(id,m);
    } else {
      CMsgPlayerDrawsMsg mm = *(CMsgPlayerDrawsMsg *)m;
      mm.tile = HiddenTile;
      send_id(id,&mm);
    }
    break;
  case CMsgPlayerDrawsLoose:
    if ( id == ((CMsgPlayerDrawsLooseMsg *)m)->id ) {
      send_id(id,m);
    } else {
      CMsgPlayerDrawsLooseMsg mm = *(CMsgPlayerDrawsLooseMsg *)m;
      mm.tile = HiddenTile;
      send_id(id,&mm);
    }
    break;
    /* The following message can occur in history, but
       is not sent to clients */
  case CMsgComment:
    break;
    /* The following should not occur in history */
  case CMsgCanMahJong:
  case CMsgClaimDenied:
  case CMsgConnectReply:
  case CMsgReconnect:
  case CMsgError:
  case CMsgGame:
  case CMsgGameOption:
  case CMsgGameOver:
  case CMsgInfoTiles:
  case CMsgNewRound:
  case CMsgPlayer:
  case CMsgPlayerOptionSet:
  case CMsgMessage:
  case CMsgChangeManager:
  case CMsgStartPlay:
  case CMsgStopPlay:
  case CMsgWall:
  case CMsgStateSaved:
    abort();
  }
}

static void clear_history(Game *g) {
  /* now clear the history records */
  while ( gextras(g)->histcount > 0 ) {
      cmsg_deepfree(gextras(g)->history[--gextras(g)->histcount]);
  }
  /* and the prehistory */
  while ( gextras(g)->prehistcount > 0 ) {
      cmsg_deepfree(gextras(g)->prehistory[--gextras(g)->prehistcount]);
  }
}

/* add a cmsg (if appropriate) to the history of a game */
static void history_add(Game *g, CMsgMsg *m) {
  switch ( m->type ) {
    /* These messages do go into history */
  case CMsgNewHand:
  case CMsgPlayerDeclaresSpecial:
  case CMsgPause:
  case CMsgPlayerReady:
  case CMsgPlayerDraws:
  case CMsgPlayerDrawsLoose:
  case CMsgPlayerDiscards:
  case CMsgPlayerDoesntClaim:
  case CMsgDangerousDiscard:
  case CMsgPlayerClaimsPung:
  case CMsgPlayerPungs:
  case CMsgPlayerFormsClosedPung:
  case CMsgPlayerClaimsKong:
  case CMsgPlayerKongs:
  case CMsgPlayerDeclaresClosedKong:
  case CMsgPlayerAddsToPung:
  case CMsgPlayerRobsKong:
  case CMsgPlayerClaimsChow:
  case CMsgPlayerChows:
  case CMsgPlayerFormsClosedChow:
  case CMsgWashOut:
  case CMsgPlayerClaimsMahJong:
  case CMsgPlayerMahJongs:
  case CMsgPlayerPairs:
  case CMsgPlayerFormsClosedPair:
  case CMsgPlayerShowsTiles:
  case CMsgPlayerSpecialSet:
  case CMsgPlayerFormsClosedSpecialSet:
  case CMsgHandScore:
  case CMsgSettlement:
  case CMsgComment:
  case CMsgSwapTile:
    gextras(g)->history[gextras(g)->histcount++] = cmsg_deepcopy(m);
    break;
    /* These messages do not go into history */
  case CMsgStateSaved:
  case CMsgCanMahJong:
  case CMsgClaimDenied:
  case CMsgConnectReply:
  case CMsgReconnect:
  case CMsgError:
  case CMsgGame:
  case CMsgGameOption:
  case CMsgGameOver:
  case CMsgInfoTiles:
  case CMsgNewRound:
  case CMsgPlayer:
  case CMsgPlayerOptionSet:
  case CMsgMessage:
  case CMsgChangeManager:
  case CMsgStartPlay:
  case CMsgStopPlay:
  case CMsgWall:
    ;
  }
}

static void save_and_exit() {
  if ( save_on_exit ) save_state(the_game,NULL);
  exit(0);
}

/* this function extracts the timeout_time from a game
   according the Timeout and TimeoutGrace options, and
   the passed in value of localtimeouts */
static int get_timeout_time(Game *g,int localtimeouts) {
  return ((int)game_get_option_value(g,GOTimeout,NULL))
    + (localtimeouts ? (int)game_get_option_value(g,GOTimeoutGrace,NULL) : 0);
}