aboutsummaryrefslogtreecommitdiffstats
path: root/FICS/ratings.c
blob: a7227521b4cd909d0531c9f086cac64786985655 (plain)
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
/*
    ratings.c

    fics - An internet chess server.
    Copyright (C) 1993  Richard V. Nash

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

/* Revision history:
   name		email		yy/mm/dd	Change
   Richard Nash                 93/10/22	Created
   vek leeds@math.gatech.edu    95/04/05	Glicko system, with sterr
   Markus Uhlin                 23/12/17	Fixed the includes
   Markus Uhlin                 23/12/17	Usage of 'time_t'
*/

#include "stdinclude.h"
#include "common.h"

#include "command.h"
#include "comproc.h"
#include "config.h"
#include "ficsmain.h"
#include "gamedb.h"
#include "lists.h"
#include "playerdb.h"
#include "ratings.h"
#include "utils.h"

// Constants for Glicko system
#define Gd	3.25
#define Gr0	1720
#define Gs0	350
#define Gq	0.00575646273249
#define Gp	0.000010072398601964
// End of Glicko system variables

#define LOWESTHIST	800
#define MAXHIST		30

PRIVATE double	Ratings_B_Average;
PRIVATE double	Ratings_B_StdDev;
PRIVATE double	Ratings_S_Average;
PRIVATE double	Ratings_S_StdDev;
PRIVATE double	Ratings_L_Average;
PRIVATE double	Ratings_L_StdDev;
PRIVATE double	Ratings_W_Average;
PRIVATE double	Ratings_W_StdDev;

PRIVATE double	Rb_M = 0.0,
		Rb_S = 0.0,
		Rb_total = 0.0;
PRIVATE int	Rb_count = 0;

PRIVATE double	Rs_M = 0.0,
		Rs_S = 0.0,
		Rs_total = 0.0;
PRIVATE int	Rs_count = 0;

PRIVATE double	Rl_M = 0.0,
		Rl_S = 0.0,
		Rl_total = 0.0;
PRIVATE int	Rl_count = 0;

PRIVATE double	Rw_M = 0.0,
		Rw_S = 0.0,
		Rw_total = 0.0;
PRIVATE int	Rw_count = 0;

PRIVATE rateStruct	bestS[MAX_BEST];
PRIVATE int		numS = 0;
PRIVATE rateStruct	bestB[MAX_BEST];
PRIVATE int		numB = 0;
PRIVATE rateStruct	bestW[MAX_BEST];
PRIVATE int		numW = 0;

PRIVATE int	sHist[MAXHIST];
PRIVATE int	bHist[MAXHIST];
PRIVATE int	wHist[MAXHIST];
PRIVATE int	lHist[MAXHIST];

PRIVATE char sdir[] = DEFAULT_STATS;

PUBLIC int is_active(int Games)
{
  return (Games >= PROVISIONAL);
}


PUBLIC void rating_add(int rating, int type)
{
  int which;

  which = (rating - LOWESTHIST) / 100;
  if (which < 0)
    which = 0;
  if (which >= MAXHIST)
    which = MAXHIST - 1;
  if (type == TYPE_BLITZ) {
    bHist[which] += 1;
    Rb_count++;
    Rb_total += rating;
    if (Rb_count == 1) {
      Rb_M = rating;
    } else {
      Rb_S = Rb_S + (rating - Rb_M) * (rating - Rb_M);
      Rb_M = Rb_M + (rating - Rb_M) / (Rb_count);
    }
    Ratings_B_StdDev = sqrt(Rb_S / Rb_count);
    Ratings_B_Average = Rb_total / (double) Rb_count;
  } else if (type == TYPE_WILD) {	/* TYPE_WILD */
    wHist[which] += 1;
    Rw_count++;
    Rw_total += rating;
    if (Rw_count == 1) {
      Rw_M = rating;
    } else {
      Rw_S = Rw_S + (rating - Rw_M) * (rating - Rw_M);
      Rw_M = Rw_M + (rating - Rw_M) / (Rw_count);
    }
    Ratings_W_StdDev = sqrt(Rw_S / Rw_count);
    Ratings_W_Average = Rw_total / (double) Rw_count;
  } else if (type == TYPE_LIGHT) {       /* TYPE_LIGHT */
    lHist[which] += 1;
    Rl_count++;
    Rl_total += rating;
    if (Rl_count == 1) {
      Rl_M = rating;
    } else {
      Rl_S = Rl_S + (rating - Rl_M) * (rating - Rl_M);
      Rl_M = Rl_M + (rating - Rl_M) / (Rl_count);
    }
    Ratings_L_StdDev = sqrt(Rl_S / Rl_count);
    Ratings_L_Average = Rl_total / (double) Rl_count;

/* Insert bughouse stuff */
  } else {			/* TYPE_STAND */
    sHist[which] += 1;
    Rs_count++;
    Rs_total += rating;
    if (Rs_count == 1) {
      Rs_M = rating;
    } else {
      Rs_S = Rs_S + (rating - Rs_M) * (rating - Rs_M);
      Rs_M = Rs_M + (rating - Rs_M) / (Rs_count);
    }
    Ratings_S_StdDev = sqrt(Rs_S / Rs_count);
    Ratings_S_Average = Rs_total / (double) Rs_count;
  }
}

