]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
d9ddd763f31274001b415fc60151646267155063
[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, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
347         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
348         return ($pretty, prettyprint_pv($nb, @pvs));
349 }
350
351 sub output {
352         #return;
353
354         return if (!defined($pos_calculating));
355
356         # Don't update too often.
357         my $age = Time::HiRes::tv_interval($latest_update);
358         if ($age < $update_max_interval) {
359                 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
360                 return;
361         }
362         
363         my $info = $engine->{'info'};
364         
365         #
366         # Some programs _always_ report MultiPV, even with only one PV.
367         # In this case, we simply use that data as if MultiPV was never
368         # specified.
369         #
370         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
371                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
372                         if (exists($info->{$key . '1'})) {
373                                 $info->{$key} = $info->{$key . '1'};
374                         }
375                 }
376         }
377         
378         #
379         # Check the PVs first. if they're invalid, just wait, as our data
380         # is most likely out of sync. This isn't a very good solution, as
381         # it can frequently miss stuff, but it's good enough for most users.
382         #
383         eval {
384                 my $dummy;
385                 if (exists($info->{'pv'})) {
386                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
387                 }
388         
389                 my $mpv = 1;
390                 while (exists($info->{'pv' . $mpv})) {
391                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
392                         ++$mpv;
393                 }
394         };
395         if ($@) {
396                 $engine->{'info'} = {};
397                 return;
398         }
399
400         output_screen();
401         output_json();
402         $latest_update = [Time::HiRes::gettimeofday];
403 }
404
405 sub output_screen {
406         my $info = $engine->{'info'};
407         my $id = $engine->{'id'};
408
409         my $text = 'Analysis';
410         if ($pos_calculating->{'last_move'} ne 'none') {
411                 if ($pos_calculating->{'toplay'} eq 'W') {
412                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
413                 } else {
414                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
415                 }
416                 if (exists($id->{'name'})) {
417                         $text .= ',';
418                 }
419         }
420
421         if (exists($id->{'name'})) {
422                 $text .= " by $id->{'name'}:\n\n";
423         } else {
424                 $text .= ":\n\n";
425         }
426
427         return unless (exists($pos_calculating->{'board'}));
428                 
429         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
430                 # multi-PV
431                 my $mpv = 1;
432                 while (exists($info->{'pv' . $mpv})) {
433                         $text .= sprintf "  PV%2u", $mpv;
434                         my $score = short_score($info, $pos_calculating, $mpv);
435                         $text .= "  ($score)" if (defined($score));
436
437                         my $tbhits = '';
438                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
439                                 if ($info->{'tbhits' . $mpv} == 1) {
440                                         $tbhits = ", 1 tbhit";
441                                 } else {
442                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
443                                 }
444                         }
445
446                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
447                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
448                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
449                         }
450
451                         $text .= ":\n";
452                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
453                         $text .= "\n";
454                         ++$mpv;
455                 }
456         } else {
457                 # single-PV
458                 my $score = long_score($info, $pos_calculating, '');
459                 $text .= "  $score\n" if defined($score);
460                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
461                 $text .=  "\n";
462
463                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
464                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
465                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
466                 }
467                 if (exists($info->{'seldepth'})) {
468                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
469                 }
470                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
471                         if ($info->{'tbhits'} == 1) {
472                                 $text .= ", one Syzygy hit";
473                         } else {
474                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
475                         }
476                 }
477                 $text .= "\n\n";
478         }
479
480         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
481
482         my @refutation_lines = ();
483         if (defined($engine2)) {
484                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
485                         my $info = $engine2->{'info'};
486                         last if (!exists($info->{'pv' . $mpv}));
487                         eval {
488                                 my $pv = $info->{'pv' . $mpv};
489
490                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
491                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
492                                 if (scalar @pretty_pv > 5) {
493                                         @pretty_pv = @pretty_pv[0..4];
494                                         push @pretty_pv, "...";
495                                 }
496                                 my $key = $pretty_move;
497                                 my $line = sprintf("  %-6s %6s %3s  %s",
498                                         $pretty_move,
499                                         short_score($info, $pos_calculating_second_engine, $mpv, 0),
500                                         "d" . $info->{'depth' . $mpv},
501                                         join(', ', @pretty_pv));
502                                 push @refutation_lines, [ $key, $line ];
503                         };
504                 }
505         }
506
507         if ($#refutation_lines >= 0) {
508                 $text .= "Shallow search of all legal moves:\n\n";
509                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
510                         $text .= $line->[1] . "\n";
511                 }
512                 $text .= "\n\n";        
513         }       
514
515         if ($last_text ne $text) {
516                 print "\e[H\e[2J"; # clear the screen
517                 print $text;
518                 $last_text = $text;
519         }
520 }
521
522 sub output_json {
523         my $info = $engine->{'info'};
524
525         my $json = {};
526         $json->{'position'} = $pos_calculating->to_json_hash();
527         $json->{'id'} = $engine->{'id'};
528         $json->{'score'} = long_score($info, $pos_calculating, '');
529
530         $json->{'nodes'} = $info->{'nodes'};
531         $json->{'nps'} = $info->{'nps'};
532         $json->{'depth'} = $info->{'depth'};
533         $json->{'tbhits'} = $info->{'tbhits'};
534         $json->{'seldepth'} = $info->{'seldepth'};
535
536         # single-PV only for now
537         $json->{'pv_uci'} = $info->{'pv'};
538         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
539
540         my %refutation_lines = ();
541         my @refutation_lines = ();
542         if (defined($engine2)) {
543                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
544                         my $info = $engine2->{'info'};
545                         my $pretty_move = "";
546                         my @pretty_pv = ();
547                         last if (!exists($info->{'pv' . $mpv}));
548
549                         eval {
550                                 my $pv = $info->{'pv' . $mpv};
551                                 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
552                                 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
553                                 $refutation_lines{$pv->[0]} = {
554                                         sort_key => $pretty_move,
555                                         depth => $info->{'depth' . $mpv},
556                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
557                                         pretty_score => short_score($info, $pos_calculating, $mpv, 0),
558                                         pretty_move => $pretty_move,
559                                         pv_pretty => \@pretty_pv,
560                                 };
561                                 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
562                         };
563                 }
564         }
565         $json->{'refutation_lines'} = \%refutation_lines;
566
567         open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
568                 or return;
569         print $fh JSON::XS::encode_json($json);
570         close $fh;
571         rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
572 }
573
574 sub uciprint {
575         my ($engine, $msg) = @_;
576         $engine->print($msg);
577         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
578 }
579
580 sub short_score {
581         my ($info, $pos, $mpv, $invert) = @_;
582
583         $invert //= 0;
584         if ($pos->{'toplay'} eq 'B') {
585                 $invert = !$invert;
586         }
587
588         if (defined($info->{'score_mate' . $mpv})) {
589                 if ($invert) {
590                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
591                 } else {
592                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
593                 }
594         } else {
595                 if (exists($info->{'score_cp' . $mpv})) {
596                         my $score = $info->{'score_cp' . $mpv} * 0.01;
597                         if ($score == 0) {
598                                 return " 0.00";
599                         }
600                         if ($invert) {
601                                 $score = -$score;
602                         }
603                         return sprintf "%+5.2f", $score;
604                 }
605         }
606
607         return undef;
608 }
609
610 sub score_sort_key {
611         my ($info, $pos, $mpv, $invert) = @_;
612
613         if (defined($info->{'score_mate' . $mpv})) {
614                 if ($invert) {
615                         return 99999 - $info->{'score_mate' . $mpv};
616                 } else {
617                         return -(99999 - $info->{'score_mate' . $mpv});
618                 }
619         } else {
620                 if (exists($info->{'score_cp' . $mpv})) {
621                         my $score = $info->{'score_cp' . $mpv};
622                         if ($invert) {
623                                 $score = -$score;
624                         }
625                         return $score;
626                 }
627         }
628
629         return undef;
630 }
631
632 sub long_score {
633         my ($info, $pos, $mpv) = @_;
634
635         if (defined($info->{'score_mate' . $mpv})) {
636                 my $mate = $info->{'score_mate' . $mpv};
637                 if ($pos->{'toplay'} eq 'B') {
638                         $mate = -$mate;
639                 }
640                 if ($mate > 0) {
641                         return sprintf "White mates in %u", $mate;
642                 } else {
643                         return sprintf "Black mates in %u", -$mate;
644                 }
645         } else {
646                 if (exists($info->{'score_cp' . $mpv})) {
647                         my $score = $info->{'score_cp' . $mpv} * 0.01;
648                         if ($score == 0) {
649                                 return "Score:  0.00";
650                         }
651                         if ($pos->{'toplay'} eq 'B') {
652                                 $score = -$score;
653                         }
654                         return sprintf "Score: %+5.2f", $score;
655                 }
656         }
657
658         return undef;
659 }
660
661 my %book_cache = ();
662 sub book_info {
663         my ($fen, $board, $toplay) = @_;
664
665         if (exists($book_cache{$fen})) {
666                 return $book_cache{$fen};
667         }
668
669         my $ret = `./booklook $fen`;
670         return "" if ($ret =~ /Not found/ || $ret eq '');
671
672         my @moves = ();
673
674         for my $m (split /\n/, $ret) {
675                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
676
677                 my $pmove;
678                 if ($move eq '')  {
679                         $pmove = '(current)';
680                 } else {
681                         ($pmove) = prettyprint_pv($board, $move);
682                         $pmove .= $annotation;
683                 }
684
685                 my $score;
686                 if ($toplay eq 'W') {
687                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
688                 } else {
689                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
690                 }
691                 my $n = $win + $draw + $lose;
692                 
693                 my $percent;
694                 if ($n == 0) {
695                         $percent = "     ";
696                 } else {
697                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
698                 }
699
700                 push @moves, [ $pmove, $n, $percent, $rating ];
701         }
702
703         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
704         
705         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
706         for my $m (@moves) {
707                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
708         }
709
710         return $text;
711 }
712
713 sub open_engine {
714         my ($cmdline, $tag) = @_;
715         return undef if (!defined($cmdline));
716         my $engine = Engine->open($cmdline, $tag);
717
718         uciprint($engine, "uci");
719
720         # gobble the options
721         my $seen_uciok = 0;
722         while (!$seen_uciok) {
723                 for my $line ($engine->read_lines()) {
724                         if ($line =~ /uciok/) {
725                                 $seen_uciok = 1;
726                         }
727                         handle_uci($engine, $line);
728                 }
729         }
730         
731         return $engine;
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 }