]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
16a4f8dc6b2f6e9b0b6918451ef3f7d531847c11
[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         $pos{'last_move'} = $x[29];
379
380         return \%pos;
381 }
382
383 sub prettyprint_pv {
384         my ($board, @pvs) = @_;
385         
386         if (scalar @pvs == 0 || !defined($pvs[0])) {
387                 return ();
388         }
389         
390         my @nb = @$board;
391
392         my $pv = shift @pvs;
393         my $from_col = ord(substr($pv, 0, 1)) - ord('a');
394         my $from_row = 7 - (ord(substr($pv, 1, 1)) - ord('1'));
395         my $to_col   = ord(substr($pv, 2, 1)) - ord('a');
396         my $to_row   = 7 - (ord(substr($pv, 3, 1)) - ord('1'));
397
398         my $pretty;
399         my $piece = substr($board->[$from_row], $from_col, 1);
400
401         if ($piece eq '-') {
402                 die "Invalid move";
403         }
404
405         # white short castling
406         if ($pv eq 'e1g1' && $piece eq 'K') {
407                 # king
408                 substr($nb[7], 4, 1, '-');
409                 substr($nb[7], 6, 1, $piece);
410                 
411                 # rook
412                 substr($nb[7], 7, 1, '-');
413                 substr($nb[7], 5, 1, 'R');
414                                 
415                 return ('0-0', prettyprint_pv(\@nb, @pvs));
416         }
417
418         # white long castling
419         if ($pv eq 'e1c1' && $piece eq 'K') {
420                 # king
421                 substr($nb[7], 4, 1, '-');
422                 substr($nb[7], 2, 1, $piece);
423                 
424                 # rook
425                 substr($nb[7], 0, 1, '-');
426                 substr($nb[7], 3, 1, 'R');
427                                 
428                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
429         }
430
431         # black short castling
432         if ($pv eq 'e8g8' && $piece eq 'k') {
433                 # king
434                 substr($nb[0], 4, 1, '-');
435                 substr($nb[0], 6, 1, $piece);
436                 
437                 # rook
438                 substr($nb[0], 7, 1, '-');
439                 substr($nb[0], 5, 1, 'r');
440                                 
441                 return ('0-0', prettyprint_pv(\@nb, @pvs));
442         }
443
444         # black long castling
445         if ($pv eq 'e8c8' && $piece eq 'k') {
446                 # king
447                 substr($nb[0], 4, 1, '-');
448                 substr($nb[0], 2, 1, $piece);
449                 
450                 # rook
451                 substr($nb[0], 0, 1, '-');
452                 substr($nb[0], 3, 1, 'r');
453                                 
454                 return ('0-0-0', prettyprint_pv(\@nb, @pvs));
455         }
456
457         # check if the from-piece is a pawn
458         if (lc($piece) eq 'p') {
459                 # attack?
460                 if ($from_col != $to_col) {
461                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
462
463                         # en passant?
464                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
465                                 if ($piece eq 'p') {
466                                         substr($nb[$to_row + 1], $to_col, 1, '-');
467                                 } else {
468                                         substr($nb[$to_row - 1], $to_col, 1, '-');
469                                 }
470                         }
471                 } else {
472                         $pretty = substr($pv, 2, 2);
473
474                         if (length($pv) == 5) {
475                                 # promotion
476                                 $pretty .= "=";
477                                 $pretty .= uc(substr($pv, 4, 1));
478
479                                 if ($piece eq 'p') {
480                                         $piece = substr($pv, 4, 1);
481                                 } else {
482                                         $piece = uc(substr($pv, 4, 1));
483                                 }
484                         }
485                 }
486         } else {
487                 $pretty = uc($piece);
488
489                 # see how many of these pieces could go here, in all
490                 my $num_total = 0;
491                 for my $col (0..7) {
492                         for my $row (0..7) {
493                                 next unless (substr($board->[$row], $col, 1) eq $piece);
494                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
495                         }
496                 }
497
498                 # see how many of these pieces from the given row could go here
499                 my $num_row = 0;
500                 for my $col (0..7) {
501                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
502                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
503                 }
504                 
505                 # and same for columns
506                 my $num_col = 0;
507                 for my $row (0..7) {
508                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
509                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
510                 }
511                 
512                 # see if we need to disambiguate
513                 if ($num_total > 1) {
514                         if ($num_col == 1) {
515                                 $pretty .= substr($pv, 0, 1);
516                         } elsif ($num_row == 1) {
517                                 $pretty .= substr($pv, 1, 1);
518                         } else {
519                                 $pretty .= substr($pv, 0, 2);
520                         }
521                 }
522
523                 # attack?
524                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
525                         $pretty .= 'x';
526                 }
527
528                 $pretty .= substr($pv, 2, 2);
529         }
530
531         # update the board
532         substr($nb[$from_row], $from_col, 1, '-');
533         substr($nb[$to_row], $to_col, 1, $piece);
534
535         if (in_mate(\@nb)) {
536                 $pretty .= '#';
537         } elsif (in_check(\@nb) ne 'none') {
538                 $pretty .= '+';
539         }
540
541         return ($pretty, prettyprint_pv(\@nb, @pvs));
542 }
543
544 sub output_screen {
545         #return;
546         
547         return if (!defined($pos_calculating));
548
549         #
550         # Check the PVs first. if they're invalid, just wait, as our data
551         # is most likely out of sync. This isn't a very good solution, as
552         # it can frequently miss stuff, but it's good enough for most users.
553         #
554         eval {
555                 my $dummy;
556                 if (exists($uciinfo{'pv'})) {
557                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}});
558                 }
559         
560                 my $mpv = 1;
561                 while (exists($uciinfo{'pv' . $mpv})) {
562                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}});
563                         ++$mpv;
564                 }
565         };
566         if ($@) {
567                 %uciinfo = ();
568                 return;
569         }
570
571         my $text = 'Analysis';
572         if ($pos_calculating->{'last_move'} ne 'none') {
573                 if ($pos_calculating->{'toplay'} eq 'W') {
574                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
575                 } else {
576                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
577                 }
578                 if (exists($uciid{'name'})) {
579                         $text .= ',';
580                 }
581         }
582
583         if (exists($uciid{'name'})) {
584                 $text .= " by $uciid{'name'}:\n\n";
585         } else {
586                 $text .= ":\n\n";
587         }
588
589         return unless (exists($pos_calculating->{'board'}));
590                 
591         #
592         # Some programs _always_ report MultiPV, even with only one PV.
593         # In this case, we simply use that data as if MultiPV was never
594         # specified.
595         #
596         if (exists($uciinfo{'pv1'}) && !exists($uciinfo{'pv2'})) {
597                 for my $key qw(pv score_cp score_mate nodes nps depth seldepth tbhits) {
598                         if (exists($uciinfo{$key . '1'}) && !exists($uciinfo{$key})) {
599                                 $uciinfo{$key} = $uciinfo{$key . '1'};
600                         }
601                 }
602         }
603
604         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
605                 # multi-PV
606                 my $mpv = 1;
607                 while (exists($uciinfo{'pv' . $mpv})) {
608                         $text .= sprintf "  PV%2u", $mpv;
609                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
610                         $text .= "  ($score)" if (defined($score));
611
612                         my $tbhits = '';
613                         if (exists($uciinfo{'tbhits' . $mpv}) && $uciinfo{'tbhits' . $mpv} > 0) {
614                                 if ($uciinfo{'tbhits' . $mpv} == 1) {
615                                         $tbhits = ", 1 tbhit";
616                                 } else {
617                                         $tbhits = sprintf ", %u tbhits", $uciinfo{'tbhits' . $mpv};
618                                 }
619                         }
620
621                         if (exists($uciinfo{'nodes' . $mpv}) && exists($uciinfo{'nps' . $mpv}) && exists($uciinfo{'depth' . $mpv})) {
622                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
623                                         $uciinfo{'nodes' . $mpv} / 1000, $uciinfo{'nps' . $mpv} / 1000, $uciinfo{'depth' . $mpv};
624                         }
625
626                         $text .= ":\n";
627                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}})) . "\n";
628                         $text .= "\n";
629                         ++$mpv;
630                 }
631         } else {
632                 # single-PV
633                 my $score = long_score(\%uciinfo, $pos_calculating, '');
634                 $text .= "  $score\n" if defined($score);
635                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
636                 $text .=  "\n";
637
638                 if (exists($uciinfo{'nodes'}) && exists($uciinfo{'nps'}) && exists($uciinfo{'depth'})) {
639                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
640                                 $uciinfo{'nodes'}, $uciinfo{'nps'}, $uciinfo{'depth'};
641                 }
642                 if (exists($uciinfo{'tbhits'}) && $uciinfo{'tbhits'} > 0) {
643                         if ($uciinfo{'tbhits'} == 1) {
644                                 $text .= ", one Nalimov hit";
645                         } else {
646                                 $text .= sprintf ", %u Nalimov hits", $uciinfo{'tbhits'};
647                         }
648                 }
649                 if (exists($uciinfo{'seldepth'})) {
650                         $text .= sprintf " (%u selective)", $uciinfo{'seldepth'};
651                 }
652                 $text .=  "\n\n";
653         }
654
655         if ($last_text ne $text) {
656                 print "\e[H\e[2J"; # clear the screen
657                 print $text;
658                 $last_text = $text;
659         }
660
661         # Now construct the tell text, if any
662         return if (!defined($telltarget));
663
664         my $tell_text = '';
665
666         if (exists($uciid{'name'})) {
667                 $tell_text .= "Analysis by $uciid{'name'} -- see http://analysis.sesse.net/ for more information\n";
668         } else {
669                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
670         }
671
672         if (exists($uciinfo{'pv1'}) && exists($uciinfo{'pv2'})) {
673                 # multi-PV
674                 my $mpv = 1;
675                 while (exists($uciinfo{'pv' . $mpv})) {
676                         $tell_text .= sprintf "  PV%2u", $mpv;
677                         my $score = short_score(\%uciinfo, $pos_calculating, $mpv);
678                         $tell_text .= "  ($score)" if (defined($score));
679
680                         if (exists($uciinfo{'depth' . $mpv})) {
681                                 $tell_text .= sprintf " (%2u ply)", $uciinfo{'depth' . $mpv};
682                         }
683
684                         $tell_text .= ": ";
685                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv' . $mpv}}));
686                         $tell_text .= "\n";
687                         ++$mpv;
688                 }
689         } else {
690                 # single-PV
691                 my $score = long_score(\%uciinfo, $pos_calculating, '');
692                 $tell_text .= "  $score\n" if defined($score);
693                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$uciinfo{'pv'}}));
694                 if (exists($uciinfo{'depth'})) {
695                         $tell_text .= sprintf " (depth %u ply)", $uciinfo{'depth'};
696                 }
697                 $tell_text .=  "\n";
698         }
699
700         # see if a new tell is called for -- it is if the delay has expired _and_
701         # this is not simply a repetition of the last one
702         if ($last_told_text ne $tell_text) {
703                 my $now = time;
704                 for my $iv (@tell_intervals) {
705                         last if ($now - $last_move < $iv);
706                         next if ($last_tell - $last_move >= $iv);
707
708                         for my $line (split /\n/, $tell_text) {
709                                 $t->print("tell $telltarget [$target] $line");
710                         }
711
712                         $last_told_text = $text;
713                         $last_tell = $now;
714
715                         last;
716                 }
717         }
718 }
719
720 sub find_kings {
721         my $board = shift;
722         my ($wkr, $wkc, $bkr, $bkc);
723
724         for my $row (0..7) {
725                 for my $col (0..7) {
726                         my $piece = substr($board->[$row], $col, 1);
727                         if ($piece eq 'K') {
728                                 ($wkr, $wkc) = ($row, $col);
729                         } elsif ($piece eq 'k') {
730                                 ($bkr, $bkc) = ($row, $col);
731                         }
732                 }
733         }
734
735         return ($wkr, $wkc, $bkr, $bkc);
736 }
737
738 sub in_mate {
739         my $board = shift;
740         my $check = in_check($board);
741         return 0 if ($check eq 'none');
742
743         # try all possible moves for the side in check
744         for my $row (0..7) {
745                 for my $col (0..7) {
746                         my $piece = substr($board->[$row], $col, 1);
747                         next if ($piece eq '-');
748
749                         if ($check eq 'white') {
750                                 next if ($piece eq lc($piece));
751                         } else {
752                                 next if ($piece eq uc($piece));
753                         }
754
755                         for my $dest_row (0..7) {
756                                 for my $dest_col (0..7) {
757                                         next if ($row == $dest_row && $col == $dest_col);
758                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
759
760                                         my @nb = @$board;
761                                         substr($nb[$row], $col, 1, '-');
762                                         substr($nb[$dest_row], $dest_col, 1, $piece);
763
764                                         my $new_check = in_check(\@nb);
765                                         return 0 if ($new_check ne $check && $new_check ne 'both');
766                                 }
767                         }
768                 }
769         }
770
771         # nothing to do; mate
772         return 1;
773 }
774
775 sub in_check {
776         my $board = shift;
777         my ($black_check, $white_check) = (0, 0);
778
779         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
780
781         # check all pieces for the possibility of threatening the two kings
782         for my $row (0..7) {
783                 for my $col (0..7) {
784                         my $piece = substr($board->[$row], $col, 1);
785                         next if ($piece eq '-');
786                 
787                         if (uc($piece) eq $piece) {
788                                 # white piece
789                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
790                         } else {
791                                 # black piece
792                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
793                         }
794                 }
795         }
796
797         if ($black_check && $white_check) {
798                 return 'both';
799         } elsif ($black_check) {
800                 return 'black';
801         } elsif ($white_check) {
802                 return 'white';
803         } else {
804                 return 'none';
805         }
806 }
807
808 sub can_reach {
809         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
810         
811         # can't eat your own piece
812         my $dest_piece = substr($board->[$to_row], $to_col, 1);
813         if ($dest_piece ne '-') {
814                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
815         }
816
817         if (lc($piece) eq 'k') {
818                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
819         }
820         if (lc($piece) eq 'r') {
821                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
822
823                 # check that there's a clear passage
824                 if ($from_row == $to_row) {
825                         if ($from_col > $to_col) {
826                                 ($to_col, $from_col) = ($from_col, $to_col);
827                         }
828
829                         for my $c (($from_col+1)..($to_col-1)) {
830                                 my $middle_piece = substr($board->[$to_row], $c, 1);
831                                 return 0 if ($middle_piece ne '-');     
832                         }
833
834                         return 1;
835                 } else {
836                         if ($from_row > $to_row) {
837                                 ($to_row, $from_row) = ($from_row, $to_row);
838                         }
839
840                         for my $r (($from_row+1)..($to_row-1)) {
841                                 my $middle_piece = substr($board->[$r], $to_col, 1);
842                                 return 0 if ($middle_piece ne '-');     
843                         }
844
845                         return 1;
846                 }
847         }
848         if (lc($piece) eq 'b') {
849                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
850
851                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
852                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
853
854                 my $r = $from_row + $dr;
855                 my $c = $from_col + $dc;
856
857                 while ($r != $to_row) {
858                         my $middle_piece = substr($board->[$r], $c, 1);
859                         return 0 if ($middle_piece ne '-');
860                         
861                         $r += $dr;
862                         $c += $dc;
863                 }
864
865                 return 1;
866         }
867         if (lc($piece) eq 'n') {
868                 my $diff_r = abs($from_row - $to_row);
869                 my $diff_c = abs($from_col - $to_col);
870                 return 1 if ($diff_r == 2 && $diff_c == 1);
871                 return 1 if ($diff_r == 1 && $diff_c == 2);
872                 return 0;
873         }
874         if ($piece eq 'q') {
875                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
876                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
877         }
878         if ($piece eq 'Q') {
879                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
880                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
881         }
882         if ($piece eq 'p') {
883                 # black pawn
884                 if ($to_col == $from_col && $to_row == $from_row + 1) {
885                         return ($dest_piece eq '-');
886                 }
887                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
888                         return ($dest_piece ne '-');
889                 }
890                 return 0;
891         }
892         if ($piece eq 'P') {
893                 # white pawn
894                 if ($to_col == $from_col && $to_row == $from_row - 1) {
895                         return ($dest_piece eq '-');
896                 }
897                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
898                         return ($dest_piece ne '-');
899                 }
900                 return 0;
901         }
902         
903         # unknown piece
904         return 0;
905 }
906
907 sub uciprint {
908         my $msg = shift;
909         print UCIWRITE "$msg\n";
910         print UCILOG localtime() . " => $msg\n";
911 }
912
913 sub short_score {
914         my ($uciinfo, $pos, $mpv) = @_;
915
916         if (defined($uciinfo{'score_mate' . $mpv})) {
917                 return sprintf "M%3d", $uciinfo{'score_mate' . $mpv};
918         } else {
919                 if (exists($uciinfo{'score_cp' . $mpv})) {
920                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
921                         if ($pos->{'toplay'} eq 'B') {
922                                 $score = -$score;
923                         }
924                         return sprintf "%+5.2f", $score;
925                 }
926         }
927
928         return undef;
929 }
930
931 sub long_score {
932         my ($uciinfo, $pos, $mpv) = @_;
933
934         if (defined($uciinfo{'score_mate' . $mpv})) {
935                 my $mate = $uciinfo{'score_mate' . $mpv};
936                 if ($pos->{'toplay'} eq 'B') {
937                         $mate = -$mate;
938                 }
939                 if ($mate > 0) {
940                         return sprintf "White mates in %u", $mate;
941                 } else {
942                         return sprintf "Black mates in %u", -$mate;
943                 }
944         } else {
945                 if (exists($uciinfo{'score_cp' . $mpv})) {
946                         my $score = $uciinfo{'score_cp' . $mpv} * 0.01;
947                         if ($pos->{'toplay'} eq 'B') {
948                                 $score = -$score;
949                         }
950                         return sprintf "Score: %+5.2f", $score;
951                 }
952         }
953
954         return undef;
955 }