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