PUBLIC void rating_remove(int rating, int type)
{
  int which;

  which = (rating - LOWESTHIST) / 100;
  if (which < 0)
    which = 0;
  if (which >= MAXHIST)
    which = MAXHIST - 1;
  if (type == TYPE_BLITZ) {
    bHist[which] = bHist[which] - 1;
    if (bHist[which] < 0)
      bHist[which] = 0;
    if (Rb_count == 0)
      return;
    Rb_count--;
    Rb_total -= rating;
    if (Rb_count == 0) {
      Rb_M = 0;
      Rb_S = 0;
    } else {
      Rb_M = Rb_M - (rating - Rb_M) / (Rb_count);
      Rb_S = Rb_S - (rating - Rb_M) * (rating - Rb_M);
       /* added this 3.11.95 foxbat */ if (Rb_S < 0)
	Rb_S = 0;
    }
    if (Rb_count) {
      Ratings_B_StdDev = sqrt(Rb_S / Rb_count);
      Ratings_B_Average = Rb_total / (double) Rb_count;
    } else {
      Ratings_B_StdDev = 0;
      Ratings_B_Average = 0;
    }
  } else if (type == TYPE_WILD) {	/* TYPE_WILD */
    wHist[which] = wHist[which] - 1;
    if (wHist[which] < 0)
      wHist[which] = 0;
    if (Rw_count == 0)
      return;
    Rw_count--;
    Rw_total -= rating;
    if (Rw_count == 0) {
      Rw_M = 0;
      Rw_S = 0;
    } else {
      Rw_M = Rw_M - (rating - Rw_M) / (Rw_count);
      Rw_S = Rw_S - (rating - Rw_M) * (rating - Rw_M);
       /* added this 3.10.95 foxbat */ if (Rw_S < 0)
	Rw_S = 0;
    }
    if (Rw_count) {
      Ratings_W_StdDev = sqrt(Rw_S / Rw_count);
      Ratings_W_Average = Rw_total / (double) Rw_count;
    } else {
      Ratings_W_StdDev = 0;
      Ratings_W_Average = 0;
    }
  } else if (type == TYPE_LIGHT) {       /* TYPE_LIGHT */
    lHist[which] = lHist[which] - 1;
    if (lHist[which] < 0)
      lHist[which] = 0;
    if (Rl_count == 0)
      return;
    Rl_count--;
    Rl_total -= rating;
    if (Rl_count == 0) {
      Rl_M = 0;
      Rl_S = 0;
    } else {
      Rl_M = Rl_M - (rating - Rl_M) / (Rl_count);
      Rl_S = Rl_S - (rating - Rl_M) * (rating - Rl_M);
       /* added this 3.10.95 foxbat */ if (Rl_S < 0)
        Rl_S = 0;
    }
    if (Rl_count) {
      Ratings_L_StdDev = sqrt(Rl_S / Rl_count);
      Ratings_L_Average = Rl_total / (double) Rl_count;
    } else {
      Ratings_L_StdDev = 0;
      Ratings_L_Average = 0;
    }
/* insert bughouse stuff here */
  } else {			/* TYPE_STAND */
    sHist[which] = sHist[which] - 1;
    if (sHist[which] < 0)
      sHist[which] = 0;
    if (Rs_count == 0)
      return;
    Rs_count--;
    Rs_total -= rating;
    if (Rs_count == 0) {
      Rs_M = 0;
      Rs_S = 0;
    } else {
      Rs_M = Rs_M - (rating - Rs_M) / (Rs_count);
      Rs_S = Rs_S - (rating - Rs_M) * (rating - Rs_M);
       /* added this 3.10.95 foxbat */ if (Rs_S < 0)
	Rs_S = 0;
    }
    if (Rs_count) {
      Ratings_S_StdDev = sqrt(Rs_S / Rs_count);
      Ratings_S_Average = Rs_total / (double) Rs_count;
    } else {
      Ratings_S_StdDev = 0;
      Ratings_S_Average = 0;
    }
  }
}

PRIVATE void load_ratings(void)
{
  FILE *fp;
  char fname[MAX_FILENAME_SIZE];
  int i;

  sprintf(fname, "%s/newratingsV%d_data", stats_dir,STATS_VERSION);
  fp = fopen(fname, "r");
  if (!fp) {
    fprintf(stderr, "FICS: Can't read ratings data!\n");
    return;
  }
  fscanf(fp, "%lf %lf %lf %d", &Rb_M, &Rb_S, &Rb_total, &Rb_count);
  fscanf(fp, "%lf %lf %lf %d", &Rs_M, &Rs_S, &Rs_total, &Rs_count);
  fscanf(fp, "%lf %lf %lf %d", &Rw_M, &Rw_S, &Rw_total, &Rw_count);
  fscanf(fp, "%lf %lf %lf %d", &Rl_M, &Rl_S, &Rl_total, &Rl_count);

  for (i = 0; i < MAXHIST; i++) {
    fscanf(fp, "%d %d %d %d", &sHist[i], &bHist[i], &wHist[i], &lHist[i]);
  }
  fclose(fp);
  if (Rs_count) {
    Ratings_S_StdDev = sqrt(Rs_S / Rs_count);
    Ratings_S_Average = Rs_total / (double) Rs_count;
  } else {
    Ratings_S_StdDev = 0;
    Ratings_S_Average = 0;
  }
  if (Rb_count) {
    Ratings_B_StdDev = sqrt(Rb_S / Rb_count);
    Ratings_B_Average = Rb_total / (double) Rb_count;
  } else {
    Ratings_B_StdDev = 0;
    Ratings_B_Average = 0;
  }
  if (Rw_count) {
    Ratings_W_StdDev = sqrt(Rw_S / Rw_count);
    Ratings_W_Average = Rw_total / (double) Rw_count;
  } else {
    Ratings_W_StdDev = 0;
    Ratings_W_Average = 0;
  }
  if (Rl_count) {
    Ratings_L_StdDev = sqrt(Rl_S / Rl_count);
    Ratings_L_Average = Rl_total / (double) Rl_count;
  } else {
    Ratings_L_StdDev = 0;
    Ratings_L_Average = 0;
  }
}

PUBLIC void
save_ratings(void)
{
	FILE	*fp;
	char	 fname[MAX_FILENAME_SIZE] = { '\0' };

	sprintf(fname, "%s/newratingsV%d_data", stats_dir, STATS_VERSION);

	if ((fp = fopen(fname, "w")) == NULL) {
		fprintf(stderr, "FICS: Can't write ratings data!\n");
		return;
	}

	fprintf(fp, "%10f %10f %10f %d\n", Rb_M, Rb_S, Rb_total, Rb_count);
	fprintf(fp, "%10f %10f %10f %d\n", Rs_M, Rs_S, Rs_total, Rs_count);
	fprintf(fp, "%10f %10f %10f %d\n", Rw_M, Rw_S, Rw_total, Rw_count);
	fprintf(fp, "%10f %10f %10f %d\n", Rl_M, Rl_S, Rl_total, Rl_count);

	for (int i = 0; i < MAXHIST; i++) {
		fprintf(fp, "%d %d %d %d\n", sHist[i], bHist[i], wHist[i],
		    lHist[i]);
	}

	fclose(fp);
}

PRIVATE void
zero_stats(void)
{
	for (int i = 0; i < MAXHIST; i++) {
		sHist[i] = 0;
		bHist[i] = 0;
		wHist[i] = 0;
		lHist[i] = 0;
	}

	Rb_M = 0.0, Rb_S = 0.0, Rb_total = 0.0;
	Rb_count = 0;

	Rs_M = 0.0, Rs_S = 0.0, Rs_total = 0.0;
	Rs_count = 0;

	Rw_M = 0.0, Rw_S = 0.0, Rw_total = 0.0;
	Rw_count = 0;

	Rl_M = 0.0, Rl_S = 0.0, Rl_total = 0.0;
	Rl_count = 0;

	numS = 0;
	numB = 0;
	numW = 0;
}

