File: fics.tcl

package info (click to toggle)
scid 1%3A4.7.4%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 23,340 kB
  • sloc: tcl: 92,411; cpp: 38,013; sh: 1,697; python: 277; javascript: 201; makefile: 89; perl: 86
file content (1835 lines) | stat: -rw-r--r-- 69,924 bytes parent folder | download | duplicates (2)
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
###
### fics.tcl: part of Scid.
### Copyright (C) 2007  Pascal Georges
###

namespace eval fics {
  set server "freechess.org"
  set sockchan ""
  set seeklist {}
  set observedGame -1
  set playing 0
  set rated 0
  set waitForRating ""
  set waitForMoves ""
  set silence 1
  set sought 0
  set soughtlist {}
  set games 0
  set gameSelection 0
  set gamesList {}
  set player 0
  set playerSelection ""
  set playerList {}
  set width 300
  set height 300
  set off 20
  set graphon 0
  set timeseal_pid 0
  font create font_offers -family courier -size 12 -weight bold
  set history {}
  set history_pos 0
  set offers_minelo 1000
  set offers_maxelo 2500
  set offers_mintime 0
  set offers_maxtime 60
  variable logged 0
  variable isGuestLogin 0
  array set profileVars {}
  array set findopponent {}

  set showabortreq 1
  set showadjournreq 1
  set showdrawreq 1
  set showtakebackreq 1

  set premoveSq1 -1
  set premoveSq2 -1

