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