PUBLIC void
rating_init(void)
{
	zero_stats();
	load_ratings();
}

/*
 * This recalculates the rating info from the player data. (Which can
 * take a long time!)
 */
PUBLIC void
rating_recalc(void)
{
	DIR		*dirp;
	char		 dname[MAX_FILENAME_SIZE];
	int		 c;
	int		 p1;
#if USE_DIRENT
	struct dirent	*dp;
#else
	struct direct	*dp;
#endif
	time_t		 t = time(NULL);

	fprintf(stderr, "FICS: Recalculating ratings at %s\n", strltime(&t));
	zero_stats();

	for (c = 'a'; c <= 'z'; c++) {
		sprintf(dname, "%s/%c", player_dir, c);

		if ((dirp = opendir(dname)) == NULL)
			continue;

		for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
			if (dp->d_name[0] != '.') {
				p1 = player_new();

				if (player_read(p1, dp->d_name)) {
					player_remove(p1);

					fprintf(stderr, "FICS: Problem reading "
					    "player %s.\n", dp->d_name);

					continue;
				}

				if (parray[p1].b_stats.rating > 0) {
					rating_add(parray[p1].b_stats.rating,
					    TYPE_BLITZ);
				}
				if (parray[p1].s_stats.rating > 0) {
					rating_add(parray[p1].s_stats.rating,
					    TYPE_STAND);
				}
				if (parray[p1].l_stats.rating > 0) {
					rating_add(parray[p1].l_stats.rating,
					    TYPE_LIGHT);
				}

				// insert bughouse stuff here

				if (parray[p1].w_stats.rating > 0) {
					rating_add(parray[p1].w_stats.rating,
					    TYPE_WILD);
				}

				player_remove(p1);
			}
		} /* for */

		closedir(dirp);
	} /* for */

	if (Rs_count) {
		Ratings_S_StdDev	= sqrt(Rs_S / Rs_count);
		Ratings_S_Average	= (Rs_total / (double)Rs_count);
	} else {
		Ratings_S_StdDev	= 0;
		Ratings_S_Average	= 0;
	}
	if (Rb_count) {
		Ratings_B_StdDev	= sqrt(Rb_S / Rb_count);
		Ratings_B_Average	= (Rb_total / (double)Rb_count);
	} else {
		Ratings_B_StdDev	= 0;
		Ratings_B_Average	= 0;
	}
	if (Rl_count) {
		Ratings_L_StdDev	= sqrt(Rl_S / Rl_count);
		Ratings_L_Average	= (Rl_total / (double)Rl_count);
	} else {
		Ratings_L_StdDev	= 0;
		Ratings_L_Average	= 0;
	}
	if (Rw_count) {
		Ratings_W_StdDev	= sqrt(Rw_S / Rw_count);
		Ratings_W_Average	= (Rw_total / (double)Rw_count);
	} else {
		Ratings_W_StdDev	= 0;
		Ratings_W_Average	= 0;
	}

	save_ratings();

	t = time(NULL);
	fprintf(stderr, "FICS: Finished at %s\n", strltime(&t));
}

PRIVATE int
Round(double x)
{
	return (x < 0 ? (int)(x - 0.5) : (int)(x + 0.5));
}

PRIVATE double
Gf(double ss)
{
	return (1.0 / sqrt(1.0 + Gp * ss * ss));
}

/*
 * Confusing but economical: calculate error and attenuation function
 * together.
 */
PRIVATE double
GE(int r, int rr, double ss, double *fss)
{
	*fss = Gf(ss);
	return (1.0 / (1.0 + pow(10.0, (rr - r) * (*fss) / 400.0)));
}

PRIVATE double
current_sterr(double s, int t)
{
	if (t < 0)
		t = 0; // this shouldn't happen
	return sqrt(s * s + Gd * Gd * log(1.0 + t / 60.0));
}

/*
 * Calculates new rating and standard error. By vek. The person who
 * invented the ratings system is Mark E. Glickman, Ph.D. His e-mail
 * address is glickman@hustat.harvard.edu as of April '95. Postscript
 * copy of the note I coded this from should be available for ftp from
 * ics.onenet.net, if not elsewhere.
 */
PUBLIC void
rating_sterr_delta(int p1, int p2, int type, int gtime, int result,
    int *deltarating, double *newsterr)
{
	double		 E, fs2, denominator, GK, w; // Parts of fancy formulas
	double		 delta, sigma; // Results to return
	double		 s1, s2;
	int		 t1, r1, t2, r2; // Initial sterrs and ratings
	statistics	*p1_stats;
	statistics	*p2_stats;

	if (type == TYPE_BLITZ) {
		p1_stats = &parray[p1].b_stats;
		p2_stats = &parray[p2].b_stats;
	} else if (type == TYPE_WILD) {
		p1_stats = &parray[p1].w_stats;
		p2_stats = &parray[p2].w_stats;
	} else if (type == TYPE_LIGHT) {
		p1_stats = &parray[p1].l_stats;
		p2_stats = &parray[p2].l_stats;

		// insert bughouse stuff here
	} else {
		p1_stats = &parray[p1].s_stats;
		p2_stats = &parray[p2].s_stats;
	}

	/*
	 * Calculate effective pre-game sterr's. ltime == 0 implies
	 * never had sterr.
	 */
	if (p1_stats->ltime == 0)
		s1 = Gs0;
	else {
		t1 = gtime - p1_stats->ltime;
		s1 = current_sterr(p1_stats->sterr, t1);

		if (s1 > Gs0)
			s1 = Gs0;
	}

	if (p2_stats->ltime == 0)
		s2 = Gs0;
	else {
		t2 = gtime - p2_stats->ltime;
		s2 = current_sterr(p2_stats->sterr, t2);

		if (s2 > Gs0)
			s2 = Gs0;
	}

	if (p1_stats->rating == 0 && p1_stats->num == 0)
		r1 = Gr0;
	else
		r1 = p1_stats->rating;

	if (p2_stats->rating == 0 && p2_stats->num == 0)
		r2 = Gr0;
	else
		r2 = p2_stats->rating;

	if (result == RESULT_WIN) {
		w = 1.0;
	} else if (result == RESULT_DRAW) {
		w = 0.5;
	} else {
		w = 0.0;
	}

	E = GE(r1, r2, s2, &fs2);
	denominator = 1.0 / (s1 * s1) + Gq * Gq * fs2 * fs2 * E * (1.0 - E);
	GK = Gq * fs2 / denominator;
	delta = GK * (w - E);

	if (p1_stats->rating == 0 && p1_stats->num == 0)
		*deltarating = Round(Gr0 + delta);
	else
		*deltarating = Round(delta);	// Returned values: deltarating,
						// newsterr.

	sigma = 1.0 / sqrt(denominator);
	*newsterr = (double) sigma;
}

