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