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