PUBLIC int
rating_delta(int p1, int p2, int type, int result, int gtime)
{
	int	delta;
	double	sigma;

	rating_sterr_delta(p1, p2, type, gtime, result, &delta, &sigma);
	return delta;
}

PUBLIC int
rating_update(int g)
{
	double		 wSigma, bSigma;
	int		 gtime;
	int		 inprogress = (g == parray[garray[g].black].game);
	int		 wDelta, bDelta;
	int		 wRes, bRes;
	statistics	*b_stats;
	statistics	*w_stats;

	/*
	 * If this is adjudication of stored game - be quiet about
	 * ratings change.
	 */
	if (garray[g].type == TYPE_BLITZ) {
		w_stats = &parray[garray[g].white].b_stats;
		b_stats = &parray[garray[g].black].b_stats;
	} else if (garray[g].type == TYPE_STAND) {
		w_stats = &parray[garray[g].white].s_stats;
		b_stats = &parray[garray[g].black].s_stats;
	} else if (garray[g].type == TYPE_WILD) {
		w_stats = &parray[garray[g].white].w_stats;
		b_stats = &parray[garray[g].black].w_stats;
	} else if (garray[g].type == TYPE_LIGHT) {
		w_stats = &parray[garray[g].white].l_stats;
		b_stats = &parray[garray[g].black].l_stats;
	} else {
		fprintf(stderr, "FICS: Can't update untimed ratings!\n");
		return -1;
	}

	switch (garray[g].result) {
	case END_CHECKMATE:
	case END_RESIGN:
	case END_FLAG:
	case END_ADJWIN:
		if (garray[g].winner == WHITE) {
			wRes = RESULT_WIN;
			bRes = RESULT_LOSS;
		} else {
			bRes = RESULT_WIN;
			wRes = RESULT_LOSS;
		}
		break;
	case END_AGREEDDRAW:
	case END_REPETITION:
	case END_50MOVERULE:
	case END_STALEMATE:
	case END_NOMATERIAL:
	case END_BOTHFLAG:
	case END_ADJDRAW:
	case END_FLAGNOMATERIAL:
		wRes = bRes = RESULT_DRAW;
		break;
	default:
		fprintf(stderr, "FICS: Update undecided game %d?\n",
		    garray[g].result);
		return -1;
	}

	gtime = untenths(garray[g].timeOfStart);

	rating_sterr_delta(garray[g].white, garray[g].black, garray[g].type,
	    gtime, wRes, &wDelta, &wSigma);
	rating_sterr_delta(garray[g].black, garray[g].white, garray[g].type,
	    gtime, bRes, &bDelta, &bSigma);

	w_stats->ltime = gtime;
	b_stats->ltime = gtime;

	if (wRes == RESULT_WIN) {
		w_stats->win++;
	} else if (wRes == RESULT_LOSS) {
		w_stats->los++;
	} else {
		w_stats->dra++;
	}

	w_stats->num++;

	if (bRes == RESULT_WIN) {
		b_stats->win++;
	} else if (bRes == RESULT_LOSS) {
		b_stats->los++;
	} else {
		b_stats->dra++;
	}

	b_stats->num++;

	rating_remove(w_stats->rating, garray[g].type);
	rating_remove(b_stats->rating, garray[g].type);

	if (inprogress) {
		pprintf(garray[g].white, "%s rating adjustment: %d ",
		    ((garray[g].type == TYPE_BLITZ) ? "Blitz" :
		    ((garray[g].type == TYPE_WILD) ? "Wild" :
		    ((garray[g].type == TYPE_LIGHT) ? "Lightning" :
		    "Standard"))),
		    w_stats->rating);
		pprintf(garray[g].black, "%s rating adjustment: %d ",
		    ((garray[g].type == TYPE_BLITZ) ? "Blitz" :
		    ((garray[g].type == TYPE_WILD) ? "Wild" :
		    ((garray[g].type == TYPE_LIGHT) ? "Lightning" :
		    "Standard"))),
		    b_stats->rating);
	}

	if (wDelta < -1000) {
		pprintf(garray[g].white, "not changed due to bug "
		    "(way too small)! sorry!\n");
		fprintf(stderr, "FICS: Got too small ratings bug for %s "
		    "(w) vs. %s\n",
		    parray[garray[g].white].login,
		    parray[garray[g].black].login);
	} else if (wDelta > 3000) {
		pprintf(garray[g].white, "not changed due to bug "
		    "(way too big)! sorry!\n");
		fprintf(stderr, "FICS: Got too big ratings bug for %s "
		    "(w) vs. %s\n",
		    parray[garray[g].white].login,
		    parray[garray[g].black].login);
	} else {
		w_stats->rating += wDelta;
		w_stats->sterr = wSigma;
	}

	if (bDelta < -1000) {
		pprintf(garray[g].black, "not changed due to bug "
		    "(way too small)! sorry! ");
		fprintf(stderr, "FICS: Got too small ratings bug for %s "
		    "(b) vs. %s\n",
		    parray[garray[g].black].login,
		    parray[garray[g].white].login);
	} else if (bDelta > 3000) {
		pprintf(garray[g].black, "not changed due to bug "
		    "(way too big)! sorry! ");
		fprintf(stderr, "FICS: Got too big ratings bug for %s "
		    "(b) vs. %s\n",
		    parray[garray[g].black].login,
		    parray[garray[g].white].login);
	} else {
		b_stats->rating += bDelta;
		b_stats->sterr = bSigma;
	}

	rating_add(w_stats->rating, garray[g].type);
	rating_add(b_stats->rating, garray[g].type);

	if (w_stats->rating > w_stats->best &&
	    is_active(w_stats->num)) {
		w_stats->best = w_stats->rating;
		w_stats->whenbest = time(NULL);
	}
	if (b_stats->rating > b_stats->best &&
	    is_active(b_stats->num)) {
		b_stats->best = b_stats->rating;
		b_stats->whenbest = time(NULL);
	}

	// Ratings are now saved to disk after each game
	player_save(garray[g].white);
	player_save(garray[g].black);

	// foxbat 3.11.95
	if (garray[g].type == TYPE_BLITZ) {
		Rb_count++;
		Rb_total += (w_stats->rating + b_stats->rating) / 2.0;
	} else if (garray[g].type == TYPE_STAND) {
		Rs_count++;
		Rs_total += (w_stats->rating + b_stats->rating) / 2.0;
	} else if (garray[g].type == TYPE_LIGHT) {
		Rl_count++;
		Rl_total += (w_stats->rating + b_stats->rating) / 2.0;
	} else if (garray[g].type == TYPE_WILD) {
		Rw_count++;
		Rw_total += (w_stats->rating + b_stats->rating) / 2.0;
	}

	// end add
	if (inprogress) {
		pprintf(garray[g].white, "--> %d\n", w_stats->rating);
		pprintf(garray[g].black, "--> %d\n", b_stats->rating);
	}

	save_ratings();

	UpdateRank(garray[g].type, parray[garray[g].white].name, w_stats,
	    parray[garray[g].white].name);
	UpdateRank(garray[g].type, parray[garray[g].black].name, b_stats,
	    parray[garray[g].black].name);
	return 0;
}

