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