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