PUBLIC int
com_assess(int p, param_list param)
{
	double	newsterr1;
	double	newsterr2;
	int	p1 = p, p2, nowtime;
	int	p1_connected = 1, p2_connected = 1;
	int	win1, draw1, loss1;
	int	win2, draw2, loss2;

	// XXX
	nowtime = time(0);

	if (param[0].type == TYPE_NULL) {
		if (parray[p].game < 0) {
			pprintf(p, "You are not playing a game.\n");
			return COM_OK;
		} else if (garray[parray[p].game].status == GAME_EXAMINE) {
			if (!strcmp(garray[parray[p].game].black_name,
			    parray[p].name)) {
				pcommand(p, "assess %s\n",
				    garray[parray[p].game].white_name);
			} else {
				pcommand(p, "assess %s %s\n",
				    garray[parray[p].game].white_name,
				    garray[parray[p].game].black_name);
			}

			return COM_OK;
		} else {
			p2 = parray[p].opponent;
		}
	} else {
		if (!FindPlayer(p, param[0].val.word, &p2, &p2_connected)) {
			pprintf(p, "No user named \"%s\" was found.\n",
			    param[0].val.word);
			return COM_OK;
		}

		if (param[1].type != TYPE_NULL) {
			p1 = p2;
			p1_connected = p2_connected;

			if (!FindPlayer(p, param[1].val.word, &p2,
			    &p2_connected)) {
				pprintf(p, "No user named \"%s\" was found.\n",
				    param[1].val.word);

				if (!p1_connected)
					player_remove(p1);
				return COM_OK;
			}
		}
	}

	if (p1 == p2) {
		pprintf(p, "You can't assess the same players.\n");

		if (!p1_connected)
			player_remove(p1);
		if (!p2_connected)
			player_remove(p2);
		return COM_OK;
	}

	rating_sterr_delta(p1, p2, TYPE_BLITZ, nowtime, RESULT_WIN, &win1,
	    &newsterr1);
	rating_sterr_delta(p1, p2, TYPE_BLITZ, nowtime, RESULT_DRAW, &draw1,
	    &newsterr1);
	rating_sterr_delta(p1, p2, TYPE_BLITZ, nowtime, RESULT_LOSS, &loss1,
	    &newsterr1);
	rating_sterr_delta(p2, p1, TYPE_BLITZ, nowtime, RESULT_WIN, &win2,
	    &newsterr2);
	rating_sterr_delta(p2, p1, TYPE_BLITZ, nowtime, RESULT_DRAW, &draw2,
	    &newsterr2);
	rating_sterr_delta(p2, p1, TYPE_BLITZ, nowtime, RESULT_LOSS, &loss2,
	    &newsterr2);

	pprintf(p, "\nBlitz\n   %10s (%4s, RD: %5.1f)  %10s (%4s, RD: %5.1f)\n",
	    parray[p1].name,
	    ratstrii(parray[p1].b_stats.rating, parray[p1].registered),
	    parray[p1].b_stats.sterr,
	    parray[p2].name,
	    ratstrii(parray[p2].b_stats.rating, parray[p2].registered),
	    parray[p2].b_stats.sterr);

	pprintf(p, "Win :         %4d                         %4d\n",
	    win1,
	    loss2);
	pprintf(p, "Draw:         %4d                         %4d\n",
	    draw1,
	    draw2);
	pprintf(p, "Loss:         %4d                         %4d\n",
	    loss1,
	    win2);
	pprintf(p, "New RD:        %5.1f                        %5.1f\n",
	    newsterr1,
	    newsterr2);

	rating_sterr_delta(p1, p2, TYPE_STAND, nowtime, RESULT_WIN, &win1,
	    &newsterr1);
	rating_sterr_delta(p1, p2, TYPE_STAND, nowtime, RESULT_DRAW, &draw1,
	    &newsterr1);
	rating_sterr_delta(p1, p2, TYPE_STAND, nowtime, RESULT_LOSS, &loss1,
	    &newsterr1);
	rating_sterr_delta(p2, p1, TYPE_STAND, nowtime, RESULT_WIN, &win2,
	    &newsterr2);
	rating_sterr_delta(p2, p1, TYPE_STAND, nowtime, RESULT_DRAW, &draw2,
	    &newsterr2);
	rating_sterr_delta(p2, p1, TYPE_STAND, nowtime, RESULT_LOSS, &loss2,
	    &newsterr2);

	pprintf(p, "\nStandard\n   %10s (%4s, RD: %5.1f)  %10s "
	    "(%4s, RD: %5.1f)\n",
	    parray[p1].name,
	    ratstrii(parray[p1].s_stats.rating, parray[p1].registered),
	    parray[p1].s_stats.sterr,
	    parray[p2].name,
	    ratstrii(parray[p2].s_stats.rating, parray[p2].registered),
	    parray[p2].s_stats.sterr);

	pprintf(p, "Win :         %4d                         %4d\n",
	    win1,
	    loss2);
	pprintf(p, "Draw:         %4d                         %4d\n",
	    draw1,
	    draw2);
	pprintf(p, "Loss:         %4d                         %4d\n",
	    loss1,
	    win2);
	pprintf(p, "New RD:        %5.1f                        %5.1f\n",
	    newsterr1,
	    newsterr2);

	rating_sterr_delta(p1, p2, TYPE_LIGHT, nowtime, RESULT_WIN, &win1,
	    &newsterr1);
	rating_sterr_delta(p1, p2, TYPE_LIGHT, nowtime, RESULT_DRAW, &draw1,
	    &newsterr1);
	rating_sterr_delta(p1, p2, TYPE_LIGHT, nowtime, RESULT_LOSS, &loss1,
	    &newsterr1);
	rating_sterr_delta(p2, p1, TYPE_LIGHT, nowtime, RESULT_WIN, &win2,
	    &newsterr2);
	rating_sterr_delta(p2, p1, TYPE_LIGHT, nowtime, RESULT_DRAW, &draw2,
	    &newsterr2);
	rating_sterr_delta(p2, p1, TYPE_LIGHT, nowtime, RESULT_LOSS, &loss2,
	    &newsterr2);

	pprintf(p, "\nLightning\n   %10s (%4s, RD: %5.1f)  %10s "
	    "(%4s, RD: %5.1f)\n",
	    parray[p1].name,
	    ratstrii(parray[p1].l_stats.rating, parray[p1].registered),
	    parray[p1].l_stats.sterr,
	    parray[p2].name,
	    ratstrii(parray[p2].l_stats.rating, parray[p2].registered),
	    parray[p2].l_stats.sterr);

	pprintf(p, "Win :         %4d                         %4d\n",
	    win1,
	    loss2);
	pprintf(p, "Draw:         %4d                         %4d\n",
	    draw1,
	    draw2);
	pprintf(p, "Loss:         %4d                         %4d\n",
	    loss1,
	    win2);
	pprintf(p, "New RD:        %5.1f                        %5.1f\n",
	    newsterr1,
	    newsterr2);

	rating_sterr_delta(p1, p2, TYPE_WILD, nowtime, RESULT_WIN, &win1,
	    &newsterr1);
	rating_sterr_delta(p1, p2, TYPE_WILD, nowtime, RESULT_DRAW, &draw1,
	    &newsterr1);
	rating_sterr_delta(p1, p2, TYPE_WILD, nowtime, RESULT_LOSS, &loss1,
	    &newsterr1);

	rating_sterr_delta(p2, p1, TYPE_WILD, nowtime, RESULT_WIN, &win2,
	    &newsterr2);
	rating_sterr_delta(p2, p1, TYPE_WILD, nowtime, RESULT_DRAW, &draw2,
	    &newsterr2);
	rating_sterr_delta(p2, p1, TYPE_WILD, nowtime, RESULT_LOSS, &loss2,
	    &newsterr2);

	pprintf(p, "\nWild\n   %10s (%4s, RD: %5.1f)  %10s (%4s, RD: %5.1f)\n",
	    parray[p1].name,
	    ratstrii(parray[p1].w_stats.rating, parray[p1].registered),
	    parray[p1].w_stats.sterr,
	    parray[p2].name,
	    ratstrii(parray[p2].w_stats.rating, parray[p2].registered),
	    parray[p2].w_stats.sterr);

	pprintf(p, "Win :         %4d                         %4d\n",
	    win1,
	    loss2);
	pprintf(p, "Draw:         %4d                         %4d\n",
	    draw1,
	    draw2);
	pprintf(p, "Loss:         %4d                         %4d\n",
	    loss1,
	    win2);
	pprintf(p, "New RD:        %5.1f                        %5.1f\n",
	    newsterr1,
	    newsterr2);

	if (!p1_connected)
		player_remove(p1);
	if (!p2_connected)
		player_remove(p2);
	return COM_OK;
}

