]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Tag which engine we are talking to in ucilog.txt
[remoteglot] / remoteglot.pl
1 #! /usr/bin/perl
2
3 #
4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 #              analysis, or for live analysis of relayed games. (Do not use for
6 #              cheating! Cheating is bad for your karma, and your abuser flag.)
7 #
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
10 #
11
12 use Net::Telnet;
13 use FileHandle;
14 use IPC::Open2;
15 use Time::HiRes;
16 use strict;
17 use warnings;
18
19 # Configuration
20 my $server = "freechess.org";
21 my $target = "GMCarlsen";
22 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
23 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";
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 = 0;                    # dangerous :-)
27 my $second_engine_start_depth = 8;
28 my @masters = (
29         'Sesse',
30         'Sessse',
31         'Sesssse',
32         'greatestguns',
33         'beuki'
34 );
35
36 # Program starts here
37 $SIG{ALRM} = sub { output_screen(); };
38
39 $| = 1;
40
41 open(FICSLOG, ">ficslog.txt")
42         or die "ficslog.txt: $!";
43 print FICSLOG "Log starting.\n";
44 select(FICSLOG);
45 $| = 1;
46
47 open(UCILOG, ">ucilog.txt")
48         or die "ucilog.txt: $!";
49 print UCILOG "Log starting.\n";
50 select(UCILOG);
51 $| = 1;
52 select(STDOUT);
53
54 # open the chess engine
55 my $engine = open_engine($engine_cmdline, 'E1');
56 my $engine2 = open_engine($engine2_cmdline, 'E2');
57 my ($last_move, $last_tell);
58 my $last_text = '';
59 my $last_told_text = '';
60 my ($pos_waiting, $pos_calculating, $move_calculating_second_engine);
61 my %refutation_moves = ();
62
63 uciprint($engine, "setoption name UCI_AnalyseMode value true");
64 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
65 uciprint($engine, "setoption name NalimovUsage value Rarely");
66 uciprint($engine, "setoption name Hash value 1024");
67 # uciprint($engine, "setoption name MultiPV value 2");
68 uciprint($engine, "ucinewgame");
69
70 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
71 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
72 uciprint($engine2, "setoption name NalimovUsage value Rarely");
73 uciprint($engine2, "setoption name Hash value 1024");
74 uciprint($engine2, "setoption name Threads value 8");
75 # uciprint($engine2, "setoption name MultiPV value 2");
76 uciprint($engine2, "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("SesseBOT");
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($engine->{'read'}), 1) = 1;
100         vec($rin, fileno($engine2->{'read'}), 1) = 1;
101         vec($rin, fileno($t), 1) = 1;
102
103         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
104         my $sleep = 1.0;
105
106         while (1) {
107                 my $line = $t->getline(Timeout => 0, errmode => 'return');
108                 last if (!defined($line));
109
110                 chomp $line;
111                 $line =~ tr/\r//d;
112                 if ($line =~ /^<12> /) {
113                         my $pos = style12_to_pos($line);
114                         
115                         # if this is already in the queue, ignore it
116                         next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
117
118                         # if we're already chewing on this and there's nothing else in the queue,
119                         # also ignore it
120                         next if (!defined($pos_waiting) && defined($pos_calculating) &&
121                                  $pos->{'fen'} eq $pos_calculating->{'fen'});
122
123                         # if we're already thinking on something, stop and wait for the engine
124                         # to approve
125                         if (defined($pos_calculating)) {
126                                 if (!defined($pos_waiting)) {
127                                         uciprint($engine, "stop");
128                                 }
129                                 if ($uci_assume_full_compliance) {
130                                         $pos_waiting = $pos;
131                                 } else {
132                                         uciprint($engine, "position fen " . $pos->{'fen'});
133                                         uciprint($engine, "go infinite");
134                                         $pos_calculating = $pos;
135                                 }
136                         } else {
137                                 # it's wrong just to give the FEN (the move history is useful,
138                                 # and per the UCI spec, we should really have sent "ucinewgame"),
139                                 # but it's easier
140                                 uciprint($engine, "position fen " . $pos->{'fen'});
141                                 uciprint($engine, "go infinite");
142                                 $pos_calculating = $pos;
143                         }
144
145                         %refutation_moves = calculate_refutation_moves($pos);
146                         if (defined($move_calculating_second_engine)) {
147                                 uciprint($engine2, "stop");
148                                 $move_calculating_second_engine = undef;
149                         } else {
150                                 give_new_move_to_second_engine($pos);
151                         }
152
153                         $engine->{'info'} = {};
154                         $engine2->{'info'} = {};
155                         $last_move = time;
156
157                         # 
158                         # Output a command every move to note that we're
159                         # still paying attention -- this is a good tradeoff,
160                         # since if no move has happened in the last half
161                         # hour, the analysis/relay has most likely stopped
162                         # and we should stop hogging server resources.
163                         #
164                         $t->cmd("date");
165                 }
166                 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
167                         my ($who, $msg) = ($1, $2);
168
169                         next if (grep { $_ eq $who } (@masters) == 0);
170         
171                         if ($msg =~ /^fics (.*?)$/) {
172                                 $t->cmd("tell $who Executing '$1' on FICS.");
173                                 $t->cmd($1);
174                         } elsif ($msg =~ /^uci (.*?)$/) {
175                                 $t->cmd("tell $who Sending '$1' to the engine.");
176                                 print { $engine->{'write'} } "$1\n";
177                         } else {
178                                 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
179                         }
180                 }
181                 #print "FICS: [$line]\n";
182                 $sleep = 0;
183         }
184         
185         # any fun on the UCI channel?
186         if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
187                 my @lines = read_lines($engine);
188                 for my $line (@lines) {
189                         handle_uci($engine, $line, 1);
190                 }
191                 $sleep = 0;
192
193                 # don't update too often
194                 Time::HiRes::alarm(0.2);
195         }
196         if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
197                 my @lines = read_lines($engine2);
198                 for my $line (@lines) {
199                         handle_uci($engine2, $line, 0);
200                 }
201                 $sleep = 0;
202
203                 # don't update too often
204                 Time::HiRes::alarm(0.2);
205         }
206
207         sleep $sleep;
208 }
209
210 sub handle_uci {
211         my ($engine, $line, $primary) = @_;
212
213         chomp $line;
214         $line =~ tr/\r//d;
215         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
216         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
217         if ($line =~ /^info/) {
218                 my (@infos) = split / /, $line;
219                 shift @infos;
220
221                 parse_infos($engine, @infos);
222         }
223         if ($line =~ /^id/) {
224                 my (@ids) = split / /, $line;
225                 shift @ids;
226
227                 parse_ids($engine, @ids);
228         }
229         if ($line =~ /^bestmove/) {
230                 if ($primary) {
231                         return if (!$uci_assume_full_compliance);
232                         if (defined($pos_waiting)) {
233                                 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
234                                 uciprint($engine, "go infinite");
235
236                                 $pos_calculating = $pos_waiting;
237                                 $pos_waiting = undef;
238                         }
239                 } else {
240                         if (defined($move_calculating_second_engine)) { 
241                                 my $move = $refutation_moves{$move_calculating_second_engine};
242                                 $move->{'pv'} = $engine->{'info'}{'pv'};
243                                 $move->{'score_cp'} = $engine->{'info'}{'score_cp'} // $engine->{'info'}{'score_cp1'} // 0;
244                                 $move->{'score_mate'} = $engine->{'info'}{'score_mate'} // $engine->{'info'}{'score_mate1'};
245                                 $move->{'toplay'} = $pos_calculating->{'toplay'};
246                         }
247                         give_new_move_to_second_engine($pos_waiting // $pos_calculating);
248                 }
249         }
250 }
251
252 sub parse_infos {
253         my ($engine, @x) = @_;
254         my $mpv = '';
255
256         my $info = $engine->{'info'};
257
258         while (scalar @x > 0) {
259                 if ($x[0] =~ 'multipv') {
260                         shift @x;
261                         $mpv = shift @x;
262                         next;
263                 }
264                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
265                         my $key = shift @x;
266                         my $value = shift @x;
267                         $info->{$key} = $value;
268                         next;
269                 }
270                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
271                         my $key = shift @x;
272                         my $value = shift @x;
273                         $info->{$key . $mpv} = $value;
274                         next;
275                 }
276                 if ($x[0] eq 'score') {
277                         shift @x;
278
279                         delete $info->{'score_cp' . $mpv};
280                         delete $info->{'score_mate' . $mpv};
281
282                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
283                                 if ($x[0] eq 'cp') {
284                                         shift @x;
285                                         $info->{'score_cp' . $mpv} = shift @x;
286                                 } elsif ($x[0] eq 'mate') {
287                                         shift @x;
288                                         $info->{'score_mate' . $mpv} = shift @x;
289                                 } else {
290                                         shift @x;
291                                 }
292                         }
293                         next;
294                 }
295                 if ($x[0] eq 'pv') {
296                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
297                         last;
298                 }
299                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
300                         last;
301                 }
302
303                 #print "unknown info '$x[0]', trying to recover...\n";
304                 #shift @x;
305                 die "Unknown info '" . join(',', @x) . "'";
306
307         }
308 }
309
310 sub parse_ids {
311         my ($engine, @x) = @_;
312
313         while (scalar @x > 0) {
314                 if ($x[0] =~ /^(name|author)$/) {
315                         my $key = shift @x;
316                         my $value = join(' ', @x);
317                         $engine->{'id'}{$key} = $value;
318                         last;
319                 }
320
321                 # unknown
322                 shift @x;
323         }
324 }
325
326 sub style12_to_pos {
327         my $str = shift;
328         my %pos = ();
329         my (@x) = split / /, $str;
330         
331         $pos{'board'} = [ @x[1..8] ];
332         $pos{'toplay'} = $x[9];
333         $pos{'ep_file_num'} = $x[10];
334         $pos{'white_castle_k'} = $x[11];
335         $pos{'white_castle_q'} = $x[12];
336         $pos{'black_castle_k'} = $x[13];
337         $pos{'black_castle_q'} = $x[14];
338         $pos{'time_to_100move_rule'} = $x[15];
339         $pos{'move_num'} = $x[26];
340         $pos{'last_move'} = $x[29];
341         $pos{'fen'} = make_fen(\%pos);
342
343         return \%pos;
344 }
345
346 sub make_fen {
347         my $pos = shift;
348
349         # the board itself
350         my (@board) = @{$pos->{'board'}};
351         for my $rank (0..7) {
352                 $board[$rank] =~ s/(-+)/length($1)/ge;
353         }
354         my $fen = join('/', @board);
355
356         # white/black to move
357         $fen .= " ";
358         $fen .= lc($pos->{'toplay'});
359
360         # castling
361         my $castling = "";
362         $castling .= "K" if ($pos->{'white_castle_k'} == 1);
363         $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
364         $castling .= "k" if ($pos->{'black_castle_k'} == 1);
365         $castling .= "q" if ($pos->{'black_castle_q'} == 1);
366         $castling = "-" if ($castling eq "");
367         # $castling = "-"; # chess960
368         $fen .= " ";
369         $fen .= $castling;
370
371         # en passant
372         my $ep = "-";
373         if ($pos->{'ep_file_num'} != -1) {
374                 my $col = $pos->{'ep_file_num'};
375                 my $nep = (qw(a b c d e f g h))[$col];
376
377                 if ($pos->{'toplay'} eq 'B') {
378                         $nep .= "3";
379                 } else {
380                         $nep .= "6";
381                 }
382
383                 #
384                 # Showing the en passant square when actually no capture can be made
385                 # seems to confuse at least Rybka. Thus, check if there's actually
386                 # a pawn of the opposite side that can do the en passant move, and if
387                 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
388                 # "right" thing as per the standard, though.
389                 #
390                 if ($pos->{'toplay'} eq 'B') {
391                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
392                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
393                 } else {
394                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
395                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
396                 }
397         }
398         $fen .= " ";
399         $fen .= $ep;
400
401         # half-move clock
402         $fen .= " ";
403         $fen .= $pos->{'time_to_100move_rule'};
404
405         # full-move clock
406         $fen .= " ";
407         $fen .= $pos->{'move_num'};
408
409         return $fen;
410 }
411
412 sub make_move {
413         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
414         my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
415         my $piece = substr($board->[$from_row], $from_col, 1);
416         my @nb = @$board;
417
418         if ($piece eq '-') {
419                 die "Invalid move $move";
420         }
421
422         # white short castling
423         if ($move eq 'e1g1' && $piece eq 'K') {
424                 # king
425                 substr($nb[7], 4, 1, '-');
426                 substr($nb[7], 6, 1, $piece);
427                 
428                 # rook
429                 substr($nb[7], 7, 1, '-');
430                 substr($nb[7], 5, 1, 'R');
431                                 
432                 return \@nb;
433         }
434
435         # white long castling
436         if ($move eq 'e1c1' && $piece eq 'K') {
437                 # king
438                 substr($nb[7], 4, 1, '-');
439                 substr($nb[7], 2, 1, $piece);
440                 
441                 # rook
442                 substr($nb[7], 0, 1, '-');
443                 substr($nb[7], 3, 1, 'R');
444                                 
445                 return \@nb;
446         }
447
448         # black short castling
449         if ($move eq 'e8g8' && $piece eq 'k') {
450                 # king
451                 substr($nb[0], 4, 1, '-');
452                 substr($nb[0], 6, 1, $piece);
453                 
454                 # rook
455                 substr($nb[0], 7, 1, '-');
456                 substr($nb[0], 5, 1, 'r');
457                                 
458                 return \@nb;
459         }
460
461         # black long castling
462         if ($move eq 'e8c8' && $piece eq 'k') {
463                 # king
464                 substr($nb[0], 4, 1, '-');
465                 substr($nb[0], 2, 1, $piece);
466                 
467                 # rook
468                 substr($nb[0], 0, 1, '-');
469                 substr($nb[0], 3, 1, 'r');
470                                 
471                 return \@nb;
472         }
473
474         # check if the from-piece is a pawn
475         if (lc($piece) eq 'p') {
476                 # attack?
477                 if ($from_col != $to_col) {
478                         # en passant?
479                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
480                                 if ($piece eq 'p') {
481                                         substr($nb[$to_row + 1], $to_col, 1, '-');
482                                 } else {
483                                         substr($nb[$to_row - 1], $to_col, 1, '-');
484                                 }
485                         }
486                 } else {
487                         if ($promo ne '') {
488                                 if ($piece eq 'p') {
489                                         $piece = $promo;
490                                 } else {
491                                         $piece = uc($promo);
492                                 }
493                         }
494                 }
495         }
496
497         # update the board
498         substr($nb[$from_row], $from_col, 1, '-');
499         substr($nb[$to_row], $to_col, 1, $piece);
500
501         return \@nb;
502 }
503
504 sub prettyprint_pv {
505         my ($board, @pvs) = @_;
506
507         if (scalar @pvs == 0 || !defined($pvs[0])) {
508                 return ();
509         }
510
511         my $pv = shift @pvs;
512         my $from_col = col_letter_to_num(substr($pv, 0, 1));
513         my $from_row = row_letter_to_num(substr($pv, 1, 1));
514         my $to_col   = col_letter_to_num(substr($pv, 2, 1));
515         my $to_row   = row_letter_to_num(substr($pv, 3, 1));
516         my $promo    = substr($pv, 4, 1);
517
518         my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
519         my $piece = substr($board->[$from_row], $from_col, 1);
520
521         if ($piece eq '-') {
522                 die "Invalid move $pv";
523         }
524
525         # white short castling
526         if ($pv eq 'e1g1' && $piece eq 'K') {
527                 return ('0-0', prettyprint_pv($nb, @pvs));
528         }
529
530         # white long castling
531         if ($pv eq 'e1c1' && $piece eq 'K') {
532                 return ('0-0-0', prettyprint_pv($nb, @pvs));
533         }
534
535         # black short castling
536         if ($pv eq 'e8g8' && $piece eq 'k') {
537                 return ('0-0', prettyprint_pv($nb, @pvs));
538         }
539
540         # black long castling
541         if ($pv eq 'e8c8' && $piece eq 'k') {
542                 return ('0-0-0', prettyprint_pv($nb, @pvs));
543         }
544
545         my $pretty;
546
547         # check if the from-piece is a pawn
548         if (lc($piece) eq 'p') {
549                 # attack?
550                 if ($from_col != $to_col) {
551                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
552                 } else {
553                         $pretty = substr($pv, 2, 2);
554
555                         if (length($pv) == 5) {
556                                 # promotion
557                                 $pretty .= "=";
558                                 $pretty .= uc(substr($pv, 4, 1));
559
560                                 if ($piece eq 'p') {
561                                         $piece = substr($pv, 4, 1);
562                                 } else {
563                                         $piece = uc(substr($pv, 4, 1));
564                                 }
565                         }
566                 }
567         } else {
568                 $pretty = uc($piece);
569
570                 # see how many of these pieces could go here, in all
571                 my $num_total = 0;
572                 for my $col (0..7) {
573                         for my $row (0..7) {
574                                 next unless (substr($board->[$row], $col, 1) eq $piece);
575                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
576                         }
577                 }
578
579                 # see how many of these pieces from the given row could go here
580                 my $num_row = 0;
581                 for my $col (0..7) {
582                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
583                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
584                 }
585                 
586                 # and same for columns
587                 my $num_col = 0;
588                 for my $row (0..7) {
589                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
590                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
591                 }
592                 
593                 # see if we need to disambiguate
594                 if ($num_total > 1) {
595                         if ($num_col == 1) {
596                                 $pretty .= substr($pv, 0, 1);
597                         } elsif ($num_row == 1) {
598                                 $pretty .= substr($pv, 1, 1);
599                         } else {
600                                 $pretty .= substr($pv, 0, 2);
601                         }
602                 }
603
604                 # attack?
605                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
606                         $pretty .= 'x';
607                 }
608
609                 $pretty .= substr($pv, 2, 2);
610         }
611
612         if (in_mate($nb)) {
613                 $pretty .= '#';
614         } elsif (in_check($nb) ne 'none') {
615                 $pretty .= '+';
616         }
617         return ($pretty, prettyprint_pv($nb, @pvs));
618 }
619
620 sub output_screen {
621         #return;
622         
623         return if (!defined($pos_calculating));
624
625         my $info = $engine->{'info'};
626         my $id = $engine->{'id'};
627
628         #
629         # Check the PVs first. if they're invalid, just wait, as our data
630         # is most likely out of sync. This isn't a very good solution, as
631         # it can frequently miss stuff, but it's good enough for most users.
632         #
633         eval {
634                 my $dummy;
635                 if (exists($info->{'pv'})) {
636                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
637                 }
638         
639                 my $mpv = 1;
640                 while (exists($info->{'pv' . $mpv})) {
641                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
642                         ++$mpv;
643                 }
644         };
645         if ($@) {
646                 $engine->{'info'} = {};
647                 return;
648         }
649
650         my $text = 'Analysis';
651         if ($pos_calculating->{'last_move'} ne 'none') {
652                 if ($pos_calculating->{'toplay'} eq 'W') {
653                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
654                 } else {
655                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
656                 }
657                 if (exists($id->{'name'})) {
658                         $text .= ',';
659                 }
660         }
661
662         if (exists($id->{'name'})) {
663                 $text .= " by $id->{'name'}:\n\n";
664         } else {
665                 $text .= ":\n\n";
666         }
667
668         return unless (exists($pos_calculating->{'board'}));
669                 
670         #
671         # Some programs _always_ report MultiPV, even with only one PV.
672         # In this case, we simply use that data as if MultiPV was never
673         # specified.
674         #
675         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
676                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
677                         if (exists($info->{$key . '1'}) && !exists($info->{$key})) {
678                                 $info->{$key} = $info->{$key . '1'};
679                         }
680                 }
681         }
682
683         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
684                 # multi-PV
685                 my $mpv = 1;
686                 while (exists($info->{'pv' . $mpv})) {
687                         $text .= sprintf "  PV%2u", $mpv;
688                         my $score = short_score($info, $pos_calculating, $mpv);
689                         $text .= "  ($score)" if (defined($score));
690
691                         my $tbhits = '';
692                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
693                                 if ($info->{'tbhits' . $mpv} == 1) {
694                                         $tbhits = ", 1 tbhit";
695                                 } else {
696                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
697                                 }
698                         }
699
700                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
701                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
702                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
703                         }
704
705                         $text .= ":\n";
706                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
707                         $text .= "\n";
708                         ++$mpv;
709                 }
710         } else {
711                 # single-PV
712                 my $score = long_score($info, $pos_calculating, '');
713                 $text .= "  $score\n" if defined($score);
714                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
715                 $text .=  "\n";
716
717                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
718                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
719                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
720                 }
721                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
722                         if ($info->{'tbhits'} == 1) {
723                                 $text .= ", one Nalimov hit";
724                         } else {
725                                 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
726                         }
727                 }
728                 if (exists($info->{'seldepth'})) {
729                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
730                 }
731                 $text .= "\n\n";
732         }
733
734         #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
735
736         my @refutation_lines = ();
737         for my $move (keys %refutation_moves) {
738                 eval {
739                         my $m = $refutation_moves{$move};
740                         next if ($m->{'depth'} < $second_engine_start_depth);
741                         my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
742                         my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
743                         if (scalar @pretty_pv > 5) {
744                                 @pretty_pv = @pretty_pv[0..4];
745                                 push @pretty_pv, "...";
746                         }
747                         #my $key = score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1);
748                         my $key = $pretty_move;
749                         my $line = sprintf("  %-6s %6s %3s  %s",
750                                 $pretty_move,
751                                 short_score($refutation_moves{$move}, $pos_calculating, '', 1),
752                                 "d" . $m->{'depth'},
753                                 join(', ', @pretty_pv));
754                         push @refutation_lines, [ $key, $line ];
755                 };
756         }
757
758         if ($#refutation_lines >= 0) {
759                 $text .= "Shallow search of all legal moves:\n\n";
760                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
761                         $text .= $line->[1] . "\n";
762                 }
763                 $text .= "\n\n";        
764         }       
765
766         if ($last_text ne $text) {
767                 print "\e[H\e[2J"; # clear the screen
768                 print $text;
769                 $last_text = $text;
770         }
771
772         # Now construct the tell text, if any
773         return if (!defined($telltarget));
774
775         my $tell_text = '';
776
777         if (exists($id->{'name'})) {
778                 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
779         } else {
780                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
781         }
782
783         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
784                 # multi-PV
785                 my $mpv = 1;
786                 while (exists($info->{'pv' . $mpv})) {
787                         $tell_text .= sprintf "  PV%2u", $mpv;
788                         my $score = short_score($info, $pos_calculating, $mpv);
789                         $tell_text .= "  ($score)" if (defined($score));
790
791                         if (exists($info->{'depth' . $mpv})) {
792                                 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
793                         }
794
795                         $tell_text .= ": ";
796                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
797                         $tell_text .= "\n";
798                         ++$mpv;
799                 }
800         } else {
801                 # single-PV
802                 my $score = long_score($info, $pos_calculating, '');
803                 $tell_text .= "  $score\n" if defined($score);
804                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
805                 if (exists($info->{'depth'})) {
806                         $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
807                 }
808                 $tell_text .=  "\n";
809         }
810
811         # see if a new tell is called for -- it is if the delay has expired _and_
812         # this is not simply a repetition of the last one
813         if ($last_told_text ne $tell_text) {
814                 my $now = time;
815                 for my $iv (@tell_intervals) {
816                         last if ($now - $last_move < $iv);
817                         next if ($last_tell - $last_move >= $iv);
818
819                         for my $line (split /\n/, $tell_text) {
820                                 $t->print("tell $telltarget [$target] $line");
821                         }
822
823                         $last_told_text = $text;
824                         $last_tell = $now;
825
826                         last;
827                 }
828         }
829 }
830
831 sub find_kings {
832         my $board = shift;
833         my ($wkr, $wkc, $bkr, $bkc);
834
835         for my $row (0..7) {
836                 for my $col (0..7) {
837                         my $piece = substr($board->[$row], $col, 1);
838                         if ($piece eq 'K') {
839                                 ($wkr, $wkc) = ($row, $col);
840                         } elsif ($piece eq 'k') {
841                                 ($bkr, $bkc) = ($row, $col);
842                         }
843                 }
844         }
845
846         return ($wkr, $wkc, $bkr, $bkc);
847 }
848
849 sub in_mate {
850         my $board = shift;
851         my $check = in_check($board);
852         return 0 if ($check eq 'none');
853
854         # try all possible moves for the side in check
855         for my $row (0..7) {
856                 for my $col (0..7) {
857                         my $piece = substr($board->[$row], $col, 1);
858                         next if ($piece eq '-');
859
860                         if ($check eq 'white') {
861                                 next if ($piece eq lc($piece));
862                         } else {
863                                 next if ($piece eq uc($piece));
864                         }
865
866                         for my $dest_row (0..7) {
867                                 for my $dest_col (0..7) {
868                                         next if ($row == $dest_row && $col == $dest_col);
869                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
870
871                                         my @nb = @$board;
872                                         substr($nb[$row], $col, 1, '-');
873                                         substr($nb[$dest_row], $dest_col, 1, $piece);
874
875                                         my $new_check = in_check(\@nb);
876                                         return 0 if ($new_check ne $check && $new_check ne 'both');
877                                 }
878                         }
879                 }
880         }
881
882         # nothing to do; mate
883         return 1;
884 }
885
886 sub in_check {
887         my $board = shift;
888         my ($black_check, $white_check) = (0, 0);
889
890         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
891
892         # check all pieces for the possibility of threatening the two kings
893         for my $row (0..7) {
894                 for my $col (0..7) {
895                         my $piece = substr($board->[$row], $col, 1);
896                         next if ($piece eq '-');
897                 
898                         if (uc($piece) eq $piece) {
899                                 # white piece
900                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
901                         } else {
902                                 # black piece
903                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
904                         }
905                 }
906         }
907
908         if ($black_check && $white_check) {
909                 return 'both';
910         } elsif ($black_check) {
911                 return 'black';
912         } elsif ($white_check) {
913                 return 'white';
914         } else {
915                 return 'none';
916         }
917 }
918
919 sub can_reach {
920         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
921         
922         # can't eat your own piece
923         my $dest_piece = substr($board->[$to_row], $to_col, 1);
924         if ($dest_piece ne '-') {
925                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
926         }
927
928         if (lc($piece) eq 'k') {
929                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
930         }
931         if (lc($piece) eq 'r') {
932                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
933
934                 # check that there's a clear passage
935                 if ($from_row == $to_row) {
936                         if ($from_col > $to_col) {
937                                 ($to_col, $from_col) = ($from_col, $to_col);
938                         }
939
940                         for my $c (($from_col+1)..($to_col-1)) {
941                                 my $middle_piece = substr($board->[$to_row], $c, 1);
942                                 return 0 if ($middle_piece ne '-');     
943                         }
944
945                         return 1;
946                 } else {
947                         if ($from_row > $to_row) {
948                                 ($to_row, $from_row) = ($from_row, $to_row);
949                         }
950
951                         for my $r (($from_row+1)..($to_row-1)) {
952                                 my $middle_piece = substr($board->[$r], $to_col, 1);
953                                 return 0 if ($middle_piece ne '-');     
954                         }
955
956                         return 1;
957                 }
958         }
959         if (lc($piece) eq 'b') {
960                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
961
962                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
963                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
964
965                 my $r = $from_row + $dr;
966                 my $c = $from_col + $dc;
967
968                 while ($r != $to_row) {
969                         my $middle_piece = substr($board->[$r], $c, 1);
970                         return 0 if ($middle_piece ne '-');
971                         
972                         $r += $dr;
973                         $c += $dc;
974                 }
975
976                 return 1;
977         }
978         if (lc($piece) eq 'n') {
979                 my $diff_r = abs($from_row - $to_row);
980                 my $diff_c = abs($from_col - $to_col);
981                 return 1 if ($diff_r == 2 && $diff_c == 1);
982                 return 1 if ($diff_r == 1 && $diff_c == 2);
983                 return 0;
984         }
985         if ($piece eq 'q') {
986                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
987                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
988         }
989         if ($piece eq 'Q') {
990                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
991                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
992         }
993
994         # TODO: en passant
995         if ($piece eq 'p') {
996                 # black pawn
997                 if ($to_col == $from_col && $to_row == $from_row + 1) {
998                         return ($dest_piece eq '-');
999                 }
1000                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1001                         my $middle_piece = substr($board->[2], $to_col, 1);
1002                         return ($dest_piece eq '-' && $middle_piece eq '-');
1003                 }
1004                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1005                         return ($dest_piece ne '-');
1006                 }
1007                 return 0;
1008         }
1009         if ($piece eq 'P') {
1010                 # white pawn
1011                 if ($to_col == $from_col && $to_row == $from_row - 1) {
1012                         return ($dest_piece eq '-');
1013                 }
1014                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1015                         my $middle_piece = substr($board->[5], $to_col, 1);
1016                         return ($dest_piece eq '-' && $middle_piece eq '-');
1017                 }
1018                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1019                         return ($dest_piece ne '-');
1020                 }
1021                 return 0;
1022         }
1023         
1024         # unknown piece
1025         return 0;
1026 }
1027
1028 sub uciprint {
1029         my ($engine, $msg) = @_;
1030         print { $engine->{'write'} } "$msg\n";
1031         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1032 }
1033
1034 sub short_score {
1035         my ($info, $pos, $mpv, $invert) = @_;
1036
1037         $invert //= 0;
1038         if ($pos->{'toplay'} eq 'B') {
1039                 $invert = !$invert;
1040         }
1041
1042         if (defined($info->{'score_mate' . $mpv})) {
1043                 if ($invert) {
1044                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
1045                 } else {
1046                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1047                 }
1048         } else {
1049                 if (exists($info->{'score_cp' . $mpv})) {
1050                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1051                         if ($invert) {
1052                                 $score = -$score;
1053                         }
1054                         return sprintf "%+5.2f", $score;
1055                 }
1056         }
1057
1058         return undef;
1059 }
1060
1061 sub score_sort_key {
1062         my ($info, $pos, $mpv, $invert) = @_;
1063
1064         $invert //= 0;
1065         if ($pos->{'toplay'} eq 'B') {
1066                 $invert = !$invert;
1067         }
1068
1069         if (defined($info->{'score_mate' . $mpv})) {
1070                 if ($invert) {
1071                         return -(99999 - $info->{'score_mate' . $mpv});
1072                 } else {
1073                         return 99999 - $info->{'score_mate' . $mpv};
1074                 }
1075         } else {
1076                 if (exists($info->{'score_cp' . $mpv})) {
1077                         my $score = $info->{'score_cp' . $mpv};
1078                         if ($invert) {
1079                                 $score = -$score;
1080                         }
1081                         return $score;
1082                 }
1083         }
1084
1085         return undef;
1086 }
1087
1088 sub long_score {
1089         my ($info, $pos, $mpv) = @_;
1090
1091         if (defined($info->{'score_mate' . $mpv})) {
1092                 my $mate = $info->{'score_mate' . $mpv};
1093                 if ($pos->{'toplay'} eq 'B') {
1094                         $mate = -$mate;
1095                 }
1096                 if ($mate > 0) {
1097                         return sprintf "White mates in %u", $mate;
1098                 } else {
1099                         return sprintf "Black mates in %u", -$mate;
1100                 }
1101         } else {
1102                 if (exists($info->{'score_cp' . $mpv})) {
1103                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1104                         if ($pos->{'toplay'} eq 'B') {
1105                                 $score = -$score;
1106                         }
1107                         return sprintf "Score: %+5.2f", $score;
1108                 }
1109         }
1110
1111         return undef;
1112 }
1113
1114 my %book_cache = ();
1115 sub book_info {
1116         my ($fen, $board, $toplay) = @_;
1117
1118         if (exists($book_cache{$fen})) {
1119                 return $book_cache{$fen};
1120         }
1121
1122         my $ret = `./booklook $fen`;
1123         return "" if ($ret =~ /Not found/ || $ret eq '');
1124
1125         my @moves = ();
1126
1127         for my $m (split /\n/, $ret) {
1128                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1129
1130                 my $pmove;
1131                 if ($move eq '')  {
1132                         $pmove = '(current)';
1133                 } else {
1134                         ($pmove) = prettyprint_pv($board, $move);
1135                         $pmove .= $annotation;
1136                 }
1137
1138                 my $score;
1139                 if ($toplay eq 'W') {
1140                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1141                 } else {
1142                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1143                 }
1144                 my $n = $win + $draw + $lose;
1145                 
1146                 my $percent;
1147                 if ($n == 0) {
1148                         $percent = "     ";
1149                 } else {
1150                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1151                 }
1152
1153                 push @moves, [ $pmove, $n, $percent, $rating ];
1154         }
1155
1156         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1157         
1158         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1159         for my $m (@moves) {
1160                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1161         }
1162
1163         return $text;
1164 }
1165
1166 sub open_engine {
1167         my ($cmdline, $tag) = @_;
1168         my ($uciread, $uciwrite);
1169         my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1170
1171         my $engine = {
1172                 pid => $pid,
1173                 read => $uciread,
1174                 readbuf => '',
1175                 write => $uciwrite,
1176                 info => {},
1177                 ids => {},
1178                 tag => $tag,
1179         };
1180
1181         uciprint($engine, "uci");
1182
1183         # gobble the options
1184         while (<$uciread>) {
1185                 /uciok/ && last;
1186                 handle_uci($engine, $_);
1187         }
1188         
1189         return $engine;
1190 }
1191
1192 sub read_lines {
1193         my $engine = shift;
1194
1195         # 
1196         # Read until we've got a full line -- if the engine sends part of
1197         # a line and then stops we're pretty much hosed, but that should
1198         # never happen.
1199         #
1200         while ($engine->{'readbuf'} !~ /\n/) {
1201                 my $tmp;
1202                 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1203
1204                 if (!defined($ret)) {
1205                         next if ($!{EINTR});
1206                         die "error in reading from the UCI engine: $!";
1207                 } elsif ($ret == 0) {
1208                         die "EOF from UCI engine";
1209                 }
1210
1211                 $engine->{'readbuf'} .= $tmp;
1212         }
1213
1214         # Blah.
1215         my @lines = ();
1216         while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1217                 my $line = $1;
1218                 $line =~ tr/\r\n//d;
1219                 push @lines, $line;
1220         }
1221         return @lines;
1222 }
1223
1224 # Find all possible legal moves.
1225 sub calculate_refutation_moves {
1226         my $pos = shift;
1227         my $board = $pos->{'board'};
1228         my %refutation_moves = ();
1229         for my $col (0..7) {
1230                 for my $row (0..7) {
1231                         my $piece = substr($board->[$row], $col, 1);
1232
1233                         # Check that there's a piece of the right color on this square.
1234                         next if ($piece eq '-');
1235                         if ($pos->{'toplay'} eq 'W') {
1236                                 next if ($piece ne uc($piece));
1237                         } else {
1238                                 next if ($piece ne lc($piece));
1239                         }
1240
1241                         for my $to_col (0..7) {
1242                                 for my $to_row (0..7) {
1243                                         next if ($col == $to_col && $row == $to_row);
1244                                         next unless (can_reach($board, $piece, $row, $col, $to_row, $to_col));
1245
1246                                         my $promo = "";  # FIXME
1247                                         my $nb = make_move($board, $row, $col, $to_row, $to_col, $promo);
1248                                         my $check = in_check($nb);
1249                                         next if ($check eq 'both');
1250                                         if ($pos->{'toplay'} eq 'W') {
1251                                                 next if ($check eq 'white');
1252                                         } else {
1253                                                 next if ($check eq 'black');
1254                                         }
1255                                         my $move = move_to_uci_notation($row, $col, $to_row, $to_col, $promo);
1256                                         $refutation_moves{$move} = { depth => $second_engine_start_depth - 1, score_cp => 0, pv => '' };
1257                                 }
1258                         }
1259                 }
1260         }
1261         return %refutation_moves;
1262 }
1263
1264 sub give_new_move_to_second_engine {
1265         my $pos = shift;
1266                                 
1267         # Find the move that's been analyzed the shortest but is most promising.
1268         # Tie-break on UCI move representation.
1269         my $best_move = undef;
1270         for my $move (sort keys %refutation_moves) {
1271                 if (!defined($best_move)) {
1272                         $best_move = $move;
1273                         next;
1274                 }
1275                 my $best = $refutation_moves{$best_move};
1276                 my $this = $refutation_moves{$move};
1277
1278                 if ($this->{'depth'} < $best->{'depth'} ||
1279                     ($this->{'depth'} == $best->{'depth'} && $this->{'score_cp'} < $best->{'score_cp'})) {
1280                         $best_move = $move;
1281                         next;
1282                 }
1283         }
1284
1285         my $m = $refutation_moves{$best_move};
1286         ++$m->{'depth'};
1287         uciprint($engine2, "position fen " . $pos->{'fen'} . " moves " . $best_move);
1288         uciprint($engine2, "go depth " . $m->{'depth'});
1289         $move_calculating_second_engine = $best_move;
1290 }
1291
1292 sub col_letter_to_num {
1293         return ord(shift) - ord('a');
1294 }
1295
1296 sub row_letter_to_num {
1297         return 7 - (ord(shift) - ord('1'));
1298 }
1299
1300 sub move_to_uci_notation {
1301         my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1302         $promo //= "";
1303         return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);
1304 }