]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
4459015e7c8510de4bf79044480c5e4b88ad4214
[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 AnyEvent;
13 use AnyEvent::Handle;
14 use AnyEvent::HTTP;
15 use Chess::PGN::Parse;
16 use EV;
17 use Net::Telnet;
18 use FileHandle;
19 use IPC::Open2;
20 use Time::HiRes;
21 use JSON::XS;
22 require 'Position.pm';
23 require 'Engine.pm';
24 require 'config.pm';
25 use strict;
26 use warnings;
27 no warnings qw(once);
28
29 # Program starts here
30 $SIG{ALRM} = sub { output(); };
31 my $latest_update = undef;
32 my $http_timer = undef;
33
34 $| = 1;
35
36 open(FICSLOG, ">ficslog.txt")
37         or die "ficslog.txt: $!";
38 print FICSLOG "Log starting.\n";
39 select(FICSLOG);
40 $| = 1;
41
42 open(UCILOG, ">ucilog.txt")
43         or die "ucilog.txt: $!";
44 print UCILOG "Log starting.\n";
45 select(UCILOG);
46 $| = 1;
47 select(STDOUT);
48
49 # open the chess engine
50 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
51 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
52 my $last_move;
53 my $last_text = '';
54 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
55
56 uciprint($engine, "setoption name UCI_AnalyseMode value true");
57 while (my ($key, $value) = each %remoteglotconf::engine_config) {
58         uciprint($engine, "setoption name $key value $value");
59 }
60 uciprint($engine, "ucinewgame");
61
62 if (defined($engine2)) {
63         uciprint($engine2, "setoption name UCI_AnalyseMode value true");
64         while (my ($key, $value) = each %remoteglotconf::engine2_config) {
65                 uciprint($engine2, "setoption name $key value $value");
66         }
67         uciprint($engine2, "setoption name MultiPV value 500");
68         uciprint($engine2, "ucinewgame");
69 }
70
71 print "Chess engine ready.\n";
72
73 # now talk to FICS
74 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
75 $t->input_log(\*FICSLOG);
76 $t->open($remoteglotconf::server);
77 $t->print($remoteglotconf::nick);
78 $t->waitfor('/Press return to enter the server/');
79 $t->cmd("");
80
81 # set some options
82 $t->cmd("set shout 0");
83 $t->cmd("set seek 0");
84 $t->cmd("set style 12");
85 $t->cmd("observe $remoteglotconf::target");
86 print "FICS ready.\n";
87
88 my $ev1 = AnyEvent->io(
89         fh => fileno($t),
90         poll => 'r',
91         cb => sub {    # what callback to execute
92                 while (1) {
93                         my $line = $t->getline(Timeout => 0, errmode => 'return');
94                         return if (!defined($line));
95
96                         chomp $line;
97                         $line =~ tr/\r//d;
98                         handle_fics($line);
99                 }
100         }
101 );
102 # Engine events have already been set up by Engine.pm.
103 EV::run;
104
105 sub handle_uci {
106         my ($engine, $line, $primary) = @_;
107
108         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
109         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
110         if ($line =~ /^info/) {
111                 my (@infos) = split / /, $line;
112                 shift @infos;
113
114                 parse_infos($engine, @infos);
115         }
116         if ($line =~ /^id/) {
117                 my (@ids) = split / /, $line;
118                 shift @ids;
119
120                 parse_ids($engine, @ids);
121         }
122         if ($line =~ /^bestmove/) {
123                 if ($primary) {
124                         return if (!$remoteglotconf::uci_assume_full_compliance);
125                         if (defined($pos_waiting)) {
126                                 uciprint($engine, "position fen " . $pos_waiting->fen());
127                                 uciprint($engine, "go infinite");
128
129                                 $pos_calculating = $pos_waiting;
130                                 $pos_waiting = undef;
131                         }
132                 } else {
133                         $engine2->{'info'} = {};
134                         my $pos = $pos_waiting // $pos_calculating;
135                         uciprint($engine2, "position fen " . $pos->fen());
136                         uciprint($engine2, "go infinite");
137                         $pos_calculating_second_engine = $pos;
138                 }
139         }
140         output();
141 }
142
143 sub handle_fics {
144         my $line = shift;
145         if ($line =~ /^<12> /) {
146                 handle_position(Position->new($line));
147         }
148         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
149                 my ($who, $msg) = ($1, $2);
150
151                 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
152
153                 if ($msg =~ /^fics (.*?)$/) {
154                         $t->cmd("tell $who Executing '$1' on FICS.");
155                         $t->cmd($1);
156                 } elsif ($msg =~ /^uci (.*?)$/) {
157                         $t->cmd("tell $who Sending '$1' to the engine.");
158                         print { $engine->{'write'} } "$1\n";
159                 } elsif ($msg =~ /^pgn (.*?)$/) {
160                         my $url = $1;
161                         $t->cmd("tell $who Starting to poll '$url'.");
162                         AnyEvent::HTTP::http_get($url, sub {
163                                 handle_pgn(@_, $url);
164                         });
165                 } elsif ($msg =~ /^stoppgn$/) {
166                         $t->cmd("tell $who Stopping poll.");
167                         $http_timer = undef;
168                 } elsif ($msg =~ /^quit$/) {
169                         $t->cmd("tell $who Bye bye.");
170                         exit;
171                 } else {
172                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
173                 }
174         }
175         #print "FICS: [$line]\n";
176 }
177
178 sub handle_pgn {
179         my ($body, $header, $url) = @_;
180         my $pgn = Chess::PGN::Parse->new(undef, $body);
181         if (!defined($pgn) || !$pgn->read_game()) {
182                 warn "Error in parsing PGN from $url\n";
183         } else {
184                 $pgn->quick_parse_game;
185                 my $pos = Position->start_pos($pgn->white, $pgn->black);
186                 my $moves = $pgn->moves;
187                 my @uci_moves = ();
188                 for my $move (@$moves) {
189                         my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
190                         push @uci_moves, Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
191                         $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
192                 }
193                 $pos->{'history'} = \@uci_moves;
194                 $pos->{'pretty_history'} = $moves;
195                 handle_position($pos);
196         }
197         
198         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
199                 AnyEvent::HTTP::http_get($url, sub {
200                         handle_pgn(@_, $url);
201                 });
202         });
203 }
204
205 sub handle_position {
206         my ($pos) = @_;
207                 
208         # if this is already in the queue, ignore it
209         return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
210
211         # if we're already chewing on this and there's nothing else in the queue,
212         # also ignore it
213         return if (!defined($pos_waiting) && defined($pos_calculating) &&
214                  $pos->fen() eq $pos_calculating->fen());
215
216         # if we're already thinking on something, stop and wait for the engine
217         # to approve
218         if (defined($pos_calculating)) {
219                 if (!defined($pos_waiting)) {
220                         uciprint($engine, "stop");
221                 }
222                 if ($remoteglotconf::uci_assume_full_compliance) {
223                         $pos_waiting = $pos;
224                 } else {
225                         uciprint($engine, "position fen " . $pos->fen());
226                         uciprint($engine, "go infinite");
227                         $pos_calculating = $pos;
228                 }
229         } else {
230                 # it's wrong just to give the FEN (the move history is useful,
231                 # and per the UCI spec, we should really have sent "ucinewgame"),
232                 # but it's easier
233                 uciprint($engine, "position fen " . $pos->fen());
234                 uciprint($engine, "go infinite");
235                 $pos_calculating = $pos;
236         }
237
238         if (defined($engine2)) {
239                 if (defined($pos_calculating_second_engine)) {
240                         uciprint($engine2, "stop");
241                 } else {
242                         uciprint($engine2, "position fen " . $pos->fen());
243                         uciprint($engine2, "go infinite");
244                         $pos_calculating_second_engine = $pos;
245                 }
246                 $engine2->{'info'} = {};
247         }
248
249         $engine->{'info'} = {};
250         $last_move = time;
251
252         # 
253         # Output a command every move to note that we're
254         # still paying attention -- this is a good tradeoff,
255         # since if no move has happened in the last half
256         # hour, the analysis/relay has most likely stopped
257         # and we should stop hogging server resources.
258         #
259         $t->cmd("date");
260 }
261
262 sub parse_infos {
263         my ($engine, @x) = @_;
264         my $mpv = '';
265
266         my $info = $engine->{'info'};
267
268         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
269         for my $i (0..$#x - 1) {
270                 if ($x[$i] eq 'multipv') {
271                         $mpv = $x[$i + 1];
272                         next;
273                 }
274         }
275
276         while (scalar @x > 0) {
277                 if ($x[0] eq 'multipv') {
278                         # Dealt with above
279                         shift @x;
280                         shift @x;
281                         next;
282                 }
283                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
284                         my $key = shift @x;
285                         my $value = shift @x;
286                         $info->{$key} = $value;
287                         next;
288                 }
289                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
290                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
291                     $x[0] eq 'tbhits') {
292                         my $key = shift @x;
293                         my $value = shift @x;
294                         $info->{$key . $mpv} = $value;
295                         next;
296                 }
297                 if ($x[0] eq 'score') {
298                         shift @x;
299
300                         delete $info->{'score_cp' . $mpv};
301                         delete $info->{'score_mate' . $mpv};
302
303                         while ($x[0] eq 'cp' || $x[0] eq 'mate' || $x[0] eq 'lowerbound' || $x[0] eq 'upperbound') {
304                                 if ($x[0] eq 'cp') {
305                                         shift @x;
306                                         $info->{'score_cp' . $mpv} = shift @x;
307                                 } elsif ($x[0] eq 'mate') {
308                                         shift @x;
309                                         $info->{'score_mate' . $mpv} = shift @x;
310                                 } else {
311                                         shift @x;
312                                 }
313                         }
314                         next;
315                 }
316                 if ($x[0] eq 'pv') {
317                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
318                         last;
319                 }
320                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
321                         last;
322                 }
323
324                 #print "unknown info '$x[0]', trying to recover...\n";
325                 #shift @x;
326                 die "Unknown info '" . join(',', @x) . "'";
327
328         }
329 }
330
331 sub parse_ids {
332         my ($engine, @x) = @_;
333
334         while (scalar @x > 0) {
335                 if ($x[0] =~ /^(name|author)$/) {
336                         my $key = shift @x;
337                         my $value = join(' ', @x);
338                         $engine->{'id'}{$key} = $value;
339                         last;
340                 }
341
342                 # unknown
343                 shift @x;
344         }
345 }
346
347 sub prettyprint_pv_no_cache {
348         my ($board, @pvs) = @_;
349
350         if (scalar @pvs == 0 || !defined($pvs[0])) {
351                 return ();
352         }
353
354         my $pv = shift @pvs;
355         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
356         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
357         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
358 }
359
360 sub prettyprint_pv {
361         my ($pos, @pvs) = @_;
362
363         my $cachekey = join('', @pvs);
364         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
365                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
366         } else {
367                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
368                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
369                 return @res;
370         }
371 }
372
373 sub output {
374         #return;
375
376         return if (!defined($pos_calculating));
377
378         # Don't update too often.
379         my $age = Time::HiRes::tv_interval($latest_update);
380         if ($age < $remoteglotconf::update_max_interval) {
381                 Time::HiRes::alarm($remoteglotconf::update_max_interval + 0.01 - $age);
382                 return;
383         }
384         
385         my $info = $engine->{'info'};
386         
387         #
388         # Some programs _always_ report MultiPV, even with only one PV.
389         # In this case, we simply use that data as if MultiPV was never
390         # specified.
391         #
392         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
393                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
394                         if (exists($info->{$key . '1'})) {
395                                 $info->{$key} = $info->{$key . '1'};
396                         }
397                 }
398         }
399         
400         #
401         # Check the PVs first. if they're invalid, just wait, as our data
402         # is most likely out of sync. This isn't a very good solution, as
403         # it can frequently miss stuff, but it's good enough for most users.
404         #
405         eval {
406                 my $dummy;
407                 if (exists($info->{'pv'})) {
408                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
409                 }
410         
411                 my $mpv = 1;
412                 while (exists($info->{'pv' . $mpv})) {
413                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
414                         ++$mpv;
415                 }
416         };
417         if ($@) {
418                 $engine->{'info'} = {};
419                 return;
420         }
421
422         output_screen();
423         output_json();
424         $latest_update = [Time::HiRes::gettimeofday];
425 }
426
427 sub output_screen {
428         my $info = $engine->{'info'};
429         my $id = $engine->{'id'};
430
431         my $text = 'Analysis';
432         if ($pos_calculating->{'last_move'} ne 'none') {
433                 if ($pos_calculating->{'toplay'} eq 'W') {
434                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
435                 } else {
436                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
437                 }
438                 if (exists($id->{'name'})) {
439                         $text .= ',';
440                 }
441         }
442
443         if (exists($id->{'name'})) {
444                 $text .= " by $id->{'name'}:\n\n";
445         } else {
446                 $text .= ":\n\n";
447         }
448
449         return unless (exists($pos_calculating->{'board'}));
450                 
451         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
452                 # multi-PV
453                 my $mpv = 1;
454                 while (exists($info->{'pv' . $mpv})) {
455                         $text .= sprintf "  PV%2u", $mpv;
456                         my $score = short_score($info, $pos_calculating, $mpv);
457                         $text .= "  ($score)" if (defined($score));
458
459                         my $tbhits = '';
460                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
461                                 if ($info->{'tbhits' . $mpv} == 1) {
462                                         $tbhits = ", 1 tbhit";
463                                 } else {
464                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
465                                 }
466                         }
467
468                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
469                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
470                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
471                         }
472
473                         $text .= ":\n";
474                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
475                         $text .= "\n";
476                         ++$mpv;
477                 }
478         } else {
479                 # single-PV
480                 my $score = long_score($info, $pos_calculating, '');
481                 $text .= "  $score\n" if defined($score);
482                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
483                 $text .=  "\n";
484
485                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
486                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
487                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
488                 }
489                 if (exists($info->{'seldepth'})) {
490                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
491                 }
492                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
493                         if ($info->{'tbhits'} == 1) {
494                                 $text .= ", one Syzygy hit";
495                         } else {
496                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
497                         }
498                 }
499                 $text .= "\n\n";
500         }
501
502         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
503
504         my @refutation_lines = ();
505         if (defined($engine2)) {
506                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
507                         my $info = $engine2->{'info'};
508                         last if (!exists($info->{'pv' . $mpv}));
509                         eval {
510                                 my $pv = $info->{'pv' . $mpv};
511
512                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
513                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
514                                 if (scalar @pretty_pv > 5) {
515                                         @pretty_pv = @pretty_pv[0..4];
516                                         push @pretty_pv, "...";
517                                 }
518                                 my $key = $pretty_move;
519                                 my $line = sprintf("  %-6s %6s %3s  %s",
520                                         $pretty_move,
521                                         short_score($info, $pos_calculating_second_engine, $mpv, 0),
522                                         "d" . $info->{'depth' . $mpv},
523                                         join(', ', @pretty_pv));
524                                 push @refutation_lines, [ $key, $line ];
525                         };
526                 }
527         }
528
529         if ($#refutation_lines >= 0) {
530                 $text .= "Shallow search of all legal moves:\n\n";
531                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
532                         $text .= $line->[1] . "\n";
533                 }
534                 $text .= "\n\n";        
535         }       
536
537         if ($last_text ne $text) {
538                 print "\e[H\e[2J"; # clear the screen
539                 print $text;
540                 $last_text = $text;
541         }
542 }
543
544 sub output_json {
545         my $info = $engine->{'info'};
546
547         my $json = {};
548         $json->{'position'} = $pos_calculating->to_json_hash();
549         $json->{'id'} = $engine->{'id'};
550         $json->{'score'} = long_score($info, $pos_calculating, '');
551
552         $json->{'nodes'} = $info->{'nodes'};
553         $json->{'nps'} = $info->{'nps'};
554         $json->{'depth'} = $info->{'depth'};
555         $json->{'tbhits'} = $info->{'tbhits'};
556         $json->{'seldepth'} = $info->{'seldepth'};
557
558         # single-PV only for now
559         $json->{'pv_uci'} = $info->{'pv'};
560         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
561
562         my %refutation_lines = ();
563         my @refutation_lines = ();
564         if (defined($engine2)) {
565                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
566                         my $info = $engine2->{'info'};
567                         my $pretty_move = "";
568                         my @pretty_pv = ();
569                         last if (!exists($info->{'pv' . $mpv}));
570
571                         eval {
572                                 my $pv = $info->{'pv' . $mpv};
573                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
574                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
575                                 $refutation_lines{$pv->[0]} = {
576                                         sort_key => $pretty_move,
577                                         depth => $info->{'depth' . $mpv},
578                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
579                                         pretty_score => short_score($info, $pos_calculating, $mpv, 0),
580                                         pretty_move => $pretty_move,
581                                         pv_pretty => \@pretty_pv,
582                                 };
583                                 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
584                         };
585                 }
586         }
587         $json->{'refutation_lines'} = \%refutation_lines;
588
589         open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
590                 or return;
591         print $fh JSON::XS::encode_json($json);
592         close $fh;
593         rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
594 }
595
596 sub uciprint {
597         my ($engine, $msg) = @_;
598         $engine->print($msg);
599         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
600 }
601
602 sub short_score {
603         my ($info, $pos, $mpv, $invert) = @_;
604
605         $invert //= 0;
606         if ($pos->{'toplay'} eq 'B') {
607                 $invert = !$invert;
608         }
609
610         if (defined($info->{'score_mate' . $mpv})) {
611                 if ($invert) {
612                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
613                 } else {
614                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
615                 }
616         } else {
617                 if (exists($info->{'score_cp' . $mpv})) {
618                         my $score = $info->{'score_cp' . $mpv} * 0.01;
619                         if ($score == 0) {
620                                 return " 0.00";
621                         }
622                         if ($invert) {
623                                 $score = -$score;
624                         }
625                         return sprintf "%+5.2f", $score;
626                 }
627         }
628
629         return undef;
630 }
631
632 sub score_sort_key {
633         my ($info, $pos, $mpv, $invert) = @_;
634
635         if (defined($info->{'score_mate' . $mpv})) {
636                 if ($invert) {
637                         return 99999 - $info->{'score_mate' . $mpv};
638                 } else {
639                         return -(99999 - $info->{'score_mate' . $mpv});
640                 }
641         } else {
642                 if (exists($info->{'score_cp' . $mpv})) {
643                         my $score = $info->{'score_cp' . $mpv};
644                         if ($invert) {
645                                 $score = -$score;
646                         }
647                         return $score;
648                 }
649         }
650
651         return undef;
652 }
653
654 sub long_score {
655         my ($info, $pos, $mpv) = @_;
656
657         if (defined($info->{'score_mate' . $mpv})) {
658                 my $mate = $info->{'score_mate' . $mpv};
659                 if ($pos->{'toplay'} eq 'B') {
660                         $mate = -$mate;
661                 }
662                 if ($mate > 0) {
663                         return sprintf "White mates in %u", $mate;
664                 } else {
665                         return sprintf "Black mates in %u", -$mate;
666                 }
667         } else {
668                 if (exists($info->{'score_cp' . $mpv})) {
669                         my $score = $info->{'score_cp' . $mpv} * 0.01;
670                         if ($score == 0) {
671                                 return "Score:  0.00";
672                         }
673                         if ($pos->{'toplay'} eq 'B') {
674                                 $score = -$score;
675                         }
676                         return sprintf "Score: %+5.2f", $score;
677                 }
678         }
679
680         return undef;
681 }
682
683 my %book_cache = ();
684 sub book_info {
685         my ($fen, $board, $toplay) = @_;
686
687         if (exists($book_cache{$fen})) {
688                 return $book_cache{$fen};
689         }
690
691         my $ret = `./booklook $fen`;
692         return "" if ($ret =~ /Not found/ || $ret eq '');
693
694         my @moves = ();
695
696         for my $m (split /\n/, $ret) {
697                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
698
699                 my $pmove;
700                 if ($move eq '')  {
701                         $pmove = '(current)';
702                 } else {
703                         ($pmove) = prettyprint_pv_no_cache($board, $move);
704                         $pmove .= $annotation;
705                 }
706
707                 my $score;
708                 if ($toplay eq 'W') {
709                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
710                 } else {
711                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
712                 }
713                 my $n = $win + $draw + $lose;
714                 
715                 my $percent;
716                 if ($n == 0) {
717                         $percent = "     ";
718                 } else {
719                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
720                 }
721
722                 push @moves, [ $pmove, $n, $percent, $rating ];
723         }
724
725         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
726         
727         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
728         for my $m (@moves) {
729                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
730         }
731
732         return $text;
733 }
734
735 sub open_engine {
736         my ($cmdline, $tag, $cb) = @_;
737         return undef if (!defined($cmdline));
738         return Engine->open($cmdline, $tag, $cb);
739 }
740
741 sub col_letter_to_num {
742         return ord(shift) - ord('a');
743 }
744
745 sub row_letter_to_num {
746         return 7 - (ord(shift) - ord('1'));
747 }
748
749 sub parse_uci_move {
750         my $move = shift;
751         my $from_col = col_letter_to_num(substr($move, 0, 1));
752         my $from_row = row_letter_to_num(substr($move, 1, 1));
753         my $to_col   = col_letter_to_num(substr($move, 2, 1));
754         my $to_row   = row_letter_to_num(substr($move, 3, 1));
755         my $promo    = substr($move, 4, 1);
756         return ($from_col, $from_row, $to_col, $to_row, $promo);
757 }