PUBLIC int
com_best(int p, param_list param)
{
	return Best(p, param, 1);
}

PUBLIC int
com_hbest(int p, param_list param)
{
	return Best(p, param, 0);
}

PUBLIC int
com_statistics(int p, param_list param)
{
	pprintf(p, "                Standard       Blitz   Lightning        "
	    "Wild\n");
	pprintf(p, "average:         %7.2f     %7.2f     %7.2f     %7.2f\n",
	    Ratings_S_Average,
	    Ratings_B_Average,
	    Ratings_L_Average,
	    Ratings_W_Average);
	pprintf(p, "std dev:         %7.2f     %7.2f     %7.2f     %7.2f\n",
	    Ratings_S_StdDev,
	    Ratings_B_StdDev,
	    Ratings_L_StdDev,
	    Ratings_W_StdDev);
	pprintf(p, "number :      %7d     %7d     %7d     %7d\n",
	    Rs_count, Rb_count,  Rl_count, Rw_count);
	return COM_OK;
}

PUBLIC int
com_fixrank(int p, param_list param)
{
	int	p1, connected;

	if (!FindPlayer(p, param[0].val.word, &p1, &connected))
		return COM_OK;

	UpdateRank(TYPE_BLITZ, parray[p1].name, &parray[p1].b_stats,
	    parray[p1].name);
	UpdateRank(TYPE_STAND, parray[p1].name, &parray[p1].s_stats,
	    parray[p1].name);
	UpdateRank(TYPE_WILD, parray[p1].name, &parray[p1].w_stats,
	    parray[p1].name);

	if (!connected)
		player_remove(p1);
	return COM_OK;
}

PUBLIC int
com_rank(int p, param_list param)
{
	return DisplayRank(p, param, 1);
}

PUBLIC int
com_hrank(int p, param_list param)
{
	return DisplayRank(p, param, 0);
}

PUBLIC int
DisplayRank(int p, param_list param, int showComputers)
{
	int	show = (SHOW_BLITZ|SHOW_STANDARD|SHOW_WILD);
	int	start, end, target, connected;

	if (param[0].type == TYPE_NULL) {
		DisplayTargetRank(p, parray[p].name, show, showComputers);
		return COM_OK;
	} else if (isdigit(param[0].val.word[0])) {
		end = -1;
		sscanf(param[0].val.word, "%d-%d", &start, &end);

		if (end > 0 && (param[1].type != TYPE_NULL))
			show = ShowFromString(param[1].val.word);

		DisplayRankedPlayers(p, start, end, show, showComputers);
		return COM_OK;
	} else {
		target = player_search(p, param[0].val.word);

		if (target == 0) {
			pprintf(p, "Target %s not found.\n", param[0].val.word);
			return COM_OK;
		}

		connected = (target > 0);

		if (!connected)
			target = -target - 1;
		else
			target--;

		if (param[1].type != TYPE_NULL)
			show = ShowFromString(param[1].val.word);

		DisplayTargetRank(p, parray[target].name, show, showComputers);

		if (!connected)
			player_remove(target);
		return COM_OK;
	}
}

PRIVATE int
GetRankFileName(char *out, int type)
{
	switch (type) {
	case TYPE_BLITZ:
		sprintf(out, "%s/rank.blitz", sdir);
		return type;
	case TYPE_STAND:
		sprintf(out, "%s/rank.std", sdir);
		return type;
	case TYPE_WILD:
		sprintf(out, "%s/rank.wild", sdir);
		return type;
	default:
		return -1;
	}
}

