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