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