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