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