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