]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Fix refutation display with always-mpv-engines.
[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 $update_max_interval = 2.0;
28 my $second_engine_start_depth = 8;
29 my @masters = (
30         'Sesse',
31         'Sessse',
32         'Sesssse',
33         'greatestguns',
34         'beuki'
35 );
36
37 # Program starts here
38 $SIG{ALRM} = sub { output_screen(); };
39 my $latest_update = undef;
40
41 $| = 1;
42
43 open(FICSLOG, ">ficslog.txt")
44         or die "ficslog.txt: $!";
45 print FICSLOG "Log starting.\n";
46 select(FICSLOG);
47 $| = 1;
48
49 open(UCILOG, ">ucilog.txt")
50         or die "ucilog.txt: $!";
51 print UCILOG "Log starting.\n";
52 select(UCILOG);
53 $| = 1;
54 select(STDOUT);
55
56 # open the chess engine
57 my $engine = open_engine($engine_cmdline, 'E1');
58 my $engine2 = open_engine($engine2_cmdline, 'E2');
59 my ($last_move, $last_tell);
60 my $last_text = '';
61 my $last_told_text = '';
62 my ($pos_waiting, $pos_calculating, $move_calculating_second_engine);
63 my %refutation_moves = ();
64
65 uciprint($engine, "setoption name UCI_AnalyseMode value true");
66 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
67 uciprint($engine, "setoption name NalimovUsage value Rarely");
68 uciprint($engine, "setoption name Hash value 1024");
69 # uciprint($engine, "setoption name MultiPV value 2");
70 uciprint($engine, "ucinewgame");
71
72 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
73 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
74 uciprint($engine2, "setoption name NalimovUsage value Rarely");
75 uciprint($engine2, "setoption name Hash value 1024");
76 uciprint($engine2, "setoption name Threads value 8");
77 # uciprint($engine2, "setoption name MultiPV value 2");
78 uciprint($engine2, "ucinewgame");
79
80 print "Chess engine ready.\n";
81
82 # now talk to FICS
83 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
84 $t->input_log(\*FICSLOG);
85 $t->open($server);
86 $t->print("SesseBOT");
87 $t->waitfor('/Press return to enter the server/');
88 $t->cmd("");
89
90 # set some options
91 $t->cmd("set shout 0");
92 $t->cmd("set seek 0");
93 $t->cmd("set style 12");
94 $t->cmd("observe $target");
95
96 # main loop
97 print "FICS ready.\n";
98 while (1) {
99         my $rin = '';
100         my $rout;
101         vec($rin, fileno($engine->{'read'}), 1) = 1;
102         vec($rin, fileno($engine2->{'read'}), 1) = 1;
103         vec($rin, fileno($t), 1) = 1;
104
105         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
106         my $sleep = 1.0;
107
108         while (1) {
109                 my $line = $t->getline(Timeout => 0, errmode => 'return');
110                 last if (!defined($line));
111
112                 chomp $line;
113                 $line =~ tr/\r//d;
114                 if ($line =~ /^<12> /) {
115                         my $pos = style12_to_pos($line);
116                         
117                         # if this is already in the queue, ignore it
118                         next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
119
120                         # if we're already chewing on this and there's nothing else in the queue,
121                         # also ignore it
122                         next if (!defined($pos_waiting) && defined($pos_calculating) &&
123                                  $pos->{'fen'} eq $pos_calculating->{'fen'});
124
125                         # if we're already thinking on something, stop and wait for the engine
126                         # to approve
127                         if (defined($pos_calculating)) {
128                                 if (!defined($pos_waiting)) {
129                                         uciprint($engine, "stop");
130                                 }
131                                 if ($uci_assume_full_compliance) {
132                                         $pos_waiting = $pos;
133                                 } else {
134                                         uciprint($engine, "position fen " . $pos->{'fen'});
135                                         uciprint($engine, "go infinite");
136                                         $pos_calculating = $pos;
137                                 }
138                         } else {
139                                 # it's wrong just to give the FEN (the move history is useful,
140                                 # and per the UCI spec, we should really have sent "ucinewgame"),
141                                 # but it's easier
142                                 uciprint($engine, "position fen " . $pos->{'fen'});
143                                 uciprint($engine, "go infinite");
144                                 $pos_calculating = $pos;
145                         }
146
147                         %refutation_moves = calculate_refutation_moves($pos);
148                         if (defined($move_calculating_second_engine)) {
149                                 uciprint($engine2, "stop");
150                                 $move_calculating_second_engine = undef;
151                         } else {
152                                 give_new_move_to_second_engine($pos);
153                         }
154
155                         $engine->{'info'} = {};
156                         $engine2->{'info'} = {};
157                         $last_move = time;
158
159                         # 
160                         # Output a command every move to note that we're
161                         # still paying attention -- this is a good tradeoff,
162                         # since if no move has happened in the last half
163                         # hour, the analysis/relay has most likely stopped
164                         # and we should stop hogging server resources.
165                         #
166                         $t->cmd("date");
167                 }
168                 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
169                         my ($who, $msg) = ($1, $2);
170
171                         next if (grep { $_ eq $who } (@masters) == 0);
172         
173                         if ($msg =~ /^fics (.*?)$/) {
174                                 $t->cmd("tell $who Executing '$1' on FICS.");
175                                 $t->cmd($1);
176                         } elsif ($msg =~ /^uci (.*?)$/) {
177                                 $t->cmd("tell $who Sending '$1' to the engine.");
178                                 print { $engine->{'write'} } "$1\n";
179                         } else {
180                                 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
181                         }
182                 }
183                 #print "FICS: [$line]\n";
184                 $sleep = 0;
185         }
186         
187         # any fun on the UCI channel?
188         if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
189                 my @lines = read_lines($engine);
190                 for my $line (@lines) {
191                         handle_uci($engine, $line, 1);
192                 }
193                 $sleep = 0;
194
195                 output_screen();
196         }
197         if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
198                 my @lines = read_lines($engine2);
199                 for my $line (@lines) {
200                         handle_uci($engine2, $line, 0);
201                 }
202                 $sleep = 0;
203
204                 output_screen();
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'} // $engine->{'info'}{'pv1'};
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         # Don't update too often.
626         my $age = Time::HiRes::tv_interval($latest_update);
627         if ($age < $update_max_interval) {
628                 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
629                 return;
630         }
631         $latest_update = [Time::HiRes::gettimeofday];
632
633         my $info = $engine->{'info'};
634         my $id = $engine->{'id'};
635
636         #
637         # Check the PVs first. if they're invalid, just wait, as our data
638         # is most likely out of sync. This isn't a very good solution, as
639         # it can frequently miss stuff, but it's good enough for most users.
640         #
641         eval {
642                 my $dummy;
643                 if (exists($info->{'pv'})) {
644                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
645                 }
646         
647                 my $mpv = 1;
648                 while (exists($info->{'pv' . $mpv})) {
649                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
650                         ++$mpv;
651                 }
652         };
653         if ($@) {
654                 $engine->{'info'} = {};
655                 return;
656         }
657
658         my $text = 'Analysis';
659         if ($pos_calculating->{'last_move'} ne 'none') {
660                 if ($pos_calculating->{'toplay'} eq 'W') {
661                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
662                 } else {
663                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
664                 }
665                 if (exists($id->{'name'})) {
666                         $text .= ',';
667                 }
668         }
669
670         if (exists($id->{'name'})) {
671                 $text .= " by $id->{'name'}:\n\n";
672         } else {
673                 $text .= ":\n\n";
674         }
675
676         return unless (exists($pos_calculating->{'board'}));
677                 
678         #
679         # Some programs _always_ report MultiPV, even with only one PV.
680         # In this case, we simply use that data as if MultiPV was never
681         # specified.
682         #
683         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
684                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
685                         if (exists($info->{$key . '1'}) && !exists($info->{$key})) {
686                                 $info->{$key} = $info->{$key . '1'};
687                         }
688                 }
689         }
690
691         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
692                 # multi-PV
693                 my $mpv = 1;
694                 while (exists($info->{'pv' . $mpv})) {
695                         $text .= sprintf "  PV%2u", $mpv;
696                         my $score = short_score($info, $pos_calculating, $mpv);
697                         $text .= "  ($score)" if (defined($score));
698
699                         my $tbhits = '';
700                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
701                                 if ($info->{'tbhits' . $mpv} == 1) {
702                                         $tbhits = ", 1 tbhit";
703                                 } else {
704                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
705                                 }
706                         }
707
708                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
709                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
710                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
711                         }
712
713                         $text .= ":\n";
714                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
715                         $text .= "\n";
716                         ++$mpv;
717                 }
718         } else {
719                 # single-PV
720                 my $score = long_score($info, $pos_calculating, '');
721                 $text .= "  $score\n" if defined($score);
722                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
723                 $text .=  "\n";
724
725                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
726                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
727                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
728                 }
729                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
730                         if ($info->{'tbhits'} == 1) {
731                                 $text .= ", one Nalimov hit";
732                         } else {
733                                 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
734                         }
735                 }
736                 if (exists($info->{'seldepth'})) {
737                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
738                 }
739                 $text .= "\n\n";
740         }
741
742         #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
743
744         my @refutation_lines = ();
745         for my $move (keys %refutation_moves) {
746                 eval {
747                         my $m = $refutation_moves{$move};
748                         die if ($m->{'depth'} < $second_engine_start_depth);
749                         my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
750                         my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
751                         if (scalar @pretty_pv > 5) {
752                                 @pretty_pv = @pretty_pv[0..4];
753                                 push @pretty_pv, "...";
754                         }
755                         #my $key = score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1);
756                         my $key = $pretty_move;
757                         my $line = sprintf("  %-6s %6s %3s  %s",
758                                 $pretty_move,
759                                 short_score($refutation_moves{$move}, $pos_calculating, '', 1),
760                                 "d" . $m->{'depth'},
761                                 join(', ', @pretty_pv));
762                         push @refutation_lines, [ $key, $line ];
763                 };
764         }
765
766         if ($#refutation_lines >= 0) {
767                 $text .= "Shallow search of all legal moves:\n\n";
768                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
769                         $text .= $line->[1] . "\n";
770                 }
771                 $text .= "\n\n";        
772         }       
773
774         if ($last_text ne $text) {
775                 print "\e[H\e[2J"; # clear the screen
776                 print $text;
777                 $last_text = $text;
778         }
779
780         # Now construct the tell text, if any
781         return if (!defined($telltarget));
782
783         my $tell_text = '';
784
785         if (exists($id->{'name'})) {
786                 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
787         } else {
788                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
789         }
790
791         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
792                 # multi-PV
793                 my $mpv = 1;
794                 while (exists($info->{'pv' . $mpv})) {
795                         $tell_text .= sprintf "  PV%2u", $mpv;
796                         my $score = short_score($info, $pos_calculating, $mpv);
797                         $tell_text .= "  ($score)" if (defined($score));
798
799                         if (exists($info->{'depth' . $mpv})) {
800                                 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
801                         }
802
803                         $tell_text .= ": ";
804                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
805                         $tell_text .= "\n";
806                         ++$mpv;
807                 }
808         } else {
809                 # single-PV
810                 my $score = long_score($info, $pos_calculating, '');
811                 $tell_text .= "  $score\n" if defined($score);
812                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
813                 if (exists($info->{'depth'})) {
814                         $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
815                 }
816                 $tell_text .=  "\n";
817         }
818
819         # see if a new tell is called for -- it is if the delay has expired _and_
820         # this is not simply a repetition of the last one
821         if ($last_told_text ne $tell_text) {
822                 my $now = time;
823                 for my $iv (@tell_intervals) {
824                         last if ($now - $last_move < $iv);
825                         next if ($last_tell - $last_move >= $iv);
826
827                         for my $line (split /\n/, $tell_text) {
828                                 $t->print("tell $telltarget [$target] $line");
829                         }
830
831                         $last_told_text = $text;
832                         $last_tell = $now;
833
834                         last;
835                 }
836         }
837 }
838
839 sub find_kings {
840         my $board = shift;
841         my ($wkr, $wkc, $bkr, $bkc);
842
843         for my $row (0..7) {
844                 for my $col (0..7) {
845                         my $piece = substr($board->[$row], $col, 1);
846                         if ($piece eq 'K') {
847                                 ($wkr, $wkc) = ($row, $col);
848                         } elsif ($piece eq 'k') {
849                                 ($bkr, $bkc) = ($row, $col);
850                         }
851                 }
852         }
853
854         return ($wkr, $wkc, $bkr, $bkc);
855 }
856
857 sub in_mate {
858         my $board = shift;
859         my $check = in_check($board);
860         return 0 if ($check eq 'none');
861
862         # try all possible moves for the side in check
863         for my $row (0..7) {
864                 for my $col (0..7) {
865                         my $piece = substr($board->[$row], $col, 1);
866                         next if ($piece eq '-');
867
868                         if ($check eq 'white') {
869                                 next if ($piece eq lc($piece));
870                         } else {
871                                 next if ($piece eq uc($piece));
872                         }
873
874                         for my $dest_row (0..7) {
875                                 for my $dest_col (0..7) {
876                                         next if ($row == $dest_row && $col == $dest_col);
877                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
878
879                                         my @nb = @$board;
880                                         substr($nb[$row], $col, 1, '-');
881                                         substr($nb[$dest_row], $dest_col, 1, $piece);
882
883                                         my $new_check = in_check(\@nb);
884                                         return 0 if ($new_check ne $check && $new_check ne 'both');
885                                 }
886                         }
887                 }
888         }
889
890         # nothing to do; mate
891         return 1;
892 }
893
894 sub in_check {
895         my $board = shift;
896         my ($black_check, $white_check) = (0, 0);
897
898         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
899
900         # check all pieces for the possibility of threatening the two kings
901         for my $row (0..7) {
902                 for my $col (0..7) {
903                         my $piece = substr($board->[$row], $col, 1);
904                         next if ($piece eq '-');
905                 
906                         if (uc($piece) eq $piece) {
907                                 # white piece
908                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
909                         } else {
910                                 # black piece
911                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
912                         }
913                 }
914         }
915
916         if ($black_check && $white_check) {
917                 return 'both';
918         } elsif ($black_check) {
919                 return 'black';
920         } elsif ($white_check) {
921                 return 'white';
922         } else {
923                 return 'none';
924         }
925 }
926
927 sub can_reach {
928         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
929         
930         # can't eat your own piece
931         my $dest_piece = substr($board->[$to_row], $to_col, 1);
932         if ($dest_piece ne '-') {
933                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
934         }
935
936         if (lc($piece) eq 'k') {
937                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
938         }
939         if (lc($piece) eq 'r') {
940                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
941
942                 # check that there's a clear passage
943                 if ($from_row == $to_row) {
944                         if ($from_col > $to_col) {
945                                 ($to_col, $from_col) = ($from_col, $to_col);
946                         }
947
948                         for my $c (($from_col+1)..($to_col-1)) {
949                                 my $middle_piece = substr($board->[$to_row], $c, 1);
950                                 return 0 if ($middle_piece ne '-');     
951                         }
952
953                         return 1;
954                 } else {
955                         if ($from_row > $to_row) {
956                                 ($to_row, $from_row) = ($from_row, $to_row);
957                         }
958
959                         for my $r (($from_row+1)..($to_row-1)) {
960                                 my $middle_piece = substr($board->[$r], $to_col, 1);
961                                 return 0 if ($middle_piece ne '-');     
962                         }
963
964                         return 1;
965                 }
966         }
967         if (lc($piece) eq 'b') {
968                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
969
970                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
971                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
972
973                 my $r = $from_row + $dr;
974                 my $c = $from_col + $dc;
975
976                 while ($r != $to_row) {
977                         my $middle_piece = substr($board->[$r], $c, 1);
978                         return 0 if ($middle_piece ne '-');
979                         
980                         $r += $dr;
981                         $c += $dc;
982                 }
983
984                 return 1;
985         }
986         if (lc($piece) eq 'n') {
987                 my $diff_r = abs($from_row - $to_row);
988                 my $diff_c = abs($from_col - $to_col);
989                 return 1 if ($diff_r == 2 && $diff_c == 1);
990                 return 1 if ($diff_r == 1 && $diff_c == 2);
991                 return 0;
992         }
993         if ($piece eq 'q') {
994                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
995                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
996         }
997         if ($piece eq 'Q') {
998                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
999                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1000         }
1001
1002         # TODO: en passant
1003         if ($piece eq 'p') {
1004                 # black pawn
1005                 if ($to_col == $from_col && $to_row == $from_row + 1) {
1006                         return ($dest_piece eq '-');
1007                 }
1008                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1009                         my $middle_piece = substr($board->[2], $to_col, 1);
1010                         return ($dest_piece eq '-' && $middle_piece eq '-');
1011                 }
1012                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1013                         return ($dest_piece ne '-');
1014                 }
1015                 return 0;
1016         }
1017         if ($piece eq 'P') {
1018                 # white pawn
1019                 if ($to_col == $from_col && $to_row == $from_row - 1) {
1020                         return ($dest_piece eq '-');
1021                 }
1022                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1023                         my $middle_piece = substr($board->[5], $to_col, 1);
1024                         return ($dest_piece eq '-' && $middle_piece eq '-');
1025                 }
1026                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1027                         return ($dest_piece ne '-');
1028                 }
1029                 return 0;
1030         }
1031         
1032         # unknown piece
1033         return 0;
1034 }
1035
1036 sub uciprint {
1037         my ($engine, $msg) = @_;
1038         print { $engine->{'write'} } "$msg\n";
1039         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1040 }
1041
1042 sub short_score {
1043         my ($info, $pos, $mpv, $invert) = @_;
1044
1045         $invert //= 0;
1046         if ($pos->{'toplay'} eq 'B') {
1047                 $invert = !$invert;
1048         }
1049
1050         if (defined($info->{'score_mate' . $mpv})) {
1051                 if ($invert) {
1052                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
1053                 } else {
1054                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1055                 }
1056         } else {
1057                 if (exists($info->{'score_cp' . $mpv})) {
1058                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1059                         if ($invert) {
1060                                 $score = -$score;
1061                         }
1062                         return sprintf "%+5.2f", $score;
1063                 }
1064         }
1065
1066         return undef;
1067 }
1068
1069 sub score_sort_key {
1070         my ($info, $pos, $mpv, $invert) = @_;
1071
1072         $invert //= 0;
1073         if ($pos->{'toplay'} eq 'B') {
1074                 $invert = !$invert;
1075         }
1076
1077         if (defined($info->{'score_mate' . $mpv})) {
1078                 if ($invert) {
1079                         return -(99999 - $info->{'score_mate' . $mpv});
1080                 } else {
1081                         return 99999 - $info->{'score_mate' . $mpv};
1082                 }
1083         } else {
1084                 if (exists($info->{'score_cp' . $mpv})) {
1085                         my $score = $info->{'score_cp' . $mpv};
1086                         if ($invert) {
1087                                 $score = -$score;
1088                         }
1089                         return $score;
1090                 }
1091         }
1092
1093         return undef;
1094 }
1095
1096 sub long_score {
1097         my ($info, $pos, $mpv) = @_;
1098
1099         if (defined($info->{'score_mate' . $mpv})) {
1100                 my $mate = $info->{'score_mate' . $mpv};
1101                 if ($pos->{'toplay'} eq 'B') {
1102                         $mate = -$mate;
1103                 }
1104                 if ($mate > 0) {
1105                         return sprintf "White mates in %u", $mate;
1106                 } else {
1107                         return sprintf "Black mates in %u", -$mate;
1108                 }
1109         } else {
1110                 if (exists($info->{'score_cp' . $mpv})) {
1111                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1112                         if ($pos->{'toplay'} eq 'B') {
1113                                 $score = -$score;
1114                         }
1115                         return sprintf "Score: %+5.2f", $score;
1116                 }
1117         }
1118
1119         return undef;
1120 }
1121
1122 my %book_cache = ();
1123 sub book_info {
1124         my ($fen, $board, $toplay) = @_;
1125
1126         if (exists($book_cache{$fen})) {
1127                 return $book_cache{$fen};
1128         }
1129
1130         my $ret = `./booklook $fen`;
1131         return "" if ($ret =~ /Not found/ || $ret eq '');
1132
1133         my @moves = ();
1134
1135         for my $m (split /\n/, $ret) {
1136                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1137
1138                 my $pmove;
1139                 if ($move eq '')  {
1140                         $pmove = '(current)';
1141                 } else {
1142                         ($pmove) = prettyprint_pv($board, $move);
1143                         $pmove .= $annotation;
1144                 }
1145
1146                 my $score;
1147                 if ($toplay eq 'W') {
1148                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1149                 } else {
1150                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1151                 }
1152                 my $n = $win + $draw + $lose;
1153                 
1154                 my $percent;
1155                 if ($n == 0) {
1156                         $percent = "     ";
1157                 } else {
1158                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1159                 }
1160
1161                 push @moves, [ $pmove, $n, $percent, $rating ];
1162         }
1163
1164         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1165         
1166         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1167         for my $m (@moves) {
1168                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1169         }
1170
1171         return $text;
1172 }
1173
1174 sub open_engine {
1175         my ($cmdline, $tag) = @_;
1176         my ($uciread, $uciwrite);
1177         my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1178
1179         my $engine = {
1180                 pid => $pid,
1181                 read => $uciread,
1182                 readbuf => '',
1183                 write => $uciwrite,
1184                 info => {},
1185                 ids => {},
1186                 tag => $tag,
1187         };
1188
1189         uciprint($engine, "uci");
1190
1191         # gobble the options
1192         while (<$uciread>) {
1193                 /uciok/ && last;
1194                 handle_uci($engine, $_);
1195         }
1196         
1197         return $engine;
1198 }
1199
1200 sub read_lines {
1201         my $engine = shift;
1202
1203         # 
1204         # Read until we've got a full line -- if the engine sends part of
1205         # a line and then stops we're pretty much hosed, but that should
1206         # never happen.
1207         #
1208         while ($engine->{'readbuf'} !~ /\n/) {
1209                 my $tmp;
1210                 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1211
1212                 if (!defined($ret)) {
1213                         next if ($!{EINTR});
1214                         die "error in reading from the UCI engine: $!";
1215                 } elsif ($ret == 0) {
1216                         die "EOF from UCI engine";
1217                 }
1218
1219                 $engine->{'readbuf'} .= $tmp;
1220         }
1221
1222         # Blah.
1223         my @lines = ();
1224         while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1225                 my $line = $1;
1226                 $line =~ tr/\r\n//d;
1227                 push @lines, $line;
1228         }
1229         return @lines;
1230 }
1231
1232 # Find all possible legal moves.
1233 sub calculate_refutation_moves {
1234         my $pos = shift;
1235         my $board = $pos->{'board'};
1236         my %refutation_moves = ();
1237         for my $col (0..7) {
1238                 for my $row (0..7) {
1239                         my $piece = substr($board->[$row], $col, 1);
1240
1241                         # Check that there's a piece of the right color on this square.
1242                         next if ($piece eq '-');
1243                         if ($pos->{'toplay'} eq 'W') {
1244                                 next if ($piece ne uc($piece));
1245                         } else {
1246                                 next if ($piece ne lc($piece));
1247                         }
1248
1249                         for my $to_col (0..7) {
1250                                 for my $to_row (0..7) {
1251                                         next if ($col == $to_col && $row == $to_row);
1252                                         next unless (can_reach($board, $piece, $row, $col, $to_row, $to_col));
1253
1254                                         my $promo = "";  # FIXME
1255                                         my $nb = make_move($board, $row, $col, $to_row, $to_col, $promo);
1256                                         my $check = in_check($nb);
1257                                         next if ($check eq 'both');
1258                                         if ($pos->{'toplay'} eq 'W') {
1259                                                 next if ($check eq 'white');
1260                                         } else {
1261                                                 next if ($check eq 'black');
1262                                         }
1263                                         my $move = move_to_uci_notation($row, $col, $to_row, $to_col, $promo);
1264                                         $refutation_moves{$move} = { depth => $second_engine_start_depth - 1, score_cp => 0, pv => '' };
1265                                 }
1266                         }
1267                 }
1268         }
1269         return %refutation_moves;
1270 }
1271
1272 sub give_new_move_to_second_engine {
1273         my $pos = shift;
1274                                 
1275         # Find the move that's been analyzed the shortest but is most promising.
1276         # Tie-break on UCI move representation.
1277         my $best_move = undef;
1278         for my $move (sort keys %refutation_moves) {
1279                 if (!defined($best_move)) {
1280                         $best_move = $move;
1281                         next;
1282                 }
1283                 my $best = $refutation_moves{$best_move};
1284                 my $this = $refutation_moves{$move};
1285
1286                 if ($this->{'depth'} < $best->{'depth'} ||
1287                     ($this->{'depth'} == $best->{'depth'} && $this->{'score_cp'} < $best->{'score_cp'})) {
1288                         $best_move = $move;
1289                         next;
1290                 }
1291         }
1292
1293         my $m = $refutation_moves{$best_move};
1294         ++$m->{'depth'};
1295         uciprint($engine2, "position fen " . $pos->{'fen'} . " moves " . $best_move);
1296         uciprint($engine2, "go depth " . $m->{'depth'});
1297         $move_calculating_second_engine = $best_move;
1298 }
1299
1300 sub col_letter_to_num {
1301         return ord(shift) - ord('a');
1302 }
1303
1304 sub row_letter_to_num {
1305         return 7 - (ord(shift) - ord('1'));
1306 }
1307
1308 sub move_to_uci_notation {
1309         my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1310         $promo //= "";
1311         return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);
1312 }