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