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