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