  set showRatedGames 1
  set showUnratedGames 1
  set showStandardGames 1
  set showBlitzGames 1
  set showLightningGames 1
  set showOnlyRegisteredPlayer 0
  set showOnlyFreePlayer 0
  set sortGamesColumn 0 ;# sort game number
  set sortGamesOrder "-increasing" ;# sort order
  set sortPlayersColumn 4 ;# sort blitz rating
  set sortPlayersOrder "-decreasing" ;# sort blitz rating
  ################################################################################
  #
  ################################################################################
  proc config {} {
    variable logged
    global ::fics::sockChan
    set w ".ficsConfig"

    if {[winfo exists $w]} {
      focus $w
      return
    }

    if {[winfo exists .fics]} {
      focus .fics
      return
    }

    set logged 0
    set ::fics::showPass 0

    win::createDialog $w
    ::setTitle $w [::tr "ConfigureFics"]
    ttk::labelframe $w.f -text "Login"
    ttk::labelframe $w.conf -text $::tr(CCDlgCGeneraloptions)
    ttk::frame $w.fbuttons

    ttk::label $w.f.lLogin -text [::tr "CCDlgLoginName"]
    ttk::entry $w.f.login -width 20 -textvariable ::fics::login
    ttk::label $w.f.lPwd -text [::tr "CCDlgPassword"]
    ttk::entry $w.f.passwd -width 20 -textvariable ::fics::password -show *
    ttk::checkbutton $w.f.showPass -text [::tr "CCDlgShowPassword"] -variable ::fics::showPass -command {
      if {$::fics::showPass} {
        .ficsConfig.f.passwd configure -show {}
      } else {
        .ficsConfig.f.passwd configure -show *
      }
    }

    ttk::button $w.fbuttons.connect -text [::tr "FICSConnect"] -state disabled -command {
      ::fics::connect [.ficsConfig.f.login get] [.ficsConfig.f.passwd get]
      destroy .ficsConfig
    }
    ttk::button $w.fbuttons.guest -text [::tr FICSGuest] -state disabled -command {
      ::fics::connect "guest" ""
      destroy .ficsConfig
    }
    ttk::button $w.fbuttons.cancel -text [::tr "Cancel"] -command { destroy .ficsConfig }

    set row 0
    grid $w.f.lLogin -column 0 -row $row -sticky w -padx "0 5"
    grid $w.f.login -column 1 -row $row -sticky w
    incr row
    grid $w.f.lPwd -column 0 -row $row -sticky w -padx "0 5"
    grid $w.f.passwd -column 1 -row $row -sticky w
    incr row
    grid $w.f.showPass -column 1 -row $row -sticky w
    incr row
    pack $w.f -side top -anchor w -fill x
    pack $w.conf -side top -anchor w -pady "10 0"

    # use default user variables
    ttk::checkbutton $w.conf.cbvars -text [::tr "FICSdefaultuservars"] -variable ::fics::usedefaultvars
    grid $w.conf.cbvars -column 0 -row $row -sticky w -columnspan 2
    incr row

    # enable premove
    ttk::checkbutton $w.conf.premove -text [::tr "FICSpremove"] -variable ::fics::premoveEnabled
    grid $w.conf.premove -column 0 -row $row -sticky w -columnspan 2
    incr row

    # Time seal configuration
    ttk::checkbutton $w.conf.cbts -text "Time seal" -variable ::fics::use_timeseal -onvalue 1 -offvalue 0
    grid $w.conf.cbts -column 0 -row $row -sticky w
    incr row
    ttk::entry $w.conf.eExec -textvariable ::fics::timeseal_exec
    ttk::button $w.conf.bExec -text "..." -command { set ::fics::timeseal_exec [tk_getOpenFile] }
    grid $w.conf.eExec -column 0 -row $row -columnspan 2 -sticky we -padx "20 10"
    grid $w.conf.bExec -column 2 -row $row -sticky w
    incr row
    ttk::label $w.conf.lFICS_ip -text [::tr "FICSServerAddress" ]
    ttk::entry $w.conf.ipserver -width 16 -textvariable ::fics::server_ip -state readonly
    ttk::button $w.conf.bRefresh -text [::tr "FICSRefresh" ] -command ::fics::getIP
    ttk::label $w.conf.lFICS_port -text [::tr "FICSServerPort"]
    ttk::entry $w.conf.portserver -width 6 -textvariable ::fics::port_fics
    ttk::label $w.conf.ltsport -text [::tr "FICSTimesealPort"]
    ttk::entry $w.conf.portts -width 6 -textvariable ::fics::port_timeseal

    grid $w.conf.lFICS_ip -column 0 -row $row -sticky w -padx "0 5"
    grid $w.conf.ipserver -column 1 -row $row -sticky w -padx "0 10"
    grid $w.conf.bRefresh -column 2 -row $row -sticky w
    incr row
    grid $w.conf.lFICS_port -column 0 -row $row -sticky w -padx "0 5"
    grid $w.conf.portserver -column 1 -row $row -sticky w
    incr row
    grid $w.conf.ltsport -column 0 -row $row -sticky w -padx "0 5"
    grid $w.conf.portts -column 1 -row $row -sticky w
    incr row

    pack $w.fbuttons -side top -anchor e
    packdlgbuttons $w.fbuttons.cancel $w.fbuttons.connect $w.fbuttons.guest

    bind $w <Escape> "$w.fbuttons.cancel invoke"
    bind $w <F1> { helpWindow FICSLogin}

    # Get IP address of server (as Timeseal needs IP address)
    if { $::fics::server_ip == "0.0.0.0" } {
      getIP
    }

    $w.fbuttons.connect configure -state normal
    $w.fbuttons.guest configure -state normal

  }
  ################################################################################
  #
  ################################################################################
  proc getIP {} {
    set b .ficsConfig.conf.bRefresh
    $b configure -state disabled
    update
    # First handle the case of a network down
    if { [catch {set sockChan [socket -async $::fics::server $::fics::port_fics]} err]} {
      tk_messageBox -icon error -type ok -title "Unable to contact $::fics::server" -message $err -parent .ficsConfig.f
      return
    }

    # Then the case of a proxy
    set timeOut 5
    set i 0
    while { $i <= $timeOut } {
      after 1000

      if { [catch {set peer [ fconfigure $sockChan -peername ]} err]} {
        if {$i == $timeOut} {
          tk_messageBox -icon error -type ok -title "Unable to contact $::fics::server" -message $err -parent .ficsConfig.f
          return
        }
      } else  {
        break
      }
      incr i
    }

    set ::fics::server_ip [lindex $peer 0]
    ::close $sockChan
    $b configure -state normal
  }
  ################################################################################
  #
  ################################################################################
  proc setProfileVars { login } {
    global  ::fics::profileVars
    if { ! [info exists profileVars(initTime_$login)] } {
      return
    }
    set ::fics::findopponent(initTime) $profileVars(initTime_$login)
    set ::fics::findopponent(incTime) $profileVars(incTime_$login)
    set ::fics::findopponent(rated) $profileVars(rated_$login)
    set ::fics::findopponent(color) $profileVars(color_$login)
    set ::fics::findopponent(limitrating) $profileVars(limitrating_$login)
    set ::fics::findopponent(rating1) $profileVars(rating1_$login)
    set ::fics::findopponent(rating2) $profileVars(rating2_$login)
    set ::fics::findopponent(manual) $profileVars(manual_$login)
    set ::fics::findopponent(formula) $profileVars(formula_$login)
  }
  ################################################################################
  #
  ################################################################################
  proc syncProfileVars { login } {
    global  ::fics::profileVars
    variable isGuestLogin

    if {$isGuestLogin} {
      set login "guest"
    }
    set profileVars(initTime_$login) $::fics::findopponent(initTime)
    set profileVars(incTime_$login) $::fics::findopponent(incTime)
    set profileVars(rated_$login) $::fics::findopponent(rated)
    set profileVars(color_$login) $::fics::findopponent(color)
    set profileVars(limitrating_$login) $::fics::findopponent(limitrating)
    set profileVars(rating1_$login) $::fics::findopponent(rating1)
    set profileVars(rating2_$login) $::fics::findopponent(rating2)
    set profileVars(manual_$login) $::fics::findopponent(manual)
    set profileVars(formula_$login) $::fics::findopponent(formula)
  }
  ################################################################################
  #
  ################################################################################
  proc storeTime { } {
      set side 1
      if { [sc_pos side] == "white" } {set side 2 }
      ::gameclock::storeTimeComment $side
  }
  proc arrangeClocks { } {
      set w .fics.f.bottom.left
      pack forget $w.clock1 $w.clock2
      if { [::board::isFlipped .main.board] } {
          pack $w.clock1 $w.clock2
      } else {
          pack $w.clock2 $w.clock1
      }
  }
  ################################################################################
  #
  ################################################################################
  proc gamespopupmenu {{w} {x} {y} {abs_x} {abs_y} } {
      lassign [$w identify $x $y] what
      if {$what == "heading"} { return }
      set item [.fics.f.top.fgames.glist identify item $x $y]
      .fics.f.top.fgames.glist selection set $item
      $w.menu delete 0 end
      set wplayer [.fics.f.top.fgames.glist set $item 2]
      set bplayer [.fics.f.top.fgames.glist set $item 4]
      set game [.fics.f.top.fgames.glist set $item 0]
      set ::fics::gameSelection $game
      $w.menu add command -label [tr FICSObserve] -command "if { $::fics::observedGame != -1 } { \
        ::fics::writechan \"unobserve\" \"echo\"
        }
        ::fics::writechan \"observe $game\""
      $w.menu add separator
      $w.menu add checkbutton -label [tr FICSRatedGames] -variable ::fics::showRatedGames -command ::fics::updateGames
      $w.menu add checkbutton -label [tr FICSUnratedGames] -variable ::fics::showUnratedGames -command ::fics::updateGames
      $w.menu add separator
      $w.menu add checkbutton -label "Lightning" -variable ::fics::showLightningGames -command ::fics::updateGames
      $w.menu add checkbutton -label "Blitz" -variable ::fics::showBlitzGames -command ::fics::updateGames
      $w.menu add checkbutton -label "Standard" -variable ::fics::showStandardGames -command ::fics::updateGames
      $w.menu add separator
      $w.menu add command -label "Finger $wplayer" -command "::fics::writechan \"finger $wplayer\""
      $w.menu add command -label "Finger $bplayer" -command "::fics::writechan \"finger $bplayer\""
      tk_popup $w.menu $abs_x $abs_y
  }
  ################################################################################
  #
  ################################################################################
  proc playerpopupmenu {{w} {x} {y} {abs_x} {abs_y} } {
      lassign [$w identify $x $y] what
      if {$what == "heading"} { return }
      set item [.fics.f.top.fplayer.plist identify item $x $y]
      .fics.f.top.fplayer.plist selection set $item
      $w.menu delete 0 end
      set player [.fics.f.top.fplayer.plist set $item 1]
      set state [.fics.f.top.fplayer.plist set $item 2]
      set ::fics::playerSelection $player
      set matchparameter "$::fics::findopponent(rated) $::fics::findopponent(initTime) \
         $::fics::findopponent(incTime) $::fics::findopponent(color)"
      $w.menu add command -label "Finger $player" -command "::fics::writechan \"finger $player\""
      if { [string first "p" $state] >= 0 } {
          $w.menu add command -label "[tr FICSObserve] $player" -command "::fics::writechan \"observe $player\""
      } elseif {  [string first "X" $state] == -1 } {
          $w.menu add command -label "[tr FICSChallenge] $player" \
              -command "::fics::writechan \"match $player $matchparameter\""
      }
      $w.menu add separator
      $w.menu add checkbutton -label [tr FICSRegisteredPlayer] -variable ::fics::showOnlyRegisteredPlayer \
          -command ::fics::updatePlayer
      $w.menu add checkbutton -label [tr FICSFreePlayer] -variable ::fics::showOnlyFreePlayer \
          -command ::fics::updatePlayer
      tk_popup $w.menu $abs_x $abs_y
  }
  ################################################################################
  #
  ################################################################################
  proc connect { login passwd } {
    global ::fics::sockchan ::fics::seeklist ::fics::width ::fics::height ::fics::off
    variable isGuestLogin

    if {$login != ""} {
      set ::fics::reallogin $login
      # do not reset the password if we log in as guest.
      # This allows to reset it if we have another UID.
      if {$login != "guest"} {
         set ::fics::password $passwd
      }
    } else {
      return
    }

    set isGuestLogin [string match -nocase "guest" $login]

    setProfileVars $login

    # check timeseal configuration
    if {$::fics::use_timeseal} {
      if {![ file executable $::fics::timeseal_exec ]} {
        tk_messageBox -title "Error" -icon error -type ok -message "Timeseal exec error : $::fics::timeseal_exec"
        return
      }
    }

    set w .fics
    ::createToplevel $w
    ::setTitle $w "Free Internet Chess Server $::fics::reallogin"
    grid [ttk::panedwindow $w.f -orient vertical] -sticky news
    grid rowconfigure $w 0 -weight 1
    grid columnconfigure $w 0 -weight 1

    ttk::notebook $w.f.top
    ttk::frame $w.f.top.fconsole
    ttk::frame $w.f.top.fconsole.f1
    ttk::frame $w.f.top.fconsole.f2

    ttk::frame $w.f.top.foffers
    ttk::frame $w.f.top.fgames
    ttk::frame $w.f.top.fplayer
    $w.f.top add $w.f.top.fconsole -sticky nsew -text [::tr "FICSConsole"]
    $w.f.top add $w.f.top.foffers -sticky nsew -text [::tr "FICSOffers"]
    $w.f.top add $w.f.top.fgames -sticky nsw -text [::tr "FICSGames"]
    $w.f.top add $w.f.top.fplayer -sticky nws -text [::tr "TmtSortPlayers"]

    grid $w.f.top.fconsole.f1 -sticky news
    grid $w.f.top.fconsole.f2 -sticky news
    grid rowconfigure $w.f.top.fconsole 0 -weight 1
    grid columnconfigure $w.f.top.fconsole 0 -weight 1
    ttk::frame $w.f.bottom

    $w.f add $w.f.top -weight 1
    $w.f add $w.f.bottom -weight 0

    ttk::frame $w.f.bottom.left
    ttk::frame $w.f.bottom.right
    grid $w.f.bottom.left $w.f.bottom.right -sticky news -padx 5

    # games
    grid rowconfigure $w.f.top.fgames 0 -weight 1
    grid columnconfigure $w.f.top.fgames 0 -weight 1
    ttk::treeview $w.f.top.fgames.glist -columns { "Game" "WElo" "White" "BElo" "Black" "Type" "Rated" "Time" } \
        -show headings -selectmode browse -yscrollcommand "$w.f.top.fgames.ybar set"

    set i 0
    set wid [font measure font_Regular W]
    foreach { width name anchor } { 3 Game e 4 GlistWElo e 10 White w 4 GlistBElo e 10 Black w \
                                        6 FinderSortType w 5 Rated w 5 Time e} {
        $w.f.top.fgames.glist column $i -width [expr $width * $wid] -anchor $anchor -stretch 1
        $w.f.top.fgames.glist heading $i -text [tr $name]
        incr i
    }
    set inc "-increasing"
    set dec "-decreasing"
    set nosort "nosort"
    set layout [list $inc $dec $inc $dec $inc $inc $nosort $nosort]
    bind $w.f.top.fgames.glist <ButtonRelease-1> "::fics::clickGames %W %x %y {$layout}"
    bind $w.f.top.fgames.glist <KeyPress-Return> {
        set ::fics::gameSelection [.fics.f.top.fgames.glist set [.fics.f.top.fgames.glist selection] 0]
        ::fics::writechan "observe $::fics::gameSelection"
    }
    bind $w.f.top.fgames.glist <<TreeviewSelect>> {
        set ::fics::gameSelection [.fics.f.top.fgames.glist set [.fics.f.top.fgames.glist selection] 0]
    }
    bind $w.f.top.fgames.glist <Double-ButtonRelease-1> {
        set ::fics::gameSelection [.fics.f.top.fgames.glist set [.fics.f.top.fgames.glist identify row %x %y] 0]
        ::fics::writechan "observe $::fics::gameSelection"
    }
    menu $w.f.top.fgames.glist.menu -borderwidth 1
    bind $w.f.top.fgames.glist <ButtonPress-$::MB3> "fics::gamespopupmenu %W %x %y %X %Y"

    ttk::scrollbar $w.f.top.fgames.ybar -command "$w.f.top.fgames.glist yview"
    grid $w.f.top.fgames.glist -column 0 -row 0 -sticky ns
    grid $w.f.top.fgames.ybar -column 1 -row 0 -sticky news

    # player
    grid rowconfigure $w.f.top.fplayer 0 -weight 1
    grid columnconfigure $w.f.top.fplayer 0 -weight 1
    ttk::treeview $w.f.top.fplayer.plist -columns { "Typ" "Name" "Status" "Blitz" "Lightning" "Standard" "onfor" "idle" } \
        -show headings -selectmode browse -yscrollcommand "$w.f.top.fplayer.ybar set"
    set i 0
    foreach { width name anchor } { 4 Typ w 10 Name w 3 Status w 4 Blitz e 4 Lightning e 4 Standard e 5 OnFor e 4 Idle e } {
        $w.f.top.fplayer.plist column $i -width [expr $width * $wid] -anchor $anchor
        $w.f.top.fplayer.plist heading $i -text [tr $name]
        incr i
    }
    set layout [list $inc $inc $inc $dec $dec $dec $inc $inc]
    bind $w.f.top.fplayer.plist <ButtonRelease-1> "::fics::clickPlayers %W %x %y {$layout}"
    $w.f.top.fplayer.plist column 6 -anchor e
    $w.f.top.fplayer.plist column 7 -anchor e
    bind $w.f.top.fplayer.plist <KeyPress-Return> {
        set ::fics::playerSelection [.fics.f.top.fplayer.plist set [.fics.f.top.fplayer.plist selection] 1]
        ::fics::writechan "finger $::fics::playerSelection"
    }
    bind $w.f.top.fplayer.plist <<TreeviewSelect>> {
        set ::fics::playerSelection [.fics.f.top.fplayer.plist set [.fics.f.top.fplayer.plist selection] 1]
    }
    bind $w.f.top.fplayer.plist <Double-ButtonRelease-1> {
        set ::fics::playerSelection [.fics.f.top.fplayer.plist set [.fics.f.top.fplayer.plist identify row %x %y] 1]
        ::fics::writechan "finger $::fics::playerSelection"
    }
    menu $w.f.top.fplayer.plist.menu -borderwidth 1
    bind $w.f.top.fplayer.plist <ButtonPress-$::MB3> "fics::playerpopupmenu %W %x %y %X %Y"

    ttk::scrollbar $w.f.top.fplayer.ybar -command "$w.f.top.fplayer.plist yview"
    grid $w.f.top.fplayer.plist -column 0 -row 0 -sticky ns
    grid $w.f.top.fplayer.ybar -column 1 -row 0 -sticky nwes

    # graph
    canvas $w.f.top.foffers.c -background white -width $width -height $height -relief solid
    grid $w.f.top.foffers.c
    bind $w.f.top.foffers <Configure> { ::fics::configureCanvas}

    ttk::scrollbar $w.f.top.fconsole.f1.ysc -command { .fics.f.top.fconsole.f1.console yview }
    text $w.f.top.fconsole.f1.console -bg $::fics::consolebg -fg $::fics::consolefg -height $::fics::consoleheight -width $::fics::consolewidth  \
         -font font_Fixed -wrap word -yscrollcommand "$w.f.top.fconsole.f1.ysc set"
    grid $w.f.top.fconsole.f1.console $w.f.top.fconsole.f1.ysc -sticky news
    grid rowconfigure $w.f.top.fconsole.f1 0 -weight 1
    grid columnconfigure $w.f.top.fconsole.f1 0 -weight 1

    #define colors for console
    $w.f.top.fconsole.f1.console tag configure seeking     -foreground $::fics::colseeking
    $w.f.top.fconsole.f1.console tag configure game        -foreground $::fics::colgame
    $w.f.top.fconsole.f1.console tag configure gameresult  -foreground $::fics::colgameresult
    $w.f.top.fconsole.f1.console tag configure ficspercent -foreground $::fics::colficspercent
    $w.f.top.fconsole.f1.console tag configure ficshelpnext -foreground $::fics::colficshelpnext -underline 1

    ttk::entry $w.f.top.fconsole.f2.cmd -width 32
    ttk::button $w.f.top.fconsole.f2.send -text [::tr "FICSSend"] -command ::fics::cmd
    bind $w.f.top.fconsole.f2.cmd <Return> { ::fics::cmd }
    bind $w.f.top.fconsole.f2.cmd <Up> { ::fics::cmdHistory up ; break }
    bind $w.f.top.fconsole.f2.cmd <Down> { ::fics::cmdHistory down ; break }
    grid $w.f.top.fconsole.f2.cmd $w.f.top.fconsole.f2.send -sticky news
    grid columnconfigure $w.f.top.fconsole.f2 0 -weight 1

    # clock 1 is white
    ::gameclock::new $w.f.bottom.left 1 100 0
    ::gameclock::new $w.f.bottom.left 2 100 0
    arrangeClocks

    set row 0
    ttk::checkbutton $w.f.bottom.right.silence -image FICSsilence -variable ::fics::silence -onvalue 0 -offvalue 1 -command {
      ::fics::writechan "set gin $::fics::silence" "echo"
      ::fics::writechan "set seek $::fics::silence" "echo"
      ::fics::writechan "set silence $::fics::silence" "echo"
      ::fics::writechan "set chanoff [expr ! $::fics::silence ]" "echo"
    }
    ::utils::tooltip::Set $w.f.bottom.right.silence "[::tr FICSSilence]\n(set gin 0\nset seek 0\nset silence 0\nset chanoff 1)"
    set ::fics::silence 1

    set ::fics::graphon 0

    ttk::button $w.f.bottom.right.findopp -image FICSsearch  -command { ::fics::findOpponent }
    ::utils::tooltip::Set $w.f.bottom.right.findopp [::tr "FICSFindOpponent"]
    grid $w.f.bottom.right.findopp -column 0 -row $row -sticky ew -pady 2
    ttk::button $w.f.bottom.right.relay -image FICSrelayedgames -compound image -command { ::fics::writechan "tell relay listgames"}
    ::utils::tooltip::Set $w.f.bottom.right.relay "[::tr FICSRelayedGames]\n(tell relay listgames)"
    grid $w.f.bottom.right.relay -column 1 -row $row -sticky ew -pady 2
    ttk::button $w.f.bottom.right.games -image FICSusers -compound image -command { ::fics::writechan "games /bsu"}
    ::utils::tooltip::Set $w.f.bottom.right.games "[::tr FICSGames]\n(games /bsu)"
    grid $w.f.bottom.right.games -column 2 -row $row -sticky ew -pady 2
    ttk::button $w.f.bottom.right.uno -image FICSunobserve -compound image -command { ::fics::writechan "unobserve"}
    ::utils::tooltip::Set $w.f.bottom.right.uno "[::tr FICSUnobserve]\n(unobserve)"
    grid $w.f.bottom.right.uno -column 3 -row $row -sticky ew -pady 2
    ttk::button $w.f.bottom.right.profile -image FICSprofile -compound image -command { ::fics::writechan "finger" ; ::fics::writechan "history" }
    ::utils::tooltip::Set $w.f.bottom.right.profile "[::tr FICSProfile]\n(finger, history)"
    grid $w.f.bottom.right.profile -column 4 -row $row -sticky ew -pady 2

    incr row

    ttk::button $w.f.bottom.right.draw -image FICSdraw -command { ::fics::writechan "draw"}
    ::utils::tooltip::Set $w.f.bottom.right.draw "[::tr CCClaimDraw]\n(draw)"
    ttk::button $w.f.bottom.right.resign -image FICSresign -command { ::fics::writechan "resign"}
    ::utils::tooltip::Set $w.f.bottom.right.resign "[::tr CCResign]\n(resign)"
    grid $w.f.bottom.right.draw -column 0 -row $row -sticky ew -pady 2
    grid $w.f.bottom.right.resign -column 1 -row $row -sticky ew -pady 2
    ttk::button $w.f.bottom.right.abort -image FICSabort -command { ::fics::writechan "abort" }
    ::utils::tooltip::Set $w.f.bottom.right.abort "[::tr Abort]\n(abort)"
    grid $w.f.bottom.right.abort -column 2 -row $row -sticky ew -pady 2
    grid $w.f.bottom.right.silence -column 4 -row $row -sticky w
    incr row

    ttk::button $w.f.bottom.right.takeback -image FICStakeback1 -command { ::fics::writechan "takeback"}
    ::utils::tooltip::Set $w.f.bottom.right.takeback "[::tr FICSTakeback]\n(takeback)"
    ttk::button $w.f.bottom.right.takeback2 -image FICStakeback2 -command { ::fics::writechan "takeback 2"}
    ::utils::tooltip::Set $w.f.bottom.right.takeback2 "[::tr FICSTakeback2]\n(takeback 2)"

    grid $w.f.bottom.right.takeback -column 0 -row $row -sticky ew -pady 2
    grid $w.f.bottom.right.takeback2 -column 1 -row $row -sticky ew -pady 2
    incr row

    ttk::button $w.f.bottom.right.cancel -image FICSexit -command { ::fics::close }
    ::utils::tooltip::Set $w.f.bottom.right.cancel [::tr "Close"]
    grid $w.f.bottom.right.cancel -column 0 -columnspan 3 -row $row -sticky ew  -pady 2

    bind $w.f.top <<NotebookTabChanged>> { ::fics::tabchanged ; break }
    bind $w <Destroy> { catch ::fics::close }

    bind $w <F1> { helpWindow FICS}
    bind $w.f.top.fconsole.f1.console <FocusIn> "focus $w.f.top.fconsole.f2.cmd"
    bind $w.f.top.fconsole.f1.console <Configure> { .fics.f.top.fconsole.f1.console yview moveto 1 }
    bind $w.f.top.fconsole.f1.console <ButtonPress-1> { ::fics::consoleClick %x %y %W }
    ::createToplevelFinalize $w

    # all widgets must be visible
    update
    set x [winfo reqwidth $w]
    set y [winfo reqheight $w]
    wm minsize $w $x $y

    ::gameclock::setColor 1 white
    ::gameclock::setColor 2 black

    updateConsole "Connecting $login"

    # start timeseal proxy
    if {$::fics::use_timeseal} {
      updateConsole "Starting TimeSeal"
      if { [catch { set timeseal_pid [exec $::fics::timeseal_exec $::fics::server_ip $::fics::port_fics -p $::fics::port_timeseal &]} ] } {
        set ::fics::use_timeseal 0
        set port $::fics::port_fics
      } else {
        #wait for proxy to be ready !?
        after 500
        set server "localhost"
        set port $::fics::port_timeseal
      }
    } else {
      set server $::fics::server
      set port $::fics::port_fics
    }

    updateConsole "Socket opening"

    if { [catch { set sockchan [socket $server $port] } ] } {
      tk_messageBox -title "FICS" -icon error -type ok -message "[tr FICSNetError] $server $port" -parent .fics
      return
    }

    updateConsole "Channel configuration"

    fconfigure $sockchan -blocking 0 -buffering line -translation auto ;#-encoding iso8859-1 -translation crlf
    fileevent $sockchan readable ::fics::readchan
    setState disabled
  }
  ################################################################################
  #
  ################################################################################
  proc cmd {} {
    set l [.fics.f.top.fconsole.f2.cmd get]
    .fics.f.top.fconsole.f2.cmd delete 0 end
    if {$l == "quit"} {
      ::fics::close
      return
    }
    # do nothing if the command is void
    if {[string trim $l] == ""} { return }
    writechan $l "echo"
    lappend ::fics::history $l
    set ::fics::history_pos [llength $::fics::history]
  }
  ################################################################################
  #
  ################################################################################
  proc cmdHistory { action } {
    set t .fics.f.top.fconsole.f2.cmd

    if {$action == "up" && $::fics::history_pos > 0} {
      incr ::fics::history_pos -1
      $t delete 0 end
      $t insert end [lindex $::fics::history $::fics::history_pos]
    }
    if {$action == "down" && $::fics::history_pos < [expr [llength $::fics::history] -1] } {
      incr ::fics::history_pos
      $t delete 0 end
      $t insert end [lindex $::fics::history $::fics::history_pos]
    }
  }
  ################################################################################
  #
  ################################################################################
  proc findOpponent {} {
    set w .ficsfindopp
    if {[winfo exists $w]} {
      focus $w
      return
    }
    win::createDialog $w
    wm title $w [::tr "FICSFindOpponent"]

    ttk::frame $w.f
    pack $w.f -side top -anchor w -fill x
    ttk::label $w.f.linit -text [::tr "FICSInitialTime"]
    ttk::spinbox $w.f.sbTime1 -background white -width 3 -textvariable ::fics::findopponent(initTime) -from 0 -to 120 -increment 1 -validate all -validatecommand { regexp {^[0-9]+$} %P }
    ttk::label $w.f.linc -text [::tr "FICSIncrement"]
    ttk::spinbox $w.f.sbTime2 -background white -width 3 -textvariable ::fics::findopponent(incTime) -from 0 -to 120 -increment 1 -validate all -validatecommand { regexp {^[0-9]+$} %P }
    grid $w.f.linit -column 0 -row 0 -sticky w
    grid $w.f.sbTime1 -column 1 -row 0 -sticky w -pady "0 2"
    grid $w.f.linc -column 0 -row 1 -sticky w
    grid $w.f.sbTime2 -column 1 -row 1 -sticky w

    ttk::checkbutton $w.f.cbrated -text [::tr "FICSRatedGame"] -onvalue "rated" -offvalue "unrated" -variable ::fics::findopponent(rated)
    grid $w.f.cbrated -column 0 -row 2 -columnspan 2 -sticky ew

    ttk::labelframe $w.f.color -text [::tr "FICSColour"]
    grid $w.f.color -column 0 -row 3 -columnspan 2 -sticky ew
    ttk::radiobutton $w.f.rb1 -text [::tr "FICSAutoColour"] -value "" -variable ::fics::findopponent(color)
    ttk::radiobutton $w.f.rb2 -text [::tr "White"] -value "white" -variable ::fics::findopponent(color)
    ttk::radiobutton $w.f.rb3 -text [::tr "Black"] -value "black" -variable ::fics::findopponent(color)
    pack $w.f.rb1 $w.f.rb2 $w.f.rb3 -side top -anchor w -in $w.f.color

    ttk::checkbutton $w.f.cblimitrating -text [::tr "RatingRange"] -variable ::fics::findopponent(limitrating)
    ttk::spinbox $w.f.sbrating1 -background white -width 4 -textvariable ::fics::findopponent(rating1) -from 1000 -to 3000 -increment 50 -validate all -validatecommand { regexp {^[0-9]+$} %P }
    ttk::spinbox $w.f.sbrating2 -background white -width 4 -textvariable ::fics::findopponent(rating2) -from 1000 -to 3000 -increment 50 -validate all -validatecommand { regexp {^[0-9]+$} %P }
    grid $w.f.cblimitrating -column 0 -row 5 -columnspan 2 -sticky ew
    grid $w.f.sbrating1 -column 0 -row 6 -sticky w
    grid $w.f.sbrating2 -column 1 -row 6 -sticky w

    ttk::checkbutton $w.f.cbmanual -text [::tr "FICSManualConfirm"] -onvalue "manual" -offvalue "auto" -variable ::fics::findopponent(manual)
    grid $w.f.cbmanual -column 0 -row 7 -columnspan 2 -sticky ew
    ttk::checkbutton $w.f.cbformula -text [::tr "FICSFilterFormula"] -onvalue "formula" -offvalue "" -variable ::fics::findopponent(formula)
    grid $w.f.cbformula -column 0 -row 8 -columnspan 2 -sticky ew

    ttk::button $w.seek -text [::tr "FICSIssueSeek"] -command {
      ::fics::syncProfileVars $::fics::login

      set range ""
      if {$::fics::findopponent(limitrating) } {
        set range "$::fics::findopponent(rating1)-$::fics::findopponent(rating2)"
      }
      set cmd "seek $::fics::findopponent(initTime) $::fics::findopponent(incTime) $::fics::findopponent(rated) \
          $::fics::findopponent(color) $::fics::findopponent(manual) $::fics::findopponent(formula) $range"
      ::fics::writechan $cmd
      destroy .ficsfindopp
    }
    ttk::button $w.cancel -text [::tr "Cancel"] -command "destroy $w"
    bind $w <F1> { helpWindow FICSfindOpp}

    packdlgbuttons $w.cancel $w.seek
  }
  ################################################################################
  #
  ################################################################################
  proc readchan {} {
    variable logged

    if {[eof $::fics::sockchan]} {
      fileevent $::fics::sockchan readable {}
      tk_messageBox -title "FICS" -icon error -type ok -message "Network error reading channel"
      ::fics::close "error"
      return
    }

    # switch from read to gets in case a read is done at the middle of a line
    if {! $logged} {
      set line [read $::fics::sockchan]
      foreach l [split $line "\n"] {
        readparse $l
      }
    } else  {
      set line [gets $::fics::sockchan]
      set line [string map {"\a" ""} $line]
      readparse $line
    }

    ::fics::makePremove
  }

  ################################################################################
  # Appends an array to soughtlist if the parameter is correct
  # returns 0 if the line is not parsed and so it is still pending for use
  ################################################################################
  proc parseSoughtLine { l } {
    global ::fics::offers_minelo ::fics::offers_maxelo ::fics::offers_mintime ::fics::offers_maxtime

    # it seems that the first offer starts with a prompt
    if {[string match "fics% *" $l]} {
      set l [string range $l 6 end]
    }

    if { [ catch { if {[llength $l] < 8} { return 0} } ] } { return 0}
    array set ga {}

    set offset 0
    set ga(game) [lindex $l 0]
    if { ! [string is integer $ga(game)] } { return 0}
    set tmp [lindex $l 1]
    if { [scan $tmp "%d" ga(elo)] != 1} { set ga(elo) $offers_minelo }
    if { $ga(elo) < $offers_minelo } { set ga(elo) $offers_minelo }
    set ga(name) [lindex $l 2]

    set tmp [lindex $l 3]
    if { [scan $tmp "%d" ga(time_init)] != 1} { set ga(time_init) $offers_maxtime}
    set tmp [lindex $l 4]
    if { [scan $tmp "%d" ga(time_inc)] != 1} { set ga(time_inc) 0 }

    set ga(rated) [lindex $l 5]
    if {$ga(rated) != "rated" && $ga(rated) != "unrated"} { return 0 }

    set ga(type) [lindex $l 6]
    if { $ga(type) != "untimed" && $ga(type) != "blitz" && $ga(type) != "standard" && $ga(type) != "lightning" } {
      return 0
    }
    set ga(color) ""
    if { [lindex $l 7] == "\[white\]" || [lindex $l 7] == "\[black\]" } {
      set ga(color) [lindex $l 7]
      set offset 1
    }
    set ga(rating_range) [lindex $l [expr 7 + $offset]]
    if { [ catch { set ga(start) [lindex $l [expr 8 + $offset]] } ] } {
      set ga(start) ""
    }

    lappend ::fics::soughtlist [array get ga]
    return 1
  }
  ################################################################################
  # Appends an array to gamesList if the parameter is correct
  # returns 0 if the line is not parsed and so it is still pending for use
  ################################################################################
  proc parseGamesLine { l } {
    # it seems that the first offer starts with a prompt
    set ret 0
    if {[string match "fics% *" $l]} {
      set l [string range $l 6 end]
    }
    set anz [scan $l "%d %s %s %s %s \[%s %d %d" nr welo p1 belo p2 type t1 t2]
    if { $anz == 8 } {
        if { [string length $type] < 3 } {
            set type " $type"
        }
        lappend ::fics::gamesList [list $nr $welo $p1 $belo $p2 $type "$t1 $t2"]
        set ret 1
    }
    return $ret
  }
  ################################################################################
  # Appends an array to playerList if the parameter is correct
  # returns 0 if the line is not parsed and so it is still pending for use
  ################################################################################
  proc parseWhoLine { l } {
    # it seems that the first offer starts with a prompt
    if {[string match "fics% *" $l]} {
      set l [string range $l 6 end]
    }
    if { [string index $l 1] == "+"} {
        # ignore frame around list
        return 1
    }
    if { [string index $l 1] != "|"} {
        return 0
    }
    #Status: X=not open for playing p=playing U=unregistered o=observing a game
    set state [string range $l 5 8]
    set game [string range $l 2 4]
    set l [string range $l 9 end]
    if { [scan $l "%s %s %s %s %s %s" name standard blitz lightning onfor idle] != 6} {
        return 1
    }
    if { $name == "User" } {
        return 1
    }
    set typ ""
    set typ_found [string first "(" $name ]
    if { $typ_found != -1 } {
        set typ [string range $name $typ_found end]
        incr typ_found -1
        set name [string range $name 0 $typ_found]
    }
    if { [string is digit [string index $game 2]] } {
        #set status player is playing
        append state "p"
    }
    if { [string index $idle 0] == "|" } {
        set idle ""
    }
    lappend ::fics::playerList [list $typ $name $state $standard $blitz $lightning $onfor $idle]
    return 1
  }
  ################################################################################
  #
  ################################################################################
  proc readparse {line} {
    variable logged
    variable isGuestLogin

    if {$line == "" || $line == "fics% "} {return}

    if { $::fics::sought } {
      if {[string match "* ad* displayed." $line]} {
        set ::fics::sought 0
        catch { displayOffers }
        return
      }
      # lappend ::fics::soughtlist $line
      if { [ parseSoughtLine $line ] } {
        return
      }
    }
    if { $::fics::games } {
      if {[string match "* ga* displayed." $line]} {
        set ::fics::games 0
        catch {
            sortGames $::fics::sortGamesColumn $::fics::sortGamesOrder
            displayGames
        }
        return
      }
      if { [ parseGamesLine $line ] } {
        return
      }
    }
    if { $::fics::player } {
      if {[string first "Players Displayed" $line] > 0 } {
        set ::fics::player 0
        catch {
            sortPlayers $::fics::sortPlayersColumn $::fics::sortPlayersOrder
            displayPlayers
        }
        return
      }
      if { [ parseWhoLine $line ] } {
        return
      }
    }

    if {[string match "login: " $line]} {
      writechan $::fics::reallogin
      if { $isGuestLogin} {
        set logged 1
      }
      return
    }
    if {[string match "password: " $line]} {
      writechan $::fics::password
      set logged 1
      return
    }
    if {[string match "<sc>*" $line]} {
      set ::fics::seeklist {}
      return
    }
    if {[string match "<s>*" $line]} {
      parseSeek $line
      return
    }
    if {[string match "<sr>*" $line]} {
      removeSeek $line
      return
    }

    if {[string match "<12>*" $line]} {
      parseStyle12 $line
      return
    }

    # puts "readparse->$line"
    updateConsole $line
    if {[string match "Creating: *" $line]} {
      # hide offers graph
      .fics.f.top select 0
      ::utils::sound::PlaySound sound_move
      # Create a game in an opened base
      if {![sc_base inUse]} {
        sc_base switch $::clipbase_db
      }
      sc_game new
      set idx1 [string first "(" $line]
      set white [string trim [string range $line 10 [expr $idx1 -1]] ]
      set idx2 [string first ")" $line]
      set whiteElo [string trim [string range $line [expr $idx1 +1] [expr $idx2 -1]] ]

      set idx1 [expr $idx2 +1]
      set idx2 [string first "(" $line $idx1]
      set black [string trim [string range $line $idx1 [expr $idx2 -1]] ]

      set idx1 [expr $idx2 +1]
      set idx2 [string first ")" $line $idx1]
      set blackElo [string trim [string range $line $idx1 [expr $idx2 -1]] ]

      if { $whiteElo == "++++"} { set whiteElo 0 }
      if { $blackElo == "++++"} { set blackElo 0 }

      sc_game tags set -white $white
      sc_game tags set -whiteElo $whiteElo
      sc_game tags set -black $black
      sc_game tags set -blackElo $blackElo
      sc_game tags set -date "[::utils::date::today year].[::utils::date::today month].[::utils::date::today day]"
      sc_game tags set -site "FICS freechess.org"
      sc_game tags set -event "FICS played [lrange $line 5 6] game"
      sc_game tags set -extra [list "Timecontrol \"[lindex $line 7]+[lindex $line 8]\""]

      if { [::board::isFlipped .main.board] } {
        if { [ string match -nocase $white $::fics::reallogin ] } { ::board::flip .main.board }
      } else {
        if { [ string match -nocase $black $::fics::reallogin ] } { ::board::flip .main.board }
      }
      arrangeClocks
      ::notify::GameChanged
      set ::fics::rated [string equal [lindex $line 5] "rated"]
      # display the win / draw / loss score
      if { $::fics::rated } { ::fics::writechan "assess" "noecho" }
      # it's a new game so show again abort, draw, etc requests
      set ::fics::showabortreq 1
      set ::fics::showadjournreq 1
      set ::fics::showdrawreq 1
      set ::fics::showtakebackreq 1
      return
    }

    if {[string match "\{Game *" $line]} {
      set num [lindex [lindex $line 0] 1]
      set res [lindex $line end]
      set comment [lrange [lindex $line 0] 2 end]
      set n [string first {)} $comment]
      if {$n > -1} {
          set comment [string range $comment $n+2 end]
      }
      sc_pos setComment "[sc_pos getComment]$comment"
      if {$num == $::fics::observedGame} {
        if {[string match "1/2*" $res]} {
          tk_messageBox -title [::tr "Result"] -icon info -type ok -message "Draw\n$comment"
        } else {
          tk_messageBox -title [::tr "Result"] -icon info -type ok -message "$res\n$comment"
        }
        sc_game tags set -result $res
        set ::fics::playing 0
        set ::fics::observedGame -1
        ::gameclock::stop 1
        ::gameclock::stop 2
        updateBoard -pgn
      }
      return
    }

    if { [string match "You are now observing game*" $line] } {
      scan $line "You are now observing game %d." ::fics::observedGame
    }

    # Start session
    if {[string match "*Starting FICS session*" $line]} {

      # mandatory init commands
      writechan "set interface Scid/$::scidVersion ([tk windowingsystem]; $::tcl_platform(os) $::tcl_platform(machine); rv:$::scidVersionDate) Tcl/Tk [info patchlevel]"
      writechan "iset seekremove 1"
      writechan "iset seekinfo 1"
      writechan "style 12"
      writechan "iset nowrap 1"
      writechan "iset nohighlight 1"

      # user init commands
      if { $::fics::usedefaultvars } {
        writechan "set seek 1" ; # be informed of "seek" ads when they are made
        writechan "set silence 1" ; #  turn off shouts, cshouts and channel tells while you play
        writechan "set chanoff 0" ; # stop hearing tells to channels
        writechan "set echo 1" ; # shouts and most other communications will be echoed to you
        writechan "set cshout 0" ; # do not hear cshouts
      }
      setState normal
      return
    }

    if { $::fics::waitForRating == "wait" } {
      if {[catch {set val [lindex $line 0]}]} {
        return
      } else  {
        if {[lindex $line 0] == "Standard"} {
          set ::fics::waitForRating [lindex $line 1]
          return
        }
      }
    }

    if { $::fics::waitForMoves != "" } {
      set m1 ""
      set m2 ""
      set t2 ""
      set t4 ""
      set line [string trim $line]

      # Because some free text may be in the form (".)
      if {[catch {llength $line} err]} {
        puts "Exception $err llength $line"
        return
      }

      if {[llength $line ] == 5 && [scan $line "%d. %s (%d:%d) %s (%d:%d)" t1 m1 t2 t3 m2 t4 t5] != 7} {
        return
      }
      if {[llength $line ] == 3 && [scan $line "%d. %s (%d:%d)" t1 m1 t2 t3] != 4} {
        return
      }
      catch { sc_move addSan $m1 }
      if {$t2 != ""} {
          storeEmtComment 0 $t2 $t3
      }
      if {$m2 != ""} {
        catch { sc_move addSan $m2 }
      }
      if {$t4 != ""} {
          storeEmtComment 0 $t4 $t5
      }

      if {[sc_pos fen] == $::fics::waitForMoves } {
        set ::fics::waitForMoves ""
      }
    }

    if {[string match "Challenge:*" $line]} {
      set ans [tk_messageBox -title [::tr "FICSChallenge"] -icon question -type yesno -message "$line\n\n[tr FICSAccept]" ]
      switch -- $ans {
        yes {writechan "accept"}
        no  {writechan "decline"}
      }
    }

    # abort request
    # for the abort, etc requests, added the "cancel" option so that during this game
    # the message box won't open again for the canceled type of request
    # to avoid "denial of play" attack by the opponent constantly issuing such a request
    # (because  tk_messageBox  "waits for the user to select one of the buttons")
    if {[string match "* would like to abort the game;*" $line] && $::fics::showabortreq} {
      set ans [tk_messageBox -title [::tr Abort] -icon question -type yesnocancel -message "$line\n\n[tr FICSAccept]" ]
      switch -- $ans {
        yes {writechan "accept"}
        no  {writechan "decline"}
        cancel {set ::fics::showabortreq 0}
      }
    }

    # takeback
    if {[string match "* would like to take back *" $line] && $::fics::showtakebackreq} {
      set ans [tk_messageBox -title [tr FICSTakeback] -icon question -type yesnocancel -message "$line\n\n[tr FICSAccept]" ]
      switch -- $ans {
        yes {writechan "accept"}
        no  {writechan "decline"}
        cancel {set ::fics::showtakebackreq 0}
      }
    }

    # draw
    if {[string match "*offers you a draw*" $line] && $::fics::showdrawreq} {
      set ans [tk_messageBox -title [tr Draw] -icon question -type yesnocancel -message "$line\n\n[tr FICSAccept]" ]
      switch -- $ans {
        yes {writechan "accept"}
        no  {writechan "decline"}
        cancel {set ::fics::showdrawreq 0}
      }
    }

    # adjourn
    if {[string match "*would like to adjourn the game*" $line] && $::fics::showadjournreq} {
      set ans [tk_messageBox -title "Abort" -icon question -type yesnocancel -message "$line\n[tr FICSAccept]" ]
      switch -- $ans {
        yes {writechan "accept"}
        no  {writechan "decline"}
        cancel {set ::fics::showadjournreq 0}
      }
    }

    # guest logging
    if {[string match "Logging you in as*" $line]} {
      set line [string map {"\"" "" ";" ""} $line ]
      set ::fics::reallogin [lindex $line 4]
      ::setTitle .fics "Free Internet Chess Server $::fics::reallogin"
    }
    if {[string match "Press return to enter the server as*" $line]} {
      writechan "\n"
    }

  }
  ################################################################################
  #  Set the state of user interface related to connection state
  ################################################################################
  proc setState { state } {
    set w .fics

    foreach elt [winfo children $w.f.bottom.right] {
      if { $elt != "$w.f.bottom.right.cancel" } {
        $elt configure -state $state
      }
    }

    foreach elt [list $w.f.top.fconsole.f2.send $w.f.top.fconsole.f2.cmd ] {
      $elt configure -state $state
    }

    if {$state == "normal" } {
      $w.f.top add $w.f.top.foffers
      $w.f.top add $w.f.top.fgames
      $w.f.top add $w.f.top.fplayer
    } else  {
      $w.f.top hide $w.f.top.foffers
      $w.f.top hide $w.f.top.fgames
      $w.f.top hide $w.f.top.fplayer
    }
  }
  ################################################################################
  #
  ################################################################################
  proc updateConsole {line} {
    set t .fics.f.top.fconsole.f1.console

    if { [string match "* seeking *" $line ] } {
      $t insert end "$line\n" seeking
    } elseif { [string match "\{Game *\}" $line ] } {
      $t insert end "$line\n" game
    } elseif { [string match "\{Game *\} *" $line ] } {
      $t insert end "$line\n" gameresult
    } elseif { [string match "fics% *" $line ] } {
      $t insert end "$line\n" ficspercent
    } elseif  { $line == "Type \[next\] to see next page."  } {
      $t insert end "Click or type \[next\] to see next page.\n" ficshelpnext
    } else  {
      $t insert end "$line\n"
    }

    set pos [ lindex [ .fics.f.top.fconsole.f1.ysc get ] 1 ]
    if {$pos == 1.0} {
      $t yview moveto 1
    }

  }
  ################################################################################
  #
  ################################################################################
  proc removeSeek {line} {
    global ::fics::seeklist
    foreach l $line {

      if { $l == "<sr>" } {continue}

      # remove seek from seeklist
      for {set i 0} {$i < [llength $seeklist]} {incr i} {
        array set a [lindex $seeklist $i]
        if {$a(index) == $l} {
          set seeklist [lreplace $seeklist $i $i]
          break
        }
      }

      # remove seek from graph
      if { $::fics::graphon } {
        for {set idx 0} { $idx < [llength $::fics::soughtlist]} { incr idx } {
          array set g [lindex $::fics::soughtlist $idx]
          set num $g(game)
          if { $num == $l } {
            .fics.f.top.foffers.c delete game_$idx
            break
          }
        }
      }

    }
  }
  ################################################################################
  #
  ################################################################################
  proc parseStyle12 {line} {
    set color [lindex $line 9]
    set gameNumber [lindex $line 16]
    set white [lindex $line 17]
    set black [lindex $line 18]
    set relation [lindex $line 19]
    set initialTime [lindex $line 20]
    set increment [lindex $line 21]
    set whiteMaterial [lindex $line 22]
    set blackMaterial [lindex $line 23]
    set whiteRemainingTime  [lindex $line 24]
    set blackRemainingTime  [lindex $line 25]
    set moveNumber [lindex $line 26]
    set verbose_move [lindex $line 27]
    set moveTime [lindex $line 28]
    set moveSan [lindex $line 29]

    set ::fics::playing $relation
    set ::fics::observedGame $gameNumber

    ::gameclock::setSec 1 [ expr 0 - $whiteRemainingTime ]
    ::gameclock::setSec 2 [ expr 0 - $blackRemainingTime ]
    if {$color == "W"} {
      ::gameclock::start 1
      ::gameclock::stop 2
    } else {
      ::gameclock::start 2
      ::gameclock::stop 1
    }

    set fen ""
    for {set i 1} {$i <=8} { incr i} {
      set l [lindex $line $i]
      set count 0

      for { set col 0 } { $col < 8 } { incr col } {
        set c [string index $l $col]
        if { $c == "-"} {
          incr count
        } else {
          if {$count != 0} {
            set fen "$fen$count"
            set count 0
          }
          set fen "$fen$c"
        }
      }

      if {$count != 0} { set fen "$fen$count" }
      if {$i != 8} { set fen "$fen/" }
    }

    set fen "$fen [string tolower $color]"
    set f [lindex $line 10]

    # en passant
    if { $f == "-1" || $verbose_move == "none"} {
      set enpassant "-"
    } else {
      set enpassant "-"
      set conv "abcdefgh"
      set fl [string index $conv $f]
      if {$color == "W"} {
        if { [ string index [lindex $line 4] [expr $f - 1]] == "P" || [ string index [lindex $line 4] [expr $f + 1]] == "P" } {
          set enpassant "${fl}6"
        }
      } else {
        if { [ string index [lindex $line 5] [expr $f - 1]] == "p" || [ string index [lindex $line 5] [expr $f + 1]] == "p" } {
          set enpassant "${fl}3"
        }
      }
    }

    set castle ""
    if {[lindex $line 11] == "1"} {set castle "${castle}K"}
    if {[lindex $line 12] == "1"} {set castle "${castle}Q"}
    if {[lindex $line 13] == "1"} {set castle "${castle}k"}
    if {[lindex $line 14] == "1"} {set castle "${castle}q"}
    if {$castle == ""} {set castle "-"}

    set fen "$fen $castle $enpassant [lindex $line 15] $moveNumber"

    # try to play the move and check if fen corresponds. If not this means the position needs to be set up.
    if {$moveSan != "none" && $::fics::playing != -1} {
      # first check side's coherency
      if { ([sc_pos side] == "white" && $color == "B") || ([sc_pos side] == "black" && $color == "W") } {
        # puts "sc_move addSan $moveSan"
        ::utils::sound::PlaySound sound_move
        ::utils::sound::AnnounceNewMove $moveSan
        if { [catch { sc_move addSan $moveSan } err ] } {
          puts "error $err"
        } else {
          if {  $::fics::playing == 1 } {
              ::fics::storeTime
          } else {
              set t1 ""; set t2 ""
              if { [scan $moveTime "(%d:%d)" t1 t2] == 2} {
                  storeEmtComment 0 $t1 $t2
              }
          }
          if { $::novag::connected } {
            set m $verbose_move
            if { [string index $m 1] == "/" } { set m [string range $m 2 end] }
            set m [string map { "-" "" "=" "" } $m]
            ::novag::addMove $m
          }
          updateBoard -pgn -animate
        }
      }
    }

    if {$fen != [sc_pos fen]} {
      # Create a game in an opened base
      if {![sc_base inUse]} {
        sc_base switch $::clipbase_db
      }
      sc_game new

      set ::fics::waitForRating "wait"
      writechan "finger $white /s"
      vwaitTimed ::fics::waitForRating 2000 "nowarn"
      if {$::fics::waitForRating == "wait"} { set ::fics::waitForRating "0" }
      sc_game tags set -white $white
      sc_game tags set -whiteElo $::fics::waitForRating

      set ::fics::waitForRating "wait"
      writechan "finger $black /s"
      vwaitTimed ::fics::waitForRating 2000 "nowarn"
      if {$::fics::waitForRating == "wait"} { set ::fics::waitForRating "0" }
      sc_game tags set -black $black
      sc_game tags set -blackElo $::fics::waitForRating

      set ::fics::waitForRating ""

      sc_game tags set -site "FICS freechess.org"
      sc_game tags set -event "FICS observed game"
      sc_game tags set -extra [list "Timecontrol \"$initialTime+$increment\""]
      sc_game tags set -date "[::utils::date::today year].[::utils::date::today month].[::utils::date::today day]"

      # try to get first moves of game
      writechan "moves $gameNumber"
      set ::fics::waitForMoves $fen
      vwaitTimed ::fics::waitForMoves 2000 "nowarn"
      set ::fics::waitForMoves ""

      # Did not manage to reconstruct the game, just set its position
      if {$fen != [sc_pos fen]} {
        sc_game startBoard $fen
      }
      ::notify::GameChanged
    }
  }
  ################################################################################
  #
  ################################################################################
  proc parseSeek {line} {
    array set seekelt {}
    set seekelt(index) [lindex $line 1]
    foreach m [split $line] {
      if {[string match "w=*" $m]} { set seekelt(name_from) [string range $m 2 end] ; continue }
      if {[string match "ti=*" $m]} { set seekelt(titles) [string range $m 3 end] ; continue }
      if {[string match "rt=*" $m]} { set seekelt(rating) [string range $m 3 end] ; continue }
      if {[string match "t=*" $m]} { set seekelt(time) [string range $m 2 end] ; continue }
      if {[string match "i=*" $m]} { set seekelt(increment) [string range $m 2 end] ; continue }
      if {[string match "r=*" $m]} { set seekelt(rated) [string range $m 2 end] ; continue }
      if {[string match "tp=*" $m]} { set seekelt(type) [string range $m 3 end] ; continue }
      if {[string match "c=*" $m]} { set seekelt(color) [string range $m 2 end] ; continue }
      if {[string match "rr=*" $m]} { set seekelt(rating_range) [string range $m 3 end] ; continue }
      if {[string match "a=*" $m]} { set seekelt(automatic) [string range $m 2 end] ; continue }
      if {[string match "f=*" $m]} { set seekelt(formula_checked) [string range $m 2 end] ; continue }
    }
    lappend ::fics::seeklist [array get seekelt]
  }
  ################################################################################
  #
  ################################################################################
  proc updateOffers { } {
    set ::fics::sought 1
    set ::fics::soughtlist {}
    writechan "sought"
    vwaitTimed ::fics::sought 5000 "nowarn"
    after 3000 ::fics::updateOffers
  }
  ################################################################################
  #
  ################################################################################
  proc updateGames { } {
    if { ![winfo exists .fics] ||
         [ .fics.f.top select ] != ".fics.f.top.fgames" } { return }
    set ::fics::games 1
    set ::fics::gamesList {}
    ::fics::writechan "games"
    vwaitTimed ::fics::games 5000 "nowarn"
    after 20000 ::fics::updateGames
  }
  ################################################################################
  #
  ################################################################################
  proc updatePlayer { } {
    if { ![winfo exists .fics] ||
         [ .fics.f.top select ] != ".fics.f.top.fplayer" } { return }
    set ::fics::player 1
    set ::fics::playerList {}
    if { $::fics::showOnlyRegisteredPlayer } {
        set command "who Rv"
    } else {
        set command "who v"
    }
    writechan $command
    vwaitTimed ::fics::player 5000 "nowarn"
    after 40000 ::fics::updatePlayer
  }
  ################################################################################
  #
  ################################################################################
  proc configureCanvas {} {
    set w .fics.f.top.foffers
    set ::fics::height [winfo height $w]
    set ::fics::width [winfo width $w]
    $w.c configure -width $::fics::width -height $::fics::height
    displayOffers
  }
  ################################################################################
  #
  ################################################################################
  proc displayOffers { } {
    global ::fics::width ::fics::height ::fics::off \
        ::fics::offers_minelo ::fics::offers_maxelo ::fics::offers_mintime ::fics::offers_maxtime
    after cancel ::fics::updateOffers

    set w .fics.f.top.foffers
    set size 5
    set idx 0

    #first erase the canvas
    foreach id [ $w.c find all] { $w.c delete $id }

    # Draw horizontal lines
    set y_unit [expr $height / 32.0]
    for {set i 0} {$i < 32} {incr i} {
      set y [expr $height - $i * $y_unit]
      $w.c create line 0 $y $width $y -fill "light gray"
    }

    # Draw horizontal tics and labels
    set x1_tick [expr $width - $off]
    set x_text [expr $width - 2]
    foreach elo [list 5 10 15 20 25 30] {
      set y [expr $height - $elo * $y_unit]
      $w.c create line $x1_tick $y $width $y -fill black
      $w.c create text $x_text $y -fill black -anchor se -text [expr $elo * 100]
    }

    # Draw vertical lines, tics and labels
    set x_unit [expr ($width - 3 * $off) / 60.0]
    set y2_tick [expr $height - $off]
    foreach t [list 2 5 10 15 30 60] {
      set x [expr $t * $x_unit + $off]
      $w.c create line $x $height $x 0 -fill "light gray"
      $w.c create line $x $height $x $y2_tick -fill black
      $w.c create text [expr $x + 2] $height -fill black -anchor sw -text "${t}m"
    }

    foreach g $::fics::soughtlist {
      array set l $g
      set fillcolor green
      # if the time is too large, put it in red
      set tt [expr $l(time_init) + $l(time_inc) * 2 / 3 ]
      if { $tt > $offers_maxtime } {
        set tt $offers_maxtime
        set fillcolor red
      }
      # if a computer, put it in blue
      if { [string match "*(C)" $l(name)] } {
        set fillcolor blue
      }
      # if player without ELO, in gray
      if { [string match "Guest*" $l(name)] } {
        set fillcolor gray
      }

      set x [expr $tt * $x_unit + $off]
      set y [expr $height - ($l(elo) / 100.0) * $y_unit]

      if { $l(rated) == "rated" } {
        set object "oval"
      } else {
        set object "rectangle"
      }
      $w.c create $object [expr $x - $size ] [expr $y - $size ] [expr $x + $size ] [expr $y + $size ] -tag game_$idx -fill $fillcolor

      $w.c bind game_$idx <Enter> "::fics::setOfferStatus $idx %x %y"
      $w.c bind game_$idx <Leave> "::fics::setOfferStatus -1 %x %y"
      $w.c bind game_$idx <ButtonPress> "::fics::getOffersGame $idx"
      incr idx
    }

  }
  ################################################################################
  #
  ################################################################################
  proc clickGames {{w} {x} {y} {layout}} {
      lassign [$w identify $x $y] what
      if {$what == "heading"} {
          set col [string index [$w identify column $x $y] 1]
          incr col -1
          set sort [lindex $layout $col]
          if { $sort ne "nosort" } {
              sortGames $col $sort
              displayGames
          }
      }
  }

  proc sortGames { column sort } {
      set ::fics::sortGamesColumn $column
      set ::fics::sortGamesOrder $sort
      set ::fics::gamesList [lsort -dictionary $::fics::sortGamesOrder -index $::fics::sortGamesColumn $::fics::gamesList]
  }

  proc displayGames { } {
      set w .fics.f.top.fgames
      set i 1
      $w.glist delete [$w.glist children {}]
      foreach game $::fics::gamesList {
          set nr [lindex $game 0]
          set type [lindex $game 5]
          set show_ru 0
          set ru [string index $type 2]
          if { ( $::fics::showRatedGames && $ru == "r") ||
               ( $::fics::showUnratedGames && $ru == "u" ) } {
              set show_ru 1
          }
          set show_sbl 0
          set sbl [string index $type 1]
          if { ( $::fics::showStandardGames && $sbl == "s" ) ||
               ( $::fics::showBlitzGames && $sbl == "b" ) ||
               ( $::fics::showLightningGames && $sbl == "l" ) } {
              set show_sbl 1
          }
          if { $show_ru && $show_sbl } {
              if { $ru == "r" } {
                  set rated [tr FICSRated]
              } else {
                  set rated [tr FICSUnrated]
              }
              switch -- $sbl {
                  s { set type "Standard"}
                  b { set type "Blitz"}
                  l { set type "Lightning"}
              }
              lset game 5 $type
              set game [linsert $game 6 $rated]
              $w.glist insert {} end -id $i -values $game
              if { $nr == $::fics::gameSelection } { $w.glist selection set $i }
              incr i
          }
      }
  }
  ################################################################################
  #
  ################################################################################
  proc clickPlayers {{w} {x} {y} {layout}} {
      lassign [$w identify $x $y] what
      if {$what == "heading"} {
          set col [string index [$w identify column $x $y] 1]
          incr col -1
          set sort [lindex $layout $col]
          sortPlayers $col $sort
          displayPlayers
      }
  }

  proc sortPlayers { column sort } {
      set ::fics::sortPlayersColumn $column
      set ::fics::sortPlayersOrder $sort
      set ::fics::playerList [lsort -dictionary $::fics::sortPlayersOrder -index $::fics::sortPlayersColumn $::fics::playerList]
  }

  proc displayPlayers { } {
      set w .fics.f.top.fplayer
      set i 1
      $w.plist delete [$w.plist children {}]
      foreach player $::fics::playerList {
          set state [lindex $player 2]
          if { ! $::fics::showOnlyFreePlayer || ! ([string first "X" $state] >= 0 || [string first "p" $state] >= 0 ) } {
              set typ [lindex $player 0]
              set name [lindex $player 1]
              #remove braces around a typ e.g. (C) -> C
              lset player 0 [string map { ")(" " " "(" "" ")" " "} $typ]
              $w.plist insert {} end -id $i -values $player
              if { $name == $::fics::playerSelection } { $w.plist selection set $i }
              incr i
          }
      }
  }
  ################################################################################
  # Play the selected game
  ################################################################################
  proc getOffersGame { idx } {
    array set ga [lindex $::fics::soughtlist $idx]
    catch { writechan "play $ga(game)" }
  }
  ################################################################################
  #
  ################################################################################
  proc setOfferStatus { idx x y } {
    global ::fics::height ::fics::width ::fics::off

    set w .fics.f.top.foffers
    if { $idx != -1 } {
      set gl [lindex $::fics::soughtlist $idx]
      if { $gl == "" } { return }
      array set l [lindex $::fics::soughtlist $idx]
      set m "$l(game) $l(name)($l(elo))\n$l(time_init)/$l(time_inc) $l(rated)\n$l(color) $l(start)"

      if {$y < [expr $height / 2]} {
        set anchor "n"
      } else {
        set anchor "s"
      }

      if {$x < [expr $width / 2]} {
        append anchor "w"
      } else {
        append anchor "e"
      }

      $w.c create text [expr $x + $off] $y -tags status -text $m -font font_offers -anchor $anchor
      $w.c raise game_$idx
    } else {
      $w.c delete status
    }
  }
  ################################################################################
  #
  ################################################################################
  proc play {index} {
    writechan "play $index"
    # set ::fics::playing 1
    set ::fics::observedGame $index
  }
  ################################################################################
  #
  ################################################################################
  proc writechan {line {echo "noecho"}} {
    if { $::fics::sockchan == "" } { return }
    after cancel ::fics::stayConnected
    if {[eof $::fics::sockchan]} {
      tk_messageBox -title "FICS" -icon error -type ok -message "Network error writing channel"
      ::fics::close "error"
      return
    }
    puts $::fics::sockchan $line
    if {$echo != "noecho"} {
      updateConsole "->>$line"
    }
    after 2700000 ::fics::stayConnected
  }
  ################################################################################
  # FICS seems to close connexion after 1 hr idle. So send a dummy command
  # every 45 minutes
  ################################################################################
  proc stayConnected {} {
    catch {
      writechan "date" "noecho"
      after 2700000 ::fics::stayConnected
    }
  }
  ################################################################################
  #  returns 1 if premove is set
  ################################################################################
  proc setPremove {sq1 sq2} {
      if { $::fics::premoveEnabled && $::fics::playing == -1 && $sq2 != -1 } {
          set ::fics::premoveSq1 $sq1
          set ::fics::premoveSq2 $sq2
          ::board::mark::DrawArrow .main.board.bd $sq2 $sq1 $::highlightLastMoveColor
          return 1
      }
      return 0
  }
  ################################################################################
  #  execute FICS premove if possible
  ################################################################################
  proc makePremove {} {
    if { $::fics::premoveEnabled && $::fics::playing == 1 && $::fics::premoveSq1 != -1 } {
      addMove $::fics::premoveSq1 $::fics::premoveSq2
      set ::fics::premoveSq1 -1
    }
  }
  ################################################################################
  #   returns 1 if the player is allowed to enter a move (either playing or using puzzlebot)
  ################################################################################
  proc playerCanMove {} {

    if { ! [winfo exists .fics] } { return 1 }

    if { [sc_game info white] == "puzzlebot" || [sc_game info black] == "puzzlebot" } {
      return 1
    }

    if { $::fics::playing == 1 } { return 1 }

    if { $::fics::premoveEnabled && $::fics::playing == -1 } {
        .main.board.bd delete mark
        set ::fics::premoveSq1 -1
        return 1
    }
    return 0
  }
  ################################################################################
  # Handle mouse button 1 on console : observe the selected game
  # or handle commands (like <next>)
  ################################################################################
  proc consoleClick { x y win } {
    set idx [ $win index @$x,$y ]
    if { [ scan $idx "%d.%d" l c ] != 2 } {
      # should never happen
      return
    }
    set elt [$win get $l.0 $l.end]

    if { $elt == "Click or type \[next\] to see next page." } {
      writechan "next"
      return
    }

    regsub -all {\s+} [string trim $elt] " " elt
    set elt [split $elt " "]
    set found 0

    if { [llength $elt] > 4} {
      # validate format
      set game [lindex $elt 0]
      set elow [lindex $elt 1]
      set white [lindex $elt 2]
      set elob [lindex $elt 3]
      set black [lindex $elt 4]

      if { [ scan $game "%d" tmp ] != 1 || \
            ( [ scan $elow "%d" tmp ] != 1 && $elow != "++++" ) || \
            ( [ scan $elob "%d" tmp ] != 1 && $elob != "++++" ) } {
      } else  {
        set found 1
      }
    }

    # Second chance : try to parse "tell relay listgames" (:104 GMxxxx GMyyyyy * B22)
    if { [llength $elt] == 5 && ! $found } {
      if { [ scan [lindex $elt 0] ":%d" game ] == 1 } {
        set white [lindex $elt 1]
        set black [lindex $elt 2]
        set elow "-"
        set elob "-"
        set found 1
      }
    }

    if { ! $found } {
      puts "$elt not a valid game"
      return
    }

    # warn the user before observing a game because it can interfere with a game played or
    # other that would be disturbed by observing a game
    set ans [tk_messageBox -title "Observe game" -icon question -type yesno \
        -message "[ ::tr FICSObserveconfirm ] $game\n$white ($elow) - $black ($elob)  ?" ]
    if { $ans == yes } {
      writechan "unobserve" "echo"
      writechan "observe $game" "echo"
    }

  }
  ################################################################################
  # updates the offers view if it is visible
  ################################################################################
  proc tabchanged {} {
    after cancel ::fics::updateGames
    after cancel ::fics::updateOffers
    after cancel ::fics::updatePlayer
    set ::fics::graphon 0
    set ::fics::sought 0
    set ::fics::games 0
    set ::fics::player 0
    switch [ .fics.f.top select ] {
      .fics.f.top.fgames {
          updateGames
      }
      .fics.f.top.fplayer {
          updatePlayer
      }
      .fics.f.top.foffers {
          updateOffers
          set ::fics::graphon 1
      }
    }
  }
  ################################################################################
  #
  ################################################################################
  proc close { {mode ""} } {
    variable logged
    # stop recursive call
    bind .fics <Destroy> {}
    # avoid error on closing via x-Button
    .fics.f.top.fconsole.f1.console configure -yscrollcommand ""

    set ::fics::sought 0
    after cancel ::fics::updateOffers
    after cancel ::fics::updateGames
    after cancel ::fics::updatePlayer
    after cancel ::fics::stayConnected
    set logged 0

    if {$mode != "error"} {
      writechan "exit"
    }

    set ::fics::playing 0
    set ::fics::games 0
    set ::fics::player 0
    set ::fics::observedGame -1
    if { $::fics::sockchan ne "" } {
        ::close $::fics::sockchan
        set ::fics::sockchan ""
    }
    if { ! $::windowsOS } { catch { exec -- kill -s INT [ $::fics::timeseal_pid ] }  }
    ::win::closeWindow .fics
  }
}
###
### End of file: fics.tcl
###