]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
16416ba07fb7a37c48c6e1c36e54c0c9cd69fe04
[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         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
219         print UCILOG localtime() . " <= $line\n";
220         if ($line =~ /^info/) {
221                 my (@infos) = split / /, $line;
222                 shift @infos;
223
224                 parse_infos(@infos);
225         }
226         if ($line =~ /^id/) {
227                 my (@ids) = split / /, $line;
228                 shift @ids;
229
230                 parse_ids(@ids);
231         }
232         if ($line =~ /^bestmove/ && $uci_assume_full_compliance) {
233                 if (defined($pos_waiting)) {
234                         uciprint("position fen " . $pos_waiting->{'fen'});
235                         uciprint("go infinite");
236
237                         $pos_calculating = $pos_waiting;
238                         $pos_waiting = undef;
239                 }
240         }
241 }
242
243 sub parse_infos {
244         my (@x) = @_;
245         my $mpv = '';
246
247         while (scalar @x > 0) {
248                 if ($x[0] =~ 'multipv') {
249                         shift @x;
250                         $mpv = shift @x;
251                         next;
252                 }
253                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
254                         my $key = shift @x;
255                         my $value = shift @x;
256                         $uciinfo{$key} = $value;
257                         next;
258                 }
259                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
260                         my $key = shift @x;
261                         my $value = shift @x;
262                         $uciinfo{$key . $mpv} = $value;
263                         next;
264                 }
265                 if ($x[0] eq 'score') {
266                         shift @x;
267
268                         delete $uciinfo{'score_cp' . $mpv};
269                         delete $uciinfo{'score_mate' . $mpv};
270
271                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
272                                 if ($x[0] eq 'cp') {
273                                         shift @x;
274                                         $uciinfo{'score_cp' . $mpv} = shift @x;
275                                 } elsif ($x[0] eq 'mate') {
276                                         shift @x;
277                                         $uciinfo{'score_mate' . $mpv} = shift @x;
278                                 } else {
279                                         shift @x;
280                                 }
281                         }
282                         next;
283                 }
284                 if ($x[0] eq 'pv') {
285                         $uciinfo{'pv' . $mpv} = [ @x[1..$#x] ];
286                         last;
287                 }
288                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
289                         last;
290                 }
291
292                 #print "unknown info '$x[0]', trying to recover...\n";
293                 #shift @x;
294                 die "Unknown info '" . join(',', @x) . "'";
295
296         }
297 }
298
299 sub parse_ids {
300         my (@x) = @_;
301
302         while (scalar @x > 0) {
303                 if ($x[0] =~ /^(name|author)$/) {
304                         my $key = shift @x;
305                         my $value = join(' ', @x);
306                         $uciid{$key} = $value;
307                         last;
308                 }
309
310                 # unknown
311                 shift @x;
312         }
313 }
314
315 sub style12_to_fen {
316         my $str = shift;
317         my %pos = ();
318         my (@x) = split / /, $str;
319         
320         $pos{'board'} = [ @x[1..8] ];
321         $pos{'toplay'} = $x[9];
322         
323         # the board itself
324         my (@board) = @x[1..8];
325         for my $rank (0..7) {
326                 $board[$rank] =~ s/(-+)/length($1)/ge;
327         }
328         my $fen = join('/', @board);
329
330         # white/black to move
331         $fen .= " ";
332         $fen .= lc($x[9]);
333
334         # castling
335         my $castling = "";
336         $castling .= "K" if ($x[11] == 1);
337         $castling .= "Q" if ($x[12] == 1);
338         $castling .= "k" if ($x[13] == 1);
339         $castling .= "q" if ($x[14] == 1);
340         $castling = "-" if ($castling eq "");
341         # $castling = "-"; # chess960
342         $fen .= " ";
343         $fen .= $castling;
344
345         # en passant
346         my $ep = "-";
347         if ($x[10] != -1) {
348                 my $col = $x[10];
349                 my $nep = (qw(a b c d e f g h))[$col];
350
351                 if ($x[9] eq 'B') {
352                         $nep .= "3";
353                 } else {
354                         $nep .= "6";
355                 }
356
357                 #
358                 # Showing the en passant square when actually no capture can be made
359                 # seems to confuse at least Rybka. Thus, check if there's actually
360                 # a pawn of the opposite side that can do the en passant move, and if
361                 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
362                 # "right" thing as per the standard, though.
363                 #
364                 if ($x[9] eq 'B') {
365                         $ep = $nep if ($col > 0 && substr($pos{'board'}[4], $col-1, 1) eq 'p');
366                         $ep = $nep if ($col < 7 && substr($pos{'board'}[4], $col+1, 1) eq 'p');
367                 } else {
368                         $ep = $nep if ($col > 0 && substr($pos{'board'}[3], $col-1, 1) eq 'P');
369                         $ep = $nep if ($col < 7 && substr($pos{'board'}[3], $col+1, 1) eq 'P');
370                 }
371         }
372         $fen .= " ";
373         $fen .= $ep;
374
375         # half-move clock
376         $fen .= " ";
377         $fen .= $x[15];
378
379         # full-move clock
380         $fen .= " ";
381         $fen .= $x[26];
382
383         $pos{'fen'} = $fen;
384         $pos{'move_num'} = $x[26];
385         $pos{'last_move'} = $x[29];
386
387         return \%pos;
388 }
389
390 sub prettyprint_pv {
391         my ($board, @pvs) = @_;
392
393         if (scalar @pvs == 0 || !defined($pvs[0])) {
394                 return ();
395         }
396         
397         my @nb = @$board;
398
399         my $pv = shift @pvs;
400         my $from_col = ord(substr($pv, 0, 1)) - ord('a');
401         my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
402         my $to_col   = ord(substr($pv, 2, 1)) - ord('a');
403         my $to_row   = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
404
405         my $pretty;
406         my $piece = substr($board->[$from_row], $from_col, 1);
407
408         if ($piece eq '-') {
409                 die "Invalid move $pv";
410         }
411
412         # white short castling
413         if ($pv eq 'e1g1' && $piece eq 'K') {
414                 # king
415                 substr($nb[7], 4, 1, '-');
416                 substr($nb[7], 6, 1, $piece);
417                 
418                 # rook
419                 substr($nb[7], 7, 1, '-');
420                 substr($nb[7], 5, 1, 'R');
421                                 
422                 return ('0-0', prettyprint_pv(\@nb, @pvs));
423         }
424
425         # white long castling
426         if ($pv eq 'e1c1' && $piece eq 'K') {
427                 # king
428                 substr($nb[7], 4, 1, '-');
429                 substr($nb[7], 2, 1, $piece);
430                 
431                 # rook
432                 substr($nb[7], 0, 1, '-');
433                 substr($nb[7], 3, 1, 'R');
434                                 
435                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
436         }
437
438         # black short castling
439         if ($pv eq 'e8g8' && $piece eq 'k') {
440                 # king
441                 substr($nb[0], 4, 1, '-');
442                 substr($nb[0], 6, 1, $piece);
443                 
444                 # rook
445                 substr($nb[0], 7, 1, '-');
446                 substr($nb[0], 5, 1, 'r');
447                                 
448                 return ('0-0', prettyprint_pv(\@nb, @pvs));
449         }
450
451         # black long castling
452         if ($pv eq 'e8c8' && $piece eq 'k') {
453                 # king
454                 substr($nb[0], 4, 1, '-');
455                 substr($nb[0], 2, 1, $piece);
456                 
457                 # rook
458                 substr($nb[0], 0, 1, '-');
459                 substr($nb[0], 3, 1, 'r');
460                                 
461                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
462         }
463
464         # check if the from-piece is a pawn
465         if (lc($piece) eq 'p') {
466                 # attack?
467                 if ($from_col != $to_col) {
468                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
469
470                         # en passant?
471                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
472                                 if ($piece eq 'p') {
473                                         substr($nb[$to_row + 1], $to_col, 1, '-');
474                                 } else {
475                                         substr($nb[$to_row - 1], $to_col, 1, '-');
476                                 }
477                         }
478                 } else {
479                         $pretty = substr($pv, 2, 2);
480
481                         if (length($pv) == 5) {
482                                 # promotion
483                                 $pretty .= "=";
484                                 $pretty .= uc(substr($pv, 4, 1));
485
486                                 if ($piece eq 'p') {
487                                         $piece = substr($pv, 4, 1);
488                                 } else {
489                                         $piece = uc(substr($pv, 4, 1));
490                                 }
491                         }
492                 }
493         } else {
494                 $pretty = uc($piece);
495
496                 # see how many of these pieces could go here, in all
497                 my $num_total = 0;
498                 for my $col (0..7) {
499                         for my $row (0..7) {
500                                 next unless (substr($board->[$row], $col, 1) eq $piece);
501                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
502                         }
503                 }
504
505                 # see how many of these pieces from the given row could go here
506                 my $num_row = 0;
507                 for my $col (0..7) {
508                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
509                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
510                 }
511                 
512                 # and same for columns
513                 my $num_col = 0;
514                 for my $row (0..7) {
515                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
516                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
517                 }
518                 
519                 # see if we need to disambiguate
520                 if ($num_total > 1) {
521                         if ($num_col == 1) {
522                                 $pretty .= substr($pv, 0, 1);
523                         } elsif ($num_row == 1) {
524                                 $pretty .= substr($pv, 1, 1);
525                         } else {
526                                 $pretty .= substr($pv, 0, 2);
527                         }
528                 }
529
530                 # attack?
531                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
532                         $pretty .= 'x';
533                 }
534
535                 $pretty .= substr($pv, 2, 2);
536         }
537
538         # update the board
539         substr($nb[$from_row], $from_col, 1, '-');
540         substr($nb[$to_row], $to_col, 1, $piece);
541
542         if (in_mate(\@nb)) {
543                 $pretty .= '#';
544         } elsif (in_check(\@nb) ne 'none') {
545                 $pretty .= '+';
546         }
547
548         return ($pretty, prettyprint_pv(\@nb, @pvs));
549 }
550
551 sub output_screen {
552         #return;
553         
554         return if (!defined($pos_calculating));
555
556         #
557         # Check the PVs first. if they're invalid, just wait, as our data
558         # is most likely out of sync. This isn't a very good solution, as
559         # it can frequently miss stuff, but it's good enough for most users.
560         #
561         eval {
562                 my $dummy;
563                 if (exists($uciinfo{'pv'})) {
564                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}});
565                 }
566         
567                 my $mpv = 1;
568                 while (exists($uciinfo{'pv' . $mpv})) {
569                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}});
570                         ++$mpv;
571                 }
572         };
573         if ($@) {
574                 %uciinfo = ();
575                 return;
576         }
577
578         my $text = 'Analysis';
579         if ($pos_calculating->{'last_move'} ne 'none') {
580                 if ($pos_calculating->{'toplay'} eq 'W') {
581                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
582                 } else {
583                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
584                 }
585                 if (exists($uciid{'name'})) {
586                         $text .= ',';
587                 }
588         }
589
590         if (exists($uciid{'name'})) {
591                 $text .= " by $uciid{'name'}:\n\n";
592         } else {
593                 $text .= ":\n\n";
594         }
595
596         return unless (exists($pos_calculating->{'board'}));
597                 
598         #
599         # Some programs _always_ report MultiPV, even with only one PV.
600         # In this case, we simply use that data as if MultiPV was never
601         # specified.
602         #
603         if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
604                 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
605                         if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
606                                 $uciinfo{$key} = $uciinfo{$key . '1'};
607                         }
608                 }
609         }
610
611         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
612                 # multi-PV
613                 my $mpv = 1;
614                 while (exists($uciinfo{'pv' . $mpv})) {
615                         $text .= sprintf "  PV%2u", $mpv;
616                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
617                         $text .= "  ($score)" if (defined($score));
618
619                         my $tbhits = '';
620                         if (exists($uciinfo{'tbhits' . $mpv}) && $uciinfo{'tbhits' . $mpv} > 0) {
621                                 if ($uciinfo{'tbhits' . $mpv} == 1) {
622                                         $tbhits = ", 1 tbhit";
623                                 } else {
624                                         $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
625                                 }
626                         }
627
628                         if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
629                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
630                                         $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
631                         }
632
633                         $text .= ":\n";
634                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
635                         $text .= "\n";
636                         ++$mpv;
637                 }
638         } else {
639                 # single-PV
640                 my $score = long_score(\%uciinfo, $pos_calculating, '');
641                 $text .= "  $score\n" if defined($score);
642                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
643                 $text .=  "\n";
644
645                 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
646                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
647                                 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
648                 }
649                 if (exists($uciinfo{'tbhits'}) && $uciinfo{'tbhits'} > 0) {
650                         if ($uciinfo{'tbhits'} == 1) {
651                                 $text .= ", one Nalimov hit";
652                         } else {
653                                 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
654                         }
655                 }
656                 if (exists($uciinfo{'seldepth'})) {
657                         $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
658                 }
659                 $text .=  "\n\n";
660         }
661
662         #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
663
664         if ($last_text ne $text) {
665                 print "\e[H\e[2J"; # clear the screen
666                 print $text;
667                 $last_text = $text;
668         }
669
670         # Now construct the tell text, if any
671         return if (!defined($telltarget));
672
673         my $tell_text = '';
674
675         if (exists($uciid{'name'})) {
676                 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
677         } else {
678                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
679         }
680
681         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
682                 # multi-PV
683                 my $mpv = 1;
684                 while (exists($uciinfo{'pv' . $mpv})) {
685                         $tell_text .= sprintf "  PV%2u", $mpv;
686                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
687                         $tell_text .= "  ($score)" if (defined($score));
688
689                         if (exists($uciinfo{'depth' . $mpv})) {
690                                 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
691                         }
692
693                         $tell_text .= ": ";
694                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}}));
695                         $tell_text .= "\n";
696                         ++$mpv;
697                 }
698         } else {
699                 # single-PV
700                 my $score = long_score(\%uciinfo, $pos_calculating, '');
701                 $tell_text .= "  $score\n" if defined($score);
702                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
703                 if (exists($uciinfo{'depth'})) {
704                         $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
705                 }
706                 $tell_text .=  "\n";
707         }
708
709         # see if a new tell is called for -- it is if the delay has expired _and_
710         # this is not simply a repetition of the last one
711         if ($last_told_text ne $tell_text) {
712                 my $now = time;
713                 for my $iv (@tell_intervals) {
714                         last if ($now - $last_move < $iv);
715                         next if ($last_tell - $last_move >= $iv);
716
717                         for my $line (split /\n/, $tell_text) {
718                                 $t->print("tell $telltarget [$target] $line");
719                         }
720
721                         $last_told_text = $text;
722                         $last_tell = $now;
723
724                         last;
725                 }
726         }
727 }
728
729 sub find_kings {
730         my $board = shift;
731         my ($wkr, $wkc, $bkr, $bkc);
732
733         for my $row (0..7) {
734                 for my $col (0..7) {
735                         my $piece = substr($board->[$row], $col, 1);
736                         if ($piece eq 'K') {
737                                 ($wkr, $wkc) = ($row, $col);
738                         } elsif ($piece eq 'k') {
739                                 ($bkr, $bkc) = ($row, $col);
740                         }
741                 }
742         }
743
744         return ($wkr, $wkc, $bkr, $bkc);
745 }
746
747 sub in_mate {
748         my $board = shift;
749         my $check = in_check($board);
750         return 0 if ($check eq 'none');
751
752         # try all possible moves for the side in check
753         for my $row (0..7) {
754                 for my $col (0..7) {
755                         my $piece = substr($board->[$row], $col, 1);
756                         next if ($piece eq '-');
757
758                         if ($check eq 'white') {
759                                 next if ($piece eq lc($piece));
760                         } else {
761                                 next if ($piece eq uc($piece));
762                         }
763
764                         for my $dest_row (0..7) {
765                                 for my $dest_col (0..7) {
766                                         next if ($row == $dest_row && $col == $dest_col);
767                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
768
769                                         my @nb = @$board;
770                                         substr($nb[$row], $col, 1, '-');
771                                         substr($nb[$dest_row], $dest_col, 1, $piece);
772
773                                         my $new_check = in_check(\@nb);
774                                         return 0 if ($new_check ne $check && $new_check ne 'both');
775                                 }
776                         }
777                 }
778         }
779
780         # nothing to do; mate
781         return 1;
782 }
783
784 sub in_check {
785         my $board = shift;
786         my ($black_check, $white_check) = (0, 0);
787
788         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
789
790         # check all pieces for the possibility of threatening the two kings
791         for my $row (0..7) {
792                 for my $col (0..7) {
793                         my $piece = substr($board->[$row], $col, 1);
794                         next if ($piece eq '-');
795                 
796                         if (uc($piece) eq $piece) {
797                                 # white piece
798                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
799                         } else {
800                                 # black piece
801                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
802                         }
803                 }
804         }
805
806         if ($black_check && $white_check) {
807                 return 'both';
808         } elsif ($black_check) {
809                 return 'black';
810         } elsif ($white_check) {
811                 return 'white';
812         } else {
813                 return 'none';
814         }
815 }
816
817 sub can_reach {
818         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
819         
820         # can't eat your own piece
821         my $dest_piece = substr($board->[$to_row], $to_col, 1);
822         if ($dest_piece ne '-') {
823                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
824         }
825
826         if (lc($piece) eq 'k') {
827                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
828         }
829         if (lc($piece) eq 'r') {
830                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
831
832                 # check that there's a clear passage
833                 if ($from_row == $to_row) {
834                         if ($from_col > $to_col) {
835                                 ($to_col, $from_col) = ($from_col, $to_col);
836                         }
837
838                         for my $c (($from_col+1)..($to_col-1)) {
839                                 my $middle_piece = substr($board->[$to_row], $c, 1);
840                                 return 0 if ($middle_piece ne '-');     
841                         }
842
843                         return 1;
844                 } else {
845                         if ($from_row > $to_row) {
846                                 ($to_row, $from_row) = ($from_row, $to_row);
847                         }
848
849                         for my $r (($from_row+1)..($to_row-1)) {
850                                 my $middle_piece = substr($board->[$r], $to_col, 1);
851                                 return 0 if ($middle_piece ne '-');     
852                         }
853
854                         return 1;
855                 }
856         }
857         if (lc($piece) eq 'b') {
858                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
859
860                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
861                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
862
863                 my $r = $from_row + $dr;
864                 my $c = $from_col + $dc;
865
866                 while ($r != $to_row) {
867                         my $middle_piece = substr($board->[$r], $c, 1);
868                         return 0 if ($middle_piece ne '-');
869                         
870                         $r += $dr;
871                         $c += $dc;
872                 }
873
874                 return 1;
875         }
876         if (lc($piece) eq 'n') {
877                 my $diff_r = abs($from_row - $to_row);
878                 my $diff_c = abs($from_col - $to_col);
879                 return 1 if ($diff_r == 2 && $diff_c == 1);
880                 return 1 if ($diff_r == 1 && $diff_c == 2);
881                 return 0;
882         }
883         if ($piece eq 'q') {
884                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
885                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
886         }
887         if ($piece eq 'Q') {
888                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
889                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
890         }
891         if ($piece eq 'p') {
892                 # black pawn
893                 if ($to_col == $from_col && $to_row == $from_row + 1) {
894                         return ($dest_piece eq '-');
895                 }
896                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
897                         return ($dest_piece ne '-');
898                 }
899                 return 0;
900         }
901         if ($piece eq 'P') {
902                 # white pawn
903                 if ($to_col == $from_col && $to_row == $from_row - 1) {
904                         return ($dest_piece eq '-');
905                 }
906                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
907                         return ($dest_piece ne '-');
908                 }
909                 return 0;
910         }
911         
912         # unknown piece
913         return 0;
914 }
915
916 sub uciprint {
917         my $msg = shift;
918         print UCIWRITE "$msg\n";
919         print UCILOG localtime() . " => $msg\n";
920 }
921
922 sub short_score {
923         my ($uciinfo, $pos, $mpv) = @_;
924
925         if (defined($uciinfo{'score_mate' . $mpv})) {
926                 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
927         } else {
928                 if (exists($uciinfo{'score_cp' . $mpv})) {
929                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
930                         if ($pos->{'toplay'} eq 'B') {
931                                 $score = -$score;
932                         }
933                         return sprintf "%+5.2f", $score;
934                 }
935         }
936
937         return undef;
938 }
939
940 sub long_score {
941         my ($uciinfo, $pos, $mpv) = @_;
942
943         if (defined($uciinfo{'score_mate' . $mpv})) {
944                 my $mate = $uciinfo{'score_mate' . $mpv};
945                 if ($pos->{'toplay'} eq 'B') {
946                         $mate = -$mate;
947                 }
948                 if ($mate > 0) {
949                         return sprintf "White mates in %u", $mate;
950                 } else {
951                         return sprintf "Black mates in %u", -$mate;
952                 }
953         } else {
954                 if (exists($uciinfo{'score_cp' . $mpv})) {
955                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
956                         if ($pos->{'toplay'} eq 'B') {
957                                 $score = -$score;
958                         }
959                         return sprintf "Score: %+5.2f", $score;
960                 }
961         }
962
963         return undef;
964 }
965
966 my %book_cache = ();
967 sub book_info {
968         my ($fen, $board, $toplay) = @_;
969
970         if (exists($book_cache{$fen})) {
971                 return $book_cache{$fen};
972         }
973
974         my $ret = `./booklook $fen`;
975         return "" if ($ret =~ /Not found/ || $ret eq '');
976
977         my @moves = ();
978
979         for my $m (split /\n/, $ret) {
980                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
981
982                 my $pmove;
983                 if ($move eq '')  {
984                         $pmove = '(current)';
985                 } else {
986                         ($pmove) = prettyprint_pv($board, $move);
987                         $pmove .= $annotation;
988                 }
989
990                 my $score;
991                 if ($toplay eq 'W') {
992                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
993                 } else {
994                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
995                 }
996                 my $n = $win + $draw + $lose;
997                 
998                 my $percent;
999                 if ($n == 0) {
1000                         $percent = "     ";
1001                 } else {
1002                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1003                 }
1004
1005                 push @moves, [ $pmove, $n, $percent, $rating ];
1006         }
1007
1008         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1009         
1010         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1011         for my $m (@moves) {
1012                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1013         }
1014
1015         return $text;
1016 }