]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Small refactoring.
[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                 handle_fics($line);
117                 $sleep = 0;
118         }
119         
120         # any fun on the UCI channel?
121         if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
122                 my @lines = $engine->read_lines();
123                 for my $line (@lines) {
124                         next if $line =~ /(upper|lower)bound/;
125                         handle_uci($engine, $line, 1);
126                 }
127                 $sleep = 0;
128
129                 output();
130         }
131         if (defined($engine2) && $nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
132                 my @lines = $engine2->read_lines();
133                 for my $line (@lines) {
134                         next if $line =~ /(upper|lower)bound/;
135                         handle_uci($engine2, $line, 0);
136                 }
137                 $sleep = 0;
138
139                 output();
140         }
141
142         sleep $sleep;
143 }
144
145 sub handle_uci {
146         my ($engine, $line, $primary) = @_;
147
148         chomp $line;
149         $line =~ tr/\r//d;
150         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
151         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
152         if ($line =~ /^info/) {
153                 my (@infos) = split / /, $line;
154                 shift @infos;
155
156                 parse_infos($engine, @infos);
157         }
158         if ($line =~ /^id/) {
159                 my (@ids) = split / /, $line;
160                 shift @ids;
161
162                 parse_ids($engine, @ids);
163         }
164         if ($line =~ /^bestmove/) {
165                 if ($primary) {
166                         return if (!$uci_assume_full_compliance);
167                         if (defined($pos_waiting)) {
168                                 uciprint($engine, "position fen " . $pos_waiting->fen());
169                                 uciprint($engine, "go infinite");
170
171                                 $pos_calculating = $pos_waiting;
172                                 $pos_waiting = undef;
173                         }
174                 } else {
175                         $engine2->{'info'} = {};
176                         my $pos = $pos_waiting // $pos_calculating;
177                         uciprint($engine2, "position fen " . $pos->fen());
178                         uciprint($engine2, "go infinite");
179                         $pos_calculating_second_engine = $pos;
180                 }
181         }
182 }
183
184 sub handle_fics {
185         my $line = shift;
186         if ($line =~ /^<12> /) {
187                 my $pos = Position->new($line);
188                 
189                 # if this is already in the queue, ignore it
190                 next if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
191
192                 # if we're already chewing on this and there's nothing else in the queue,
193                 # also ignore it
194                 next if (!defined($pos_waiting) && defined($pos_calculating) &&
195                          $pos->fen() eq $pos_calculating->fen());
196
197                 # if we're already thinking on something, stop and wait for the engine
198                 # to approve
199                 if (defined($pos_calculating)) {
200                         if (!defined($pos_waiting)) {
201                                 uciprint($engine, "stop");
202                         }
203                         if ($uci_assume_full_compliance) {
204                                 $pos_waiting = $pos;
205                         } else {
206                                 uciprint($engine, "position fen " . $pos->fen());
207                                 uciprint($engine, "go infinite");
208                                 $pos_calculating = $pos;
209                         }
210                 } else {
211                         # it's wrong just to give the FEN (the move history is useful,
212                         # and per the UCI spec, we should really have sent "ucinewgame"),
213                         # but it's easier
214                         uciprint($engine, "position fen " . $pos->fen());
215                         uciprint($engine, "go infinite");
216                         $pos_calculating = $pos;
217                 }
218
219                 if (defined($engine2)) {
220                         if (defined($pos_calculating_second_engine)) {
221                                 uciprint($engine2, "stop");
222                         } else {
223                                 uciprint($engine2, "position fen " . $pos->fen());
224                                 uciprint($engine2, "go infinite");
225                                 $pos_calculating_second_engine = $pos;
226                         }
227                         $engine2->{'info'} = {};
228                 }
229
230                 $engine->{'info'} = {};
231                 $last_move = time;
232
233                 # 
234                 # Output a command every move to note that we're
235                 # still paying attention -- this is a good tradeoff,
236                 # since if no move has happened in the last half
237                 # hour, the analysis/relay has most likely stopped
238                 # and we should stop hogging server resources.
239                 #
240                 $t->cmd("date");
241         }
242         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
243                 my ($who, $msg) = ($1, $2);
244
245                 next if (grep { $_ eq $who } (@masters) == 0);
246
247                 if ($msg =~ /^fics (.*?)$/) {
248                         $t->cmd("tell $who Executing '$1' on FICS.");
249                         $t->cmd($1);
250                 } elsif ($msg =~ /^uci (.*?)$/) {
251                         $t->cmd("tell $who Sending '$1' to the engine.");
252                         print { $engine->{'write'} } "$1\n";
253                 } else {
254                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
255                 }
256         }
257         #print "FICS: [$line]\n";
258 }
259
260 sub parse_infos {
261         my ($engine, @x) = @_;
262         my $mpv = '';
263
264         my $info = $engine->{'info'};
265
266         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
267         for my $i (0..$#x - 1) {
268                 if ($x[$i] =~ 'multipv') {
269                         $mpv = $x[$i + 1];
270                         next;
271                 }
272         }
273
274         while (scalar @x > 0) {
275                 if ($x[0] =~ 'multipv') {
276                         # Dealt with above
277                         shift @x;
278                         shift @x;
279                         next;
280                 }
281                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
282                         my $key = shift @x;
283                         my $value = shift @x;
284                         $info->{$key} = $value;
285                         next;
286                 }
287                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
288                         my $key = shift @x;
289                         my $value = shift @x;
290                         $info->{$key . $mpv} = $value;
291                         next;
292                 }
293                 if ($x[0] eq 'score') {
294                         shift @x;
295
296                         delete $info->{'score_cp' . $mpv};
297                         delete $info->{'score_mate' . $mpv};
298
299                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
300                                 if ($x[0] eq 'cp') {
301                                         shift @x;
302                                         $info->{'score_cp' . $mpv} = shift @x;
303                                 } elsif ($x[0] eq 'mate') {
304                                         shift @x;
305                                         $info->{'score_mate' . $mpv} = shift @x;
306                                 } else {
307                                         shift @x;
308                                 }
309                         }
310                         next;
311                 }
312                 if ($x[0] eq 'pv') {
313                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
314                         last;
315                 }
316                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
317                         last;
318                 }
319
320                 #print "unknown info '$x[0]', trying to recover...\n";
321                 #shift @x;
322                 die "Unknown info '" . join(',', @x) . "'";
323
324         }
325 }
326
327 sub parse_ids {
328         my ($engine, @x) = @_;
329
330         while (scalar @x > 0) {
331                 if ($x[0] =~ /^(name|author)$/) {
332                         my $key = shift @x;
333                         my $value = join(' ', @x);
334                         $engine->{'id'}{$key} = $value;
335                         last;
336                 }
337
338                 # unknown
339                 shift @x;
340         }
341 }
342
343 sub prettyprint_pv {
344         my ($board, @pvs) = @_;
345
346         if (scalar @pvs == 0 || !defined($pvs[0])) {
347                 return ();
348         }
349
350         my $pv = shift @pvs;
351         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
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
747 sub parse_uci_move {
748         my $move = shift;
749         my $from_col = col_letter_to_num(substr($move, 0, 1));
750         my $from_row = row_letter_to_num(substr($move, 1, 1));
751         my $to_col   = col_letter_to_num(substr($move, 2, 1));
752         my $to_row   = row_letter_to_num(substr($move, 3, 1));
753         my $promo    = substr($move, 4, 1);
754         return ($from_col, $from_row, $to_col, $to_row, $promo);
755 }