PUBLIC void
UpdateRank(int type, char *addName, statistics *sNew, char *delName)
{
	/* TODO: Reenable */;
}

#if 0
PUBLIC void
UpdateRank(int type, char *addName, statistics *sNew, char *delName)
{
	FILE		*fp;
	FILE		*fptemp;
	char		 RankFile[MAX_FILENAME_SIZE];
	char		 TmpRankFile[MAX_FILENAME_SIZE];
	char		 command[MAX_STRING_LENGTH];
	char		 line[MAX_RANK_LINE] = { '\0' };
	char		 login[MAX_LOGIN_NAME] = { '\0' };
	int		 comp;
	statistics	 sCur;

	if (GetRankFileName(RankFile, type) < 0)
		return;

	if ((fp = fopen(RankFile, "r")) == NULL) {
		fprintf(stderr, "Can't open rank file to update.\n");
		return;
	}

	sprintf(TmpRankFile, "%s/tmpRank", sdir);

	if ((fptemp = fopen(TmpRankFile, "w")) == NULL) {
		fprintf(stderr, "Unable to open rank file for updating.\n");
		return;
	}

	while (fgets(line, MAX_RANK_LINE - 1, fp)) {
		sscanf(line, "%s %d %d %d", login, &sCur.rating, &sCur.num,
		    &comp);

		if (delName != NULL &&
		    !strcasecmp(delName, login)) {	// Kill name.
			delName = NULL;
			continue;
		}

		if (addName != NULL &&
		    CompareStats(addName, sNew, login, &sCur) > 0) {
			int computer = in_list(-1, L_COMPUTER, addName);

			fprintf(fptemp, "%s %d %d %d\n", addName, sNew->rating,
			    sNew->num, computer);
			addName = NULL;
		}

		fprintf(fptemp, "%s %d %d %d\n", login, sCur.rating, sCur.num,
		    comp);
	}

	fclose(fptemp);
	fclose(fp);

	// XXX
	sprintf(command, "mv %s %s", TmpRankFile, RankFile);
	system(command);
}
#endif

PRIVATE void
DisplayRankHead(int p, int show)
{
	char Line[MAX_STRING_LENGTH] = { '\0' };

	if (CheckFlag(show, SHOW_BLITZ))
		strcat(Line, "         Blitz          ");
	if (CheckFlag(show, SHOW_STANDARD))
		strcat(Line, "       Standard          ");
	if (CheckFlag(show, SHOW_WILD))
		strcat(Line, "          Wild");

	pprintf(p, "%s\n\n", Line);
}

PRIVATE int
CountRankLine(int countComp, char *loginName, int num, int is_computer)
{
	if (loginName == NULL || loginName[0] == '\0')
		return 0;
	return (countComp || !is_computer) && (is_active(num));
}

PRIVATE int
GetRank(FILE *fp, char *target, int countComp)
{
	char	line[MAX_RANK_LINE] = { '\0' };
	char	login[MAX_LOGIN_NAME] = { '\0' };
	int	count = 0;
	int	nGames, is_computer;
	int	playerFound = 0;

	while (fgets(line, MAX_RANK_LINE - 1, fp) &&
	    !playerFound) {
		sscanf(line, "%s %*d %d %d", login, &nGames, &is_computer);

		if ((playerFound = !strcasecmp(login, target)) ||
		    CountRankLine(countComp, login, nGames, is_computer))
			count++;
	}

	return (playerFound ? count : -1);
}

PRIVATE void
PositionFilePtr(FILE *fp, int count, int *last, int *nTied, int showComp)
{
	char	line[MAX_RANK_LINE] = { '\0' };
	char	login[MAX_LOGIN_NAME] = { '\0' };
	int	rating, nGames, is_computer;

	if (fp == NULL)
		return;

	rewind(fp);

	for (int i = 1; i < count; i++) {
		do {
			fgets(line, MAX_RANK_LINE - 1, fp);

			if (feof(fp))
				break;
			sscanf(line, "%s %d %d %d", login, &rating, &nGames,
			    &is_computer);
		} while (!CountRankLine(showComp, login, nGames, is_computer));

		if (rating != *last) {
			*nTied = 1;
			*last = rating;
		} else
			(*nTied)++;
	}
}

PRIVATE int
ShowRankEntry(int p, FILE *fp, int count, int comp, char *target,
    int *lastRating, int *nTied)
{
	char	login[MAX_LOGIN_NAME] = { '\0' };
	char	newLine[MAX_RANK_LINE] = { '\0' };
	int	rating, findable, nGames, is_comp;

	findable = (count > 0 && !feof(fp));

	if (findable) {
		do {
			fgets(newLine, MAX_RANK_LINE - 1, fp);

			if (feof(fp)) {
				findable = 0;
			} else if (newLine[0] != '\0') {
				sscanf(newLine, "%s %d %d %d", login, &rating,
				    &nGames, &is_comp);
			} else {
				login[0] = '\0';
			}
		} while (!CountRankLine(comp, login, nGames, is_comp) &&
		    findable &&
		    strcasecmp(login, target));
	}

	if (findable) {
		if (!strcasecmp(login, target) && !CountRankLine(comp, login,
		    nGames, is_comp)) {
			pprintf_highlight(p, "----  %-12.12s %4s", login,
			    ratstr(rating));
			pprintf(p, "  ");
			return 0;
		} else if (*lastRating == rating && *nTied < 1) {
			pprintf(p, "      ");

			if (!strcasecmp(login, target)) {
				pprintf_highlight(p, "%-12.12s %4s", login,
				    ratstr(rating));
			} else {
				pprintf(p, "%-12.12s %4s", login,
				    ratstr(rating));
			}

			pprintf(p, "  ");
			return 1;
		} else {
			if (*nTied >= 1) {
				if (*lastRating == rating)
					count -= *nTied;
				*nTied = -1;
			}

			if (!strcasecmp(login, target)) {
				pprintf_highlight(p, "%4d. %-12.12s %4s", count,
				    login, ratstr(rating));
			} else {
				pprintf(p, "%4d. %-12.12s %4s", count, login,
				    ratstr(rating));
			}

			pprintf(p, "  ");
			*lastRating = rating;
			return 1;
		}
	} else {
		pprintf(p, "%25s", "");
		return 1;
	}
}

PRIVATE int
CountAbove(int num, int blitz, int std, int wild, int which)
{
	int	max = blitz;

	if (max < std)
		max = std;
	if (max < wild)
		max = wild;
	return (max <= (num + 1) / 2 ? max - 1 : (num + 1) / 2);
}

