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