]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
c4c9c3699f8d9d8ccbaf9365e721611c3cf99960
[remoteglot] / remoteglot.pl
1 #! /usr/bin/perl
2
3 #
4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 #              analysis, or for live analysis of relayed games. (Do not use for
6 #              cheating! Cheating is bad for your karma, and your abuser flag.)
7 #
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
10 #
11
12 use Net::Telnet;
13 use FileHandle;
14 use IPC::Open2;
15 use Time::HiRes;
16 use strict;
17 use warnings;
18
19 # Configuration
20 my $server = "freechess.org";
21 my $target = "GMCarlsen";
22 my $engine = "'./Deep Rybka 4 SSE42 x64'";
23 my $telltarget = undef;   # undef to be silent
24 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960);  # after each move
25 my $uci_assume_full_compliance = 0;                    # dangerous :-)
26 my @masters = (
27         'Sesse',
28         'Sessse',
29         'Sesssse',
30         'greatestguns',
31         'beuki'
32 );
33
34 # Program starts here
35 $SIG{ALRM} = sub { output_screen(); };
36
37 $| = 1;
38
39 open(FICSLOG, ">ficslog.txt")
40         or die "ficslog.txt: $!";
41 print FICSLOG "Log starting.\n";
42 select(FICSLOG);
43 $| = 1;
44
45 open(UCILOG, ">ucilog.txt")
46         or die "ucilog.txt: $!";
47 print UCILOG "Log starting.\n";
48 select(UCILOG);
49 $| = 1;
50 select(STDOUT);
51
52 # open the chess engine
53 my $pid = IPC::Open2::open2(*UCIREAD, *UCIWRITE, $engine);
54 my %uciinfo = ();
55 my %uciid = ();
56 my ($last_move, $last_tell);
57 my $last_text = '';
58 my $last_told_text = '';
59 my ($pos_waiting, $pos_calculating);
60
61 uciprint("uci");
62
63 # gobble the options
64 while (<UCIREAD>) {
65         /uciok/ && last;
66         handle_uci($_);
67 }
68
69 uciprint("setoption name UCI_AnalyseMode value true");
70 # uciprint("setoption name NalimovPath value /srv/tablebase");
71 uciprint("setoption name NalimovUsage value Rarely");
72 uciprint("setoption name Hash value 1024");
73 # uciprint("setoption name MultiPV value 2");
74 uciprint("ucinewgame");
75
76 print "Chess engine ready.\n";
77
78 # now talk to FICS
79 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
80 $t->input_log(\*FICSLOG);
81 $t->open($server);
82 $t->print("SesseBOT");
83 $t->waitfor('/Press return to enter the server/');
84 $t->cmd("");
85
86 # set some options
87 $t->cmd("set shout 0");
88 $t->cmd("set seek 0");
89 $t->cmd("set style 12");
90 $t->cmd("observe $target");
91
92 # main loop
93 print "FICS ready.\n";
94 while (1) {
95         my $rin = '';
96         my $rout;
97         vec($rin, fileno(UCIREAD), 1) = 1;
98         vec($rin, fileno($t), 1) = 1;
99
100         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
101         my $sleep = 1.0;
102
103         while (1) {
104                 my $line = $t->getline(Timeout => 0, errmode => 'return');
105                 last if (!defined($line));
106
107                 chomp $line;
108                 $line =~ tr/\r//d;
109                 if ($line =~ /^<12> /) {
110                         my $pos = style12_to_fen($line);
111                         
112                         # if this is already in the queue, ignore it
113                         next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
114
115                         # if we're already chewing on this and there's nothing else in the queue,
116                         # also ignore it
117                         next if (!defined($pos_waiting) && defined($pos_calculating) &&
118                                  $pos->{'fen'} eq $pos_calculating->{'fen'});
119
120                         # if we're already thinking on something, stop and wait for the engine
121                         # to approve
122                         if (defined($pos_calculating)) {
123                                 if (!defined($pos_waiting)) {
124                                         uciprint("stop");
125                                 }
126                                 if ($uci_assume_full_compliance) {
127                                         $pos_waiting = $pos;
128                                 } else {
129                                         uciprint("position fen " . $pos->{'fen'});
130                                         uciprint("go infinite");
131                                         $pos_calculating = $pos;
132                                 }
133                         } else {
134                                 # it's wrong just to give the FEN (the move history is useful,
135                                 # and per the UCI spec, we should really have sent "ucinewgame"),
136                                 # but it's easier
137                                 uciprint("position fen " . $pos->{'fen'});
138                                 uciprint("go infinite");
139                                 $pos_calculating = $pos;
140                         }
141
142                         %uciinfo = ();
143                         $last_move = time;
144
145                         # 
146                         # Output a command every move to note that we're
147                         # still paying attention -- this is a good tradeoff,
148                         # since if no move has happened in the last half
149                         # hour, the analysis/relay has most likely stopped
150                         # and we should stop hogging server resources.
151                         #
152                         $t->cmd("date");
153                 }
154                 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
155                         my ($who, $msg) = ($1, $2);
156
157                         next if (grep { $_ eq $who } (@masters) == 0);
158         
159                         if ($msg =~ /^fics (.*?)$/) {
160                                 $t->cmd("tell $who Executing '$1' on FICS.");
161                                 $t->cmd($1);
162                         } elsif ($msg =~ /^uci (.*?)$/) {
163                                 $t->cmd("tell $who Sending '$1' to the engine.");
164                                 print UCIWRITE "$1\n";
165                         } else {
166                                 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
167                         }
168                 }
169                 #print "FICS: [$line]\n";
170                 $sleep = 0;
171         }
172         
173         # any fun on the UCI channel?
174         if ($nfound > 0 && vec($rout, fileno(UCIREAD), 1) == 1) {
175                 # 
176                 # Read until we've got a full line -- if the engine sends part of
177                 # a line and then stops we're pretty much hosed, but that should
178                 # never happen.
179                 #
180                 my $line = '';
181                 while ($line !~ /\n/) {
182                         my $tmp;
183                         my $ret = sysread UCIREAD, $tmp, 1;
184
185                         if (!defined($ret)) {
186                                 next if ($!{EINTR});
187                                 die "error in reading from the UCI engine: $!";
188                         } elsif ($ret == 0) {
189                                 die "EOF from UCI engine";
190                         }
191
192                         $line .= $tmp;
193                 }
194
195                 $line =~ tr/\r\n//d;
196                 handle_uci($line);
197                 $sleep = 0;
198
199                 # don't update too often
200                 Time::HiRes::alarm(0.2);
201         }
202
203         sleep $sleep;
204 }
205
206 sub handle_uci {
207         my ($line) = @_;
208
209         chomp $line;
210         $line =~ tr/\r//d;
211         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
212         print UCILOG localtime() . " <= $line\n";
213         if ($line =~ /^info/) {
214                 my (@infos) = split / /, $line;
215                 shift @infos;
216
217                 parse_infos(@infos);
218         }
219         if ($line =~ /^id/) {
220                 my (@ids) = split / /, $line;
221                 shift @ids;
222
223                 parse_ids(@ids);
224         }
225         if ($line =~ /^bestmove/ && $uci_assume_full_compliance) {
226                 if (defined($pos_waiting)) {
227                         uciprint("position fen " . $pos_waiting->{'fen'});
228                         uciprint("go infinite");
229
230                         $pos_calculating = $pos_waiting;
231                         $pos_waiting = undef;
232                 }
233         }
234 }
235
236 sub parse_infos {
237         my (@x) = @_;
238         my $mpv = '';
239
240         while (scalar @x > 0) {
241                 if ($x[0] =~ 'multipv') {
242                         shift @x;
243                         $mpv = shift @x;
244                         next;
245                 }
246                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
247                         my $key = shift @x;
248                         my $value = shift @x;
249                         $uciinfo{$key} = $value;
250                         next;
251                 }
252                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
253                         my $key = shift @x;
254                         my $value = shift @x;
255                         $uciinfo{$key . $mpv} = $value;
256                         next;
257                 }
258                 if ($x[0] eq 'score') {
259                         shift @x;
260
261                         delete $uciinfo{'score_cp' . $mpv};
262                         delete $uciinfo{'score_mate' . $mpv};
263
264                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
265                                 if ($x[0] eq 'cp') {
266                                         shift @x;
267                                         $uciinfo{'score_cp' . $mpv} = shift @x;
268                                 } elsif ($x[0] eq 'mate') {
269                                         shift @x;
270                                         $uciinfo{'score_mate' . $mpv} = shift @x;
271                                 } else {
272                                         shift @x;
273                                 }
274                         }
275                         next;
276                 }
277                 if ($x[0] eq 'pv') {
278                         $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
279                         last;
280                 }
281                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
282                         last;
283                 }
284
285                 #print "unknown info '$x[0]', trying to recover...\n";
286                 #shift @x;
287                 die "Unknown info '" . join(',', @x) . "'";
288
289         }
290 }
291
292 sub parse_ids {
293         my (@x) = @_;
294
295         while (scalar @x > 0) {
296                 if ($x[0] =~ /^(name|author)$/) {
297                         my $key = shift @x;
298                         my $value = join(' ', @x);
299                         $uciid{$key} = $value;
300                         last;
301                 }
302
303                 # unknown
304                 shift @x;
305         }
306 }
307
308 sub style12_to_fen {
309         my $str = shift;
310         my %pos = ();
311         my (@x) = split / /, $str;
312         
313         $pos{'board'} = [ @x[1..8] ];
314         $pos{'toplay'} = $x[9];
315         
316         # the board itself
317         my (@board) = @x[1..8];
318         for my $rank (0..7) {
319                 $board[$rank] =~ s/(-+)/length($1)/ge;
320         }
321         my $fen = join('/', @board);
322
323         # white/black to move
324         $fen .= " ";
325         $fen .= lc($x[9]);
326
327         # castling
328         my $castling = "";
329         $castling .= "K" if ($x[11] == 1);
330         $castling .= "Q" if ($x[12] == 1);
331         $castling .= "k" if ($x[13] == 1);
332         $castling .= "q" if ($x[14] == 1);
333         $castling = "-" if ($castling eq "");
334         # $castling = "-"; # chess960
335         $fen .= " ";
336         $fen .= $castling;
337
338         # en passant
339         my $ep = "-";
340         if ($x[10] != -1) {
341                 my $col = $x[10];
342                 my $nep = (qw(a b c d e f g h))[$col];
343
344                 if ($x[9] eq 'B') {
345                         $nep .= "3";
346                 } else {
347                         $nep .= "6";
348                 }
349
350                 #
351                 # Showing the en passant square when actually no capture can be made
352                 # seems to confuse at least Rybka. Thus, check if there's actually
353                 # a pawn of the opposite side that can do the en passant move, and if
354                 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
355                 # "right" thing as per the standard, though.
356                 #
357                 if ($x[9] eq 'B') {
358                         $ep = $nep if ($col > 0 && substr($pos{'board'}[4], $col-1, 1) eq 'p');
359                         $ep = $nep if ($col < 7 && substr($pos{'board'}[4], $col+1, 1) eq 'p');
360                 } else {
361                         $ep = $nep if ($col > 0 && substr($pos{'board'}[3], $col-1, 1) eq 'P');
362                         $ep = $nep if ($col < 7 && substr($pos{'board'}[3], $col+1, 1) eq 'P');
363                 }
364         }
365         $fen .= " ";
366         $fen .= $ep;
367
368         # half-move clock
369         $fen .= " ";
370         $fen .= $x[15];
371
372         # full-move clock
373         $fen .= " ";
374         $fen .= $x[26];
375
376         $pos{'fen'} = $fen;
377         $pos{'move_num'} = $x[26];
378         $pos{'last_move'} = $x[29];
379
380         return \%pos;
381 }
382
383 sub prettyprint_pv {
384         my ($board, @pvs) = @_;
385
386         if (scalar @pvs == 0 || !defined($pvs[0])) {
387                 return ();
388         }
389         
390         my @nb = @$board;
391
392         my $pv = shift @pvs;
393         my $from_col = ord(substr($pv, 0, 1)) - ord('a');
394         my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
395         my $to_col   = ord(substr($pv, 2, 1)) - ord('a');
396         my $to_row   = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
397
398         my $pretty;
399         my $piece = substr($board->[$from_row], $from_col, 1);
400
401         if ($piece eq '-') {
402                 die "Invalid move $pv";
403         }
404
405         # white short castling
406         if ($pv eq 'e1g1' && $piece eq 'K') {
407                 # king
408                 substr($nb[7], 4, 1, '-');
409                 substr($nb[7], 6, 1, $piece);
410                 
411                 # rook
412                 substr($nb[7], 7, 1, '-');
413                 substr($nb[7], 5, 1, 'R');
414                                 
415                 return ('0-0', prettyprint_pv(\@nb, @pvs));
416         }
417
418         # white long castling
419         if ($pv eq 'e1c1' && $piece eq 'K') {
420                 # king
421                 substr($nb[7], 4, 1, '-');
422                 substr($nb[7], 2, 1, $piece);
423                 
424                 # rook
425                 substr($nb[7], 0, 1, '-');
426                 substr($nb[7], 3, 1, 'R');
427                                 
428                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
429         }
430
431         # black short castling
432         if ($pv eq 'e8g8' && $piece eq 'k') {
433                 # king
434                 substr($nb[0], 4, 1, '-');
435                 substr($nb[0], 6, 1, $piece);
436                 
437                 # rook
438                 substr($nb[0], 7, 1, '-');
439                 substr($nb[0], 5, 1, 'r');
440                                 
441                 return ('0-0', prettyprint_pv(\@nb, @pvs));
442         }
443
444         # black long castling
445         if ($pv eq 'e8c8' && $piece eq 'k') {
446                 # king
447                 substr($nb[0], 4, 1, '-');
448                 substr($nb[0], 2, 1, $piece);
449                 
450                 # rook
451                 substr($nb[0], 0, 1, '-');
452                 substr($nb[0], 3, 1, 'r');
453                                 
454                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
455         }
456
457         # check if the from-piece is a pawn
458         if (lc($piece) eq 'p') {
459                 # attack?
460                 if ($from_col != $to_col) {
461                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
462
463                         # en passant?
464                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
465                                 if ($piece eq 'p') {
466                                         substr($nb[$to_row + 1], $to_col, 1, '-');
467                                 } else {
468                                         substr($nb[$to_row - 1], $to_col, 1, '-');
469                                 }
470                         }
471                 } else {
472                         $pretty = substr($pv, 2, 2);
473
474                         if (length($pv) == 5) {
475                                 # promotion
476                                 $pretty .= "=";
477                                 $pretty .= uc(substr($pv, 4, 1));
478
479                                 if ($piece eq 'p') {
480                                         $piece = substr($pv, 4, 1);
481                                 } else {
482                                         $piece = uc(substr($pv, 4, 1));
483                                 }
484                         }
485                 }
486         } else {
487                 $pretty = uc($piece);
488
489                 # see how many of these pieces could go here, in all
490                 my $num_total = 0;
491                 for my $col (0..7) {
492                         for my $row (0..7) {
493                                 next unless (substr($board->[$row], $col, 1) eq $piece);
494                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
495                         }
496                 }
497
498                 # see how many of these pieces from the given row could go here
499                 my $num_row = 0;
500                 for my $col (0..7) {
501                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
502                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
503                 }
504                 
505                 # and same for columns
506                 my $num_col = 0;
507                 for my $row (0..7) {
508                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
509                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
510                 }
511                 
512                 # see if we need to disambiguate
513                 if ($num_total > 1) {
514                         if ($num_col == 1) {
515                                 $pretty .= substr($pv, 0, 1);
516                         } elsif ($num_row == 1) {
517                                 $pretty .= substr($pv, 1, 1);
518                         } else {
519                                 $pretty .= substr($pv, 0, 2);
520                         }
521                 }
522
523                 # attack?
524                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
525                         $pretty .= 'x';
526                 }
527
528                 $pretty .= substr($pv, 2, 2);
529         }
530
531         # update the board
532         substr($nb[$from_row], $from_col, 1, '-');
533         substr($nb[$to_row], $to_col, 1, $piece);
534
535         if (in_mate(\@nb)) {
536                 $pretty .= '#';
537         } elsif (in_check(\@nb) ne 'none') {
538                 $pretty .= '+';
539         }
540
541         return ($pretty, prettyprint_pv(\@nb, @pvs));
542 }
543
544 sub output_screen {
545         #return;
546         
547         return if (!defined($pos_calculating));
548
549         #
550         # Check the PVs first. if they're invalid, just wait, as our data
551         # is most likely out of sync. This isn't a very good solution, as
552         # it can frequently miss stuff, but it's good enough for most users.
553         #
554         eval {
555                 my $dummy;
556                 if (exists($uciinfo{'pv'})) {
557                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}});
558                 }
559         
560                 my $mpv = 1;
561                 while (exists($uciinfo{'pv' . $mpv})) {
562                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}});
563                         ++$mpv;
564                 }
565         };
566         if ($@) {
567                 %uciinfo = ();
568                 return;
569         }
570
571         my $text = 'Analysis';
572         if ($pos_calculating->{'last_move'} ne 'none') {
573                 if ($pos_calculating->{'toplay'} eq 'W') {
574                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
575                 } else {
576                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
577                 }
578                 if (exists($uciid{'name'})) {
579                         $text .= ',';
580                 }
581         }
582
583         if (exists($uciid{'name'})) {
584                 $text .= " by $uciid{'name'}:\n\n";
585         } else {
586                 $text .= ":\n\n";
587         }
588
589         return unless (exists($pos_calculating->{'board'}));
590                 
591         #
592         # Some programs _always_ report MultiPV, even with only one PV.
593         # In this case, we simply use that data as if MultiPV was never
594         # specified.
595         #
596         if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
597                 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
598                         if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
599                                 $uciinfo{$key} = $uciinfo{$key . '1'};
600                         }
601                 }
602         }
603
604         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
605                 # multi-PV
606                 my $mpv = 1;
607                 while (exists($uciinfo{'pv' . $mpv})) {
608                         $text .= sprintf "  PV%2u", $mpv;
609                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
610                         $text .= "  ($score)" if (defined($score));
611
612                         my $tbhits = '';
613                         if (exists($uciinfo{'tbhits' . $mpv}) && $uciinfo{'tbhits' . $mpv} > 0) {
614                                 if ($uciinfo{'tbhits' . $mpv} == 1) {
615                                         $tbhits = ", 1 tbhit";
616                                 } else {
617                                         $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
618                                 }
619                         }
620
621                         if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
622                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
623                                         $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
624                         }
625
626                         $text .= ":\n";
627                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
628                         $text .= "\n";
629                         ++$mpv;
630                 }
631         } else {
632                 # single-PV
633                 my $score = long_score(\%uciinfo, $pos_calculating, '');
634                 $text .= "  $score\n" if defined($score);
635                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
636                 $text .=  "\n";
637
638                 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
639                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
640                                 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
641                 }
642                 if (exists($uciinfo{'tbhits'}) && $uciinfo{'tbhits'} > 0) {
643                         if ($uciinfo{'tbhits'} == 1) {
644                                 $text .= ", one Nalimov hit";
645                         } else {
646                                 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
647                         }
648                 }
649                 if (exists($uciinfo{'seldepth'})) {
650                         $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
651                 }
652                 $text .=  "\n\n";
653         }
654
655         #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
656
657         if ($last_text ne $text) {
658                 print "\e[H\e[2J"; # clear the screen
659                 print $text;
660                 $last_text = $text;
661         }
662
663         # Now construct the tell text, if any
664         return if (!defined($telltarget));
665
666         my $tell_text = '';
667
668         if (exists($uciid{'name'})) {
669                 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
670         } else {
671                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
672         }
673
674         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
675                 # multi-PV
676                 my $mpv = 1;
677                 while (exists($uciinfo{'pv' . $mpv})) {
678                         $tell_text .= sprintf "  PV%2u", $mpv;
679                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
680                         $tell_text .= "  ($score)" if (defined($score));
681
682                         if (exists($uciinfo{'depth' . $mpv})) {
683                                 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
684                         }
685
686                         $tell_text .= ": ";
687                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}}));
688                         $tell_text .= "\n";
689                         ++$mpv;
690                 }
691         } else {
692                 # single-PV
693                 my $score = long_score(\%uciinfo, $pos_calculating, '');
694                 $tell_text .= "  $score\n" if defined($score);
695                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
696                 if (exists($uciinfo{'depth'})) {
697                         $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
698                 }
699                 $tell_text .=  "\n";
700         }
701
702         # see if a new tell is called for -- it is if the delay has expired _and_
703         # this is not simply a repetition of the last one
704         if ($last_told_text ne $tell_text) {
705                 my $now = time;
706                 for my $iv (@tell_intervals) {
707                         last if ($now - $last_move < $iv);
708                         next if ($last_tell - $last_move >= $iv);
709
710                         for my $line (split /\n/, $tell_text) {
711                                 $t->print("tell $telltarget [$target] $line");
712                         }
713
714                         $last_told_text = $text;
715                         $last_tell = $now;
716
717                         last;
718                 }
719         }
720 }
721
722 sub find_kings {
723         my $board = shift;
724         my ($wkr, $wkc, $bkr, $bkc);
725
726         for my $row (0..7) {
727                 for my $col (0..7) {
728                         my $piece = substr($board->[$row], $col, 1);
729                         if ($piece eq 'K') {
730                                 ($wkr, $wkc) = ($row, $col);
731                         } elsif ($piece eq 'k') {
732                                 ($bkr, $bkc) = ($row, $col);
733                         }
734                 }
735         }
736
737         return ($wkr, $wkc, $bkr, $bkc);
738 }
739
740 sub in_mate {
741         my $board = shift;
742         my $check = in_check($board);
743         return 0 if ($check eq 'none');
744
745         # try all possible moves for the side in check
746         for my $row (0..7) {
747                 for my $col (0..7) {
748                         my $piece = substr($board->[$row], $col, 1);
749                         next if ($piece eq '-');
750
751                         if ($check eq 'white') {
752                                 next if ($piece eq lc($piece));
753                         } else {
754                                 next if ($piece eq uc($piece));
755                         }
756
757                         for my $dest_row (0..7) {
758                                 for my $dest_col (0..7) {
759                                         next if ($row == $dest_row && $col == $dest_col);
760                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
761
762                                         my @nb = @$board;
763                                         substr($nb[$row], $col, 1, '-');
764                                         substr($nb[$dest_row], $dest_col, 1, $piece);
765
766                                         my $new_check = in_check(\@nb);
767                                         return 0 if ($new_check ne $check && $new_check ne 'both');
768                                 }
769                         }
770                 }
771         }
772
773         # nothing to do; mate
774         return 1;
775 }
776
777 sub in_check {
778         my $board = shift;
779         my ($black_check, $white_check) = (0, 0);
780
781         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
782
783         # check all pieces for the possibility of threatening the two kings
784         for my $row (0..7) {
785                 for my $col (0..7) {
786                         my $piece = substr($board->[$row], $col, 1);
787                         next if ($piece eq '-');
788                 
789                         if (uc($piece) eq $piece) {
790                                 # white piece
791                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
792                         } else {
793                                 # black piece
794                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
795                         }
796                 }
797         }
798
799         if ($black_check && $white_check) {
800                 return 'both';
801         } elsif ($black_check) {
802                 return 'black';
803         } elsif ($white_check) {
804                 return 'white';
805         } else {
806                 return 'none';
807         }
808 }
809
810 sub can_reach {
811         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
812         
813         # can't eat your own piece
814         my $dest_piece = substr($board->[$to_row], $to_col, 1);
815         if ($dest_piece ne '-') {
816                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
817         }
818
819         if (lc($piece) eq 'k') {
820                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
821         }
822         if (lc($piece) eq 'r') {
823                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
824
825                 # check that there's a clear passage
826                 if ($from_row == $to_row) {
827                         if ($from_col > $to_col) {
828                                 ($to_col, $from_col) = ($from_col, $to_col);
829                         }
830
831                         for my $c (($from_col+1)..($to_col-1)) {
832                                 my $middle_piece = substr($board->[$to_row], $c, 1);
833                                 return 0 if ($middle_piece ne '-');     
834                         }
835
836                         return 1;
837                 } else {
838                         if ($from_row > $to_row) {
839                                 ($to_row, $from_row) = ($from_row, $to_row);
840                         }
841
842                         for my $r (($from_row+1)..($to_row-1)) {
843                                 my $middle_piece = substr($board->[$r], $to_col, 1);
844                                 return 0 if ($middle_piece ne '-');     
845                         }
846
847                         return 1;
848                 }
849         }
850         if (lc($piece) eq 'b') {
851                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
852
853                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
854                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
855
856                 my $r = $from_row + $dr;
857                 my $c = $from_col + $dc;
858
859                 while ($r != $to_row) {
860                         my $middle_piece = substr($board->[$r], $c, 1);
861                         return 0 if ($middle_piece ne '-');
862                         
863                         $r += $dr;
864                         $c += $dc;
865                 }
866
867                 return 1;
868         }
869         if (lc($piece) eq 'n') {
870                 my $diff_r = abs($from_row - $to_row);
871                 my $diff_c = abs($from_col - $to_col);
872                 return 1 if ($diff_r == 2 && $diff_c == 1);
873                 return 1 if ($diff_r == 1 && $diff_c == 2);
874                 return 0;
875         }
876         if ($piece eq 'q') {
877                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
878                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
879         }
880         if ($piece eq 'Q') {
881                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
882                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
883         }
884         if ($piece eq 'p') {
885                 # black pawn
886                 if ($to_col == $from_col && $to_row == $from_row + 1) {
887                         return ($dest_piece eq '-');
888                 }
889                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
890                         return ($dest_piece ne '-');
891                 }
892                 return 0;
893         }
894         if ($piece eq 'P') {
895                 # white pawn
896                 if ($to_col == $from_col && $to_row == $from_row - 1) {
897                         return ($dest_piece eq '-');
898                 }
899                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
900                         return ($dest_piece ne '-');
901                 }
902                 return 0;
903         }
904         
905         # unknown piece
906         return 0;
907 }
908
909 sub uciprint {
910         my $msg = shift;
911         print UCIWRITE "$msg\n";
912         print UCILOG localtime() . " => $msg\n";
913 }
914
915 sub short_score {
916         my ($uciinfo, $pos, $mpv) = @_;
917
918         if (defined($uciinfo{'score_mate' . $mpv})) {
919                 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
920         } else {
921                 if (exists($uciinfo{'score_cp' . $mpv})) {
922                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
923                         if ($pos->{'toplay'} eq 'B') {
924                                 $score = -$score;
925                         }
926                         return sprintf "%+5.2f", $score;
927                 }
928         }
929
930         return undef;
931 }
932
933 sub long_score {
934         my ($uciinfo, $pos, $mpv) = @_;
935
936         if (defined($uciinfo{'score_mate' . $mpv})) {
937                 my $mate = $uciinfo{'score_mate' . $mpv};
938                 if ($pos->{'toplay'} eq 'B') {
939                         $mate = -$mate;
940                 }
941                 if ($mate > 0) {
942                         return sprintf "White mates in %u", $mate;
943                 } else {
944                         return sprintf "Black mates in %u", -$mate;
945                 }
946         } else {
947                 if (exists($uciinfo{'score_cp' . $mpv})) {
948                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
949                         if ($pos->{'toplay'} eq 'B') {
950                                 $score = -$score;
951                         }
952                         return sprintf "Score: %+5.2f", $score;
953                 }
954         }
955
956         return undef;
957 }
958
959 my %book_cache = ();
960 sub book_info {
961         my ($fen, $board, $toplay) = @_;
962
963         if (exists($book_cache{$fen})) {
964                 return $book_cache{$fen};
965         }
966
967         my $ret = `./booklook $fen`;
968         return "" if ($ret =~ /Not found/ || $ret eq '');
969
970         my @moves = ();
971
972         for my $m (split /\n/, $ret) {
973                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
974
975                 my $pmove;
976                 if ($move eq '')  {
977                         $pmove = '(current)';
978                 } else {
979                         ($pmove) = prettyprint_pv($board, $move);
980                         $pmove .= $annotation;
981                 }
982
983                 my $score;
984                 if ($toplay eq 'W') {
985                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
986                 } else {
987                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
988                 }
989                 my $n = $win + $draw + $lose;
990                 
991                 my $percent;
992                 if ($n == 0) {
993                         $percent = "     ";
994                 } else {
995                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
996                 }
997
998                 push @moves, [ $pmove, $n, $percent, $rating ];
999         }
1000
1001         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1002         
1003         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1004         for my $m (@moves) {
1005                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1006         }
1007
1008         return $text;
1009 }