PRIVATE int
ShowRankLines(int p, FILE *fb, FILE *fs, FILE *fw, int bCount, int sCount,
    int wCount, int n, int showComp, int show, char *target)
{
	int	lastBlitz = 9999, nTiedBlitz = 0;
	int	lastStd = 9999, nTiedStd = 0;
	int	lastWild = 9999, nTiedWild = 0;

	if (n <= 0)
		return 0;

	if (CheckFlag(show, SHOW_BLITZ)) {
		PositionFilePtr(fb, bCount, &lastBlitz, &nTiedBlitz, showComp);

		if (feof(fb))
			ClearFlag(show, SHOW_BLITZ);
	}

	if (CheckFlag(show, SHOW_STANDARD)) {
		PositionFilePtr(fs, sCount, &lastStd, &nTiedStd, showComp);

		if (feof(fs))
			ClearFlag(show, SHOW_STANDARD);
	}

	if (CheckFlag(show, SHOW_WILD)) {
		PositionFilePtr(fw, wCount, &lastWild, &nTiedWild, showComp);

		if (feof(fw))
			ClearFlag(show, SHOW_WILD);
	}

	if (!CheckFlag(show, (SHOW_BLITZ | SHOW_STANDARD | SHOW_WILD)))
		return 0;

	DisplayRankHead(p, show);

	for (int i = 0; i < n && show; i++) {
		if (CheckFlag(show, SHOW_BLITZ)) {
			bCount += ShowRankEntry(p, fb, bCount, showComp, target,
			    &lastBlitz, &nTiedBlitz);
		}
		if (CheckFlag(show, SHOW_STANDARD)) {
			sCount += ShowRankEntry(p, fs, sCount, showComp, target,
			    &lastStd, &nTiedStd);
		}
		if (CheckFlag(show, SHOW_WILD)) {
			wCount += ShowRankEntry(p, fw, wCount, showComp, target,
			    &lastWild, &nTiedWild);
		}
		pprintf(p, "\n");
	}

	return 1;
}

PUBLIC int
DisplayTargetRank(int p, char *target, int show, int showComp)
{
	FILE	*fb = NULL;
	FILE	*fs = NULL;
	FILE	*fw = NULL;
	char	 Path[MAX_FILENAME_SIZE] = { '\0' };
	int	 numAbove;
	int	 numToShow = 20;
	int	 blitzRank = -1, blitzCount;
	int	 stdRank = -1, stdCount;
	int	 wildRank = -1, wildCount;

	if (CheckFlag(show, SHOW_BLITZ)) {
		GetRankFileName(Path, TYPE_BLITZ);

		if ((fb = fopen(Path, "r")) != NULL)
			blitzRank = GetRank(fb, target, showComp);
		if (blitzRank < 0)
			ClearFlag(show, SHOW_BLITZ);
	}

	if (CheckFlag(show, SHOW_STANDARD)) {
		GetRankFileName(Path, TYPE_STAND);

		if ((fs = fopen(Path, "r")) != NULL)
			stdRank = GetRank(fs, target, showComp);
		if (stdRank < 0)
			ClearFlag(show, SHOW_STANDARD);
	}

	if (CheckFlag(show, SHOW_WILD)) {
		GetRankFileName(Path, TYPE_WILD);

		if (CheckFlag(show, SHOW_WILD))
			fw = fopen(Path, "r");
		if (fw != NULL)
			wildRank = GetRank(fw, target, showComp);
		if (wildRank < 0)
			ClearFlag(show, SHOW_WILD);
	}

	if (!CheckFlag(show, (SHOW_BLITZ | SHOW_STANDARD | SHOW_WILD))) {
		pprintf(p, "No ratings to show.\n");

		if (fb != NULL)
			fclose(fb);
		if (fs != NULL)
			fclose(fs);
		if (fw != NULL)
			fclose(fw);
		return 0;
	}

	numAbove = CountAbove(numToShow, blitzRank, stdRank, wildRank, show);

	blitzCount	= (blitzRank - numAbove);
	stdCount	= (stdRank - numAbove);
	wildCount	= (wildRank - numAbove);

	ShowRankLines(p, fb, fs, fw, blitzCount, stdCount, wildCount, numToShow,
	    showComp, show, target);

	if (fb != NULL)
		fclose(fb);
	if (fs != NULL)
		fclose(fs);
	if (fw != NULL)
		fclose(fw);
	return 1;
}

PUBLIC int
DisplayRankedPlayers(int p, int start, int end, int show, int showComp)
{
	FILE	*fb = NULL;
	FILE	*fs = NULL;
	FILE	*fw = NULL;
	char	 Path[MAX_FILENAME_SIZE] = { '\0' };
	int	 num = (end - start + 1);

	if (start <= 0)
		start = 1;
	if (num <= 0)
		return 0;
	if (num > 100)
		num = 100;

	if (CheckFlag(show, SHOW_BLITZ)) {
		GetRankFileName(Path, TYPE_BLITZ);

		if ((fb = fopen(Path, "r")) == NULL)
			ClearFlag(show, SHOW_BLITZ);
	}
	if (CheckFlag(show, SHOW_STANDARD)) {
		GetRankFileName(Path, TYPE_STAND);

		if ((fs = fopen(Path, "r")) == NULL)
			ClearFlag(show, SHOW_STANDARD);
	}
	if (CheckFlag(show, SHOW_WILD)) {
		GetRankFileName(Path, TYPE_WILD);

		if ((fw = fopen(Path, "r")) == NULL)
			ClearFlag(show, SHOW_WILD);
	}

	ShowRankLines(p, fb, fs, fw, start, start, start, num, showComp, show,
	    "");

	if (fb)
		fclose(fb);
	if (fs)
		fclose(fs);
	if (fw)
		fclose(fw);
	return 1;
}

PUBLIC int
ShowFromString(char *s)
{
	int	len = strlen(s ? s : "");
	int	show = 0;

	if (s == NULL || s[0] == '\0')
		return (SHOW_BLITZ | SHOW_STANDARD | SHOW_WILD);

	for (int i = 0; i < len; i++) {
		switch (s[i]) {
		case 'b':
			SetFlag(show, SHOW_BLITZ);
			break;
		case 's':
			SetFlag(show, SHOW_STANDARD);
			break;
		case 'w':
			SetFlag(show, SHOW_WILD);
			break;
		}
	}

	return show;
}

PUBLIC int
Best(int p, param_list param, int ShowComp)
{
	int show = (SHOW_BLITZ | SHOW_STANDARD | SHOW_WILD);

	if (param[0].type != TYPE_NULL)
		show = ShowFromString(param[0].val.word);

	DisplayRankedPlayers(p, 1, 20, show, ShowComp);
	return COM_OK;
}