]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Tiny error message cleanup.
[remoteglot] / remoteglot.pl
1 #! /usr/bin/perl
2
3 #
4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 #              analysis, or for live analysis of relayed games. (Do not use for
6 #              cheating! Cheating is bad for your karma, and your abuser flag.)
7 #
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
10 #
11
12 use AnyEvent;
13 use AnyEvent::Handle;
14 use AnyEvent::HTTP;
15 use Chess::PGN::Parse;
16 use EV;
17 use Net::Telnet;
18 use FileHandle;
19 use IPC::Open2;
20 use Time::HiRes;
21 use JSON::XS;
22 use URI::Escape;
23 require 'Position.pm';
24 require 'Engine.pm';
25 require 'config.pm';
26 use strict;
27 use warnings;
28 no warnings qw(once);
29
30 # Program starts here
31 $SIG{ALRM} = sub { output(); };
32 my $latest_update = undef;
33 my $http_timer = undef;
34 my $tb_retry_timer = undef;
35 my %tb_cache = ();
36 my $tb_lookup_running = 0;
37
38 $| = 1;
39
40 open(FICSLOG, ">ficslog.txt")
41         or die "ficslog.txt: $!";
42 print FICSLOG "Log starting.\n";
43 select(FICSLOG);
44 $| = 1;
45
46 open(UCILOG, ">ucilog.txt")
47         or die "ucilog.txt: $!";
48 print UCILOG "Log starting.\n";
49 select(UCILOG);
50 $| = 1;
51
52 open(TBLOG, ">tblog.txt")
53         or die "tblog.txt: $!";
54 print TBLOG "Log starting.\n";
55 select(TBLOG);
56 $| = 1;
57
58 select(STDOUT);
59
60 # open the chess engine
61 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
62 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
63 my $last_move;
64 my $last_text = '';
65 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
66
67 uciprint($engine, "setoption name UCI_AnalyseMode value true");
68 while (my ($key, $value) = each %remoteglotconf::engine_config) {
69         uciprint($engine, "setoption name $key value $value");
70 }
71 uciprint($engine, "ucinewgame");
72
73 if (defined($engine2)) {
74         uciprint($engine2, "setoption name UCI_AnalyseMode value true");
75         while (my ($key, $value) = each %remoteglotconf::engine2_config) {
76                 uciprint($engine2, "setoption name $key value $value");
77         }
78         uciprint($engine2, "setoption name MultiPV value 500");
79         uciprint($engine2, "ucinewgame");
80 }
81
82 print "Chess engine ready.\n";
83
84 # now talk to FICS
85 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
86 $t->input_log(\*FICSLOG);
87 $t->open($remoteglotconf::server);
88 $t->print($remoteglotconf::nick);
89 $t->waitfor('/Press return to enter the server/');
90 $t->cmd("");
91
92 # set some options
93 $t->cmd("set shout 0");
94 $t->cmd("set seek 0");
95 $t->cmd("set style 12");
96 $t->cmd("observe $remoteglotconf::target");
97 print "FICS ready.\n";
98
99 my $ev1 = AnyEvent->io(
100         fh => fileno($t),
101         poll => 'r',
102         cb => sub {    # what callback to execute
103                 while (1) {
104                         my $line = $t->getline(Timeout => 0, errmode => 'return');
105                         return if (!defined($line));
106
107                         chomp $line;
108                         $line =~ tr/\r//d;
109                         handle_fics($line);
110                 }
111         }
112 );
113 # Engine events have already been set up by Engine.pm.
114 EV::run;
115
116 sub handle_uci {
117         my ($engine, $line, $primary) = @_;
118
119         return if $line =~ /(upper|lower)bound/;
120
121         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
122         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
123         if ($line =~ /^info/) {
124                 my (@infos) = split / /, $line;
125                 shift @infos;
126
127                 parse_infos($engine, @infos);
128         }
129         if ($line =~ /^id/) {
130                 my (@ids) = split / /, $line;
131                 shift @ids;
132
133                 parse_ids($engine, @ids);
134         }
135         if ($line =~ /^bestmove/) {
136                 if ($primary) {
137                         return if (!$remoteglotconf::uci_assume_full_compliance);
138                         if (defined($pos_waiting)) {
139                                 uciprint($engine, "position fen " . $pos_waiting->fen());
140                                 uciprint($engine, "go infinite");
141
142                                 $pos_calculating = $pos_waiting;
143                                 $pos_waiting = undef;
144                         }
145                 } else {
146                         $engine2->{'info'} = {};
147                         my $pos = $pos_waiting // $pos_calculating;
148                         uciprint($engine2, "position fen " . $pos->fen());
149                         uciprint($engine2, "go infinite");
150                         $pos_calculating_second_engine = $pos;
151                 }
152         }
153         output();
154 }
155
156 sub handle_fics {
157         my $line = shift;
158         if ($line =~ /^<12> /) {
159                 handle_position(Position->new($line));
160         }
161         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
162                 my ($who, $msg) = ($1, $2);
163
164                 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
165
166                 if ($msg =~ /^fics (.*?)$/) {
167                         $t->cmd("tell $who Executing '$1' on FICS.");
168                         $t->cmd($1);
169                 } elsif ($msg =~ /^uci (.*?)$/) {
170                         $t->cmd("tell $who Sending '$1' to the engine.");
171                         print { $engine->{'write'} } "$1\n";
172                 } elsif ($msg =~ /^pgn (.*?)$/) {
173                         my $url = $1;
174                         $t->cmd("tell $who Starting to poll '$url'.");
175                         AnyEvent::HTTP::http_get($url, sub {
176                                 handle_pgn(@_, $url);
177                         });
178                 } elsif ($msg =~ /^stoppgn$/) {
179                         $t->cmd("tell $who Stopping poll.");
180                         $http_timer = undef;
181                 } elsif ($msg =~ /^quit$/) {
182                         $t->cmd("tell $who Bye bye.");
183                         exit;
184                 } else {
185                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
186                 }
187         }
188         #print "FICS: [$line]\n";
189 }
190
191 sub handle_pgn {
192         my ($body, $header, $url) = @_;
193         my $pgn = Chess::PGN::Parse->new(undef, $body);
194         if (!defined($pgn) || !$pgn->read_game()) {
195                 warn "Error in parsing PGN from $url\n";
196         } else {
197                 $pgn->quick_parse_game;
198                 my $pos = Position->start_pos($pgn->white, $pgn->black);
199                 my $moves = $pgn->moves;
200                 my @uci_moves = ();
201                 for my $move (@$moves) {
202                         my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
203                         push @uci_moves, Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
204                         $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
205                 }
206                 $pos->{'history'} = \@uci_moves;
207                 $pos->{'pretty_history'} = $moves;
208                 handle_position($pos);
209         }
210         
211         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
212                 AnyEvent::HTTP::http_get($url, sub {
213                         handle_pgn(@_, $url);
214                 });
215         });
216 }
217
218 sub handle_position {
219         my ($pos) = @_;
220                 
221         # if this is already in the queue, ignore it
222         return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
223
224         # if we're already chewing on this and there's nothing else in the queue,
225         # also ignore it
226         return if (!defined($pos_waiting) && defined($pos_calculating) &&
227                  $pos->fen() eq $pos_calculating->fen());
228
229         # if we're already thinking on something, stop and wait for the engine
230         # to approve
231         if (defined($pos_calculating)) {
232                 if (!defined($pos_waiting)) {
233                         uciprint($engine, "stop");
234                 }
235                 if ($remoteglotconf::uci_assume_full_compliance) {
236                         $pos_waiting = $pos;
237                 } else {
238                         uciprint($engine, "position fen " . $pos->fen());
239                         uciprint($engine, "go infinite");
240                         $pos_calculating = $pos;
241                 }
242         } else {
243                 # it's wrong just to give the FEN (the move history is useful,
244                 # and per the UCI spec, we should really have sent "ucinewgame"),
245                 # but it's easier
246                 uciprint($engine, "position fen " . $pos->fen());
247                 uciprint($engine, "go infinite");
248                 $pos_calculating = $pos;
249         }
250
251         if (defined($engine2)) {
252                 if (defined($pos_calculating_second_engine)) {
253                         uciprint($engine2, "stop");
254                 } else {
255                         uciprint($engine2, "position fen " . $pos->fen());
256                         uciprint($engine2, "go infinite");
257                         $pos_calculating_second_engine = $pos;
258                 }
259                 $engine2->{'info'} = {};
260         }
261
262         $engine->{'info'} = {};
263         $last_move = time;
264
265         schedule_tb_lookup();
266
267         # 
268         # Output a command every move to note that we're
269         # still paying attention -- this is a good tradeoff,
270         # since if no move has happened in the last half
271         # hour, the analysis/relay has most likely stopped
272         # and we should stop hogging server resources.
273         #
274         $t->cmd("date");
275 }
276
277 sub parse_infos {
278         my ($engine, @x) = @_;
279         my $mpv = '';
280
281         my $info = $engine->{'info'};
282
283         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
284         for my $i (0..$#x - 1) {
285                 if ($x[$i] eq 'multipv') {
286                         $mpv = $x[$i + 1];
287                         next;
288                 }
289         }
290
291         while (scalar @x > 0) {
292                 if ($x[0] eq 'multipv') {
293                         # Dealt with above
294                         shift @x;
295                         shift @x;
296                         next;
297                 }
298                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
299                         my $key = shift @x;
300                         my $value = shift @x;
301                         $info->{$key} = $value;
302                         next;
303                 }
304                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
305                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
306                     $x[0] eq 'tbhits') {
307                         my $key = shift @x;
308                         my $value = shift @x;
309                         $info->{$key . $mpv} = $value;
310                         next;
311                 }
312                 if ($x[0] eq 'score') {
313                         shift @x;
314
315                         delete $info->{'score_cp' . $mpv};
316                         delete $info->{'score_mate' . $mpv};
317
318                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
319                                 if ($x[0] eq 'cp') {
320                                         shift @x;
321                                         $info->{'score_cp' . $mpv} = shift @x;
322                                 } elsif ($x[0] eq 'mate') {
323                                         shift @x;
324                                         $info->{'score_mate' . $mpv} = shift @x;
325                                 } else {
326                                         shift @x;
327                                 }
328                         }
329                         next;
330                 }
331                 if ($x[0] eq 'pv') {
332                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
333                         last;
334                 }
335                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
336                         last;
337                 }
338
339                 #print "unknown info '$x[0]', trying to recover...\n";
340                 #shift @x;
341                 die "Unknown info '" . join(',', @x) . "'";
342
343         }
344 }
345
346 sub parse_ids {
347         my ($engine, @x) = @_;
348
349         while (scalar @x > 0) {
350                 if ($x[0] =~ /^(name|author)$/) {
351                         my $key = shift @x;
352                         my $value = join(' ', @x);
353                         $engine->{'id'}{$key} = $value;
354                         last;
355                 }
356
357                 # unknown
358                 shift @x;
359         }
360 }
361
362 sub prettyprint_pv_no_cache {
363         my ($board, @pvs) = @_;
364
365         if (scalar @pvs == 0 || !defined($pvs[0])) {
366                 return ();
367         }
368
369         my $pv = shift @pvs;
370         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
371         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
372         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
373 }
374
375 sub prettyprint_pv {
376         my ($pos, @pvs) = @_;
377
378         my $cachekey = join('', @pvs);
379         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
380                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
381         } else {
382                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
383                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
384                 return @res;
385         }
386 }
387
388 sub output {
389         #return;
390
391         return if (!defined($pos_calculating));
392
393         # Don't update too often.
394         my $age = Time::HiRes::tv_interval($latest_update);
395         if ($age < $remoteglotconf::update_max_interval) {
396                 Time::HiRes::alarm($remoteglotconf::update_max_interval + 0.01 - $age);
397                 return;
398         }
399         
400         my $info = $engine->{'info'};
401
402         #
403         # If we have tablebase data from a previous lookup, replace the
404         # engine data with the data from the tablebase.
405         #
406         my $fen = $pos_calculating->fen();
407         if (exists($tb_cache{$fen})) {
408                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
409                         delete $info->{$key . '1'};
410                         delete $info->{$key};
411                 }
412                 $info->{'nodes'} = 0;
413                 $info->{'nps'} = 0;
414                 $info->{'depth'} = 0;
415                 $info->{'seldepth'} = 0;
416                 $info->{'tbhits'} = 0;
417
418                 my $t = $tb_cache{$fen};
419                 my $pv = $t->{'pv'};
420                 my $matelen = int((1 + scalar @$pv) / 2);
421                 if ($t->{'result'} eq '1/2-1/2') {
422                         $info->{'score_cp'} = 0;
423                 } elsif ($t->{'result'} eq '1-0') {
424                         if ($pos_calculating->{'toplay'} eq 'B') {
425                                 $info->{'score_mate'} = -$matelen;
426                         } else {
427                                 $info->{'score_mate'} = $matelen;
428                         }
429                 } else {
430                         if ($pos_calculating->{'toplay'} eq 'B') {
431                                 $info->{'score_mate'} = $matelen;
432                         } else {
433                                 $info->{'score_mate'} = -$matelen;
434                         }
435                 }
436                 $info->{'pv'} = $pv;
437                 $info->{'tablebase'} = 1;
438         } else {
439                 $info->{'tablebase'} = 0;
440         }
441         
442         #
443         # Some programs _always_ report MultiPV, even with only one PV.
444         # In this case, we simply use that data as if MultiPV was never
445         # specified.
446         #
447         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
448                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
449                         if (exists($info->{$key . '1'})) {
450                                 $info->{$key} = $info->{$key . '1'};
451                         }
452                 }
453         }
454         
455         #
456         # Check the PVs first. if they're invalid, just wait, as our data
457         # is most likely out of sync. This isn't a very good solution, as
458         # it can frequently miss stuff, but it's good enough for most users.
459         #
460         eval {
461                 my $dummy;
462                 if (exists($info->{'pv'})) {
463                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
464                 }
465         
466                 my $mpv = 1;
467                 while (exists($info->{'pv' . $mpv})) {
468                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
469                         ++$mpv;
470                 }
471         };
472         if ($@) {
473                 $engine->{'info'} = {};
474                 return;
475         }
476
477         output_screen();
478         output_json();
479         $latest_update = [Time::HiRes::gettimeofday];
480 }
481
482 sub output_screen {
483         my $info = $engine->{'info'};
484         my $id = $engine->{'id'};
485
486         my $text = 'Analysis';
487         if ($pos_calculating->{'last_move'} ne 'none') {
488                 if ($pos_calculating->{'toplay'} eq 'W') {
489                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
490                 } else {
491                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
492                 }
493                 if (exists($id->{'name'})) {
494                         $text .= ',';
495                 }
496         }
497
498         if (exists($id->{'name'})) {
499                 $text .= " by $id->{'name'}:\n\n";
500         } else {
501                 $text .= ":\n\n";
502         }
503
504         return unless (exists($pos_calculating->{'board'}));
505                 
506         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
507                 # multi-PV
508                 my $mpv = 1;
509                 while (exists($info->{'pv' . $mpv})) {
510                         $text .= sprintf "  PV%2u", $mpv;
511                         my $score = short_score($info, $pos_calculating, $mpv);
512                         $text .= "  ($score)" if (defined($score));
513
514                         my $tbhits = '';
515                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
516                                 if ($info->{'tbhits' . $mpv} == 1) {
517                                         $tbhits = ", 1 tbhit";
518                                 } else {
519                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
520                                 }
521                         }
522
523                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
524                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
525                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
526                         }
527
528                         $text .= ":\n";
529                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
530                         $text .= "\n";
531                         ++$mpv;
532                 }
533         } else {
534                 # single-PV
535                 my $score = long_score($info, $pos_calculating, '');
536                 $text .= "  $score\n" if defined($score);
537                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
538                 $text .=  "\n";
539
540                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
541                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
542                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
543                 }
544                 if (exists($info->{'seldepth'})) {
545                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
546                 }
547                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
548                         if ($info->{'tbhits'} == 1) {
549                                 $text .= ", one Syzygy hit";
550                         } else {
551                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
552                         }
553                 }
554                 $text .= "\n\n";
555         }
556
557         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
558
559         my @refutation_lines = ();
560         if (defined($engine2)) {
561                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
562                         my $info = $engine2->{'info'};
563                         last if (!exists($info->{'pv' . $mpv}));
564                         eval {
565                                 my $pv = $info->{'pv' . $mpv};
566
567                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
568                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
569                                 if (scalar @pretty_pv > 5) {
570                                         @pretty_pv = @pretty_pv[0..4];
571                                         push @pretty_pv, "...";
572                                 }
573                                 my $key = $pretty_move;
574                                 my $line = sprintf("  %-6s %6s %3s  %s",
575                                         $pretty_move,
576                                         short_score($info, $pos_calculating_second_engine, $mpv),
577                                         "d" . $info->{'depth' . $mpv},
578                                         join(', ', @pretty_pv));
579                                 push @refutation_lines, [ $key, $line ];
580                         };
581                 }
582         }
583
584         if ($#refutation_lines >= 0) {
585                 $text .= "Shallow search of all legal moves:\n\n";
586                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
587                         $text .= $line->[1] . "\n";
588                 }
589                 $text .= "\n\n";        
590         }       
591
592         if ($last_text ne $text) {
593                 print "\e[H\e[2J"; # clear the screen
594                 print $text;
595                 $last_text = $text;
596         }
597 }
598
599 sub output_json {
600         my $info = $engine->{'info'};
601
602         my $json = {};
603         $json->{'position'} = $pos_calculating->to_json_hash();
604         $json->{'id'} = $engine->{'id'};
605         $json->{'score'} = long_score($info, $pos_calculating, '');
606         $json->{'short_score'} = short_score($info, $pos_calculating, '');
607
608         $json->{'nodes'} = $info->{'nodes'};
609         $json->{'nps'} = $info->{'nps'};
610         $json->{'depth'} = $info->{'depth'};
611         $json->{'tbhits'} = $info->{'tbhits'};
612         $json->{'seldepth'} = $info->{'seldepth'};
613         $json->{'tablebase'} = $info->{'tablebase'};
614
615         # single-PV only for now
616         $json->{'pv_uci'} = $info->{'pv'};
617         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
618
619         my %refutation_lines = ();
620         my @refutation_lines = ();
621         if (defined($engine2)) {
622                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
623                         my $info = $engine2->{'info'};
624                         my $pretty_move = "";
625                         my @pretty_pv = ();
626                         last if (!exists($info->{'pv' . $mpv}));
627
628                         eval {
629                                 my $pv = $info->{'pv' . $mpv};
630                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
631                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
632                                 $refutation_lines{$pv->[0]} = {
633                                         sort_key => $pretty_move,
634                                         depth => $info->{'depth' . $mpv},
635                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
636                                         pretty_score => short_score($info, $pos_calculating, $mpv),
637                                         pretty_move => $pretty_move,
638                                         pv_pretty => \@pretty_pv,
639                                 };
640                                 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
641                         };
642                 }
643         }
644         $json->{'refutation_lines'} = \%refutation_lines;
645
646         open my $fh, ">", $remoteglotconf::json_output . ".tmp"
647                 or return;
648         print $fh JSON::XS::encode_json($json);
649         close $fh;
650         rename($remoteglotconf::json_output . ".tmp", $remoteglotconf::json_output);
651 }
652
653 sub uciprint {
654         my ($engine, $msg) = @_;
655         $engine->print($msg);
656         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
657 }
658
659 sub short_score {
660         my ($info, $pos, $mpv) = @_;
661
662         my $invert = ($pos->{'toplay'} eq 'B');
663         if (defined($info->{'score_mate' . $mpv})) {
664                 if ($invert) {
665                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
666                 } else {
667                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
668                 }
669         } else {
670                 if (exists($info->{'score_cp' . $mpv})) {
671                         my $score = $info->{'score_cp' . $mpv} * 0.01;
672                         if ($score == 0) {
673                                 if ($info->{'tablebase'}) {
674                                         return "TB draw";
675                                 } else {
676                                         return " 0.00";
677                                 }
678                         }
679                         if ($invert) {
680                                 $score = -$score;
681                         }
682                         return sprintf "%+5.2f", $score;
683                 }
684         }
685
686         return undef;
687 }
688
689 sub score_sort_key {
690         my ($info, $pos, $mpv, $invert) = @_;
691
692         if (defined($info->{'score_mate' . $mpv})) {
693                 my $mate = $info->{'score_mate' . $mpv};
694                 my $score;
695                 if ($mate > 0) {
696                         # Side to move mates
697                         $mate = 99999 - $mate;
698                 } else {
699                         # Side to move is getting mated (note the double negative for $mate)
700                         $mate = -99999 - $mate;
701                 }
702                 if ($invert) {
703                         $score = -$score;
704                 }
705                 return $score;
706         } else {
707                 if (exists($info->{'score_cp' . $mpv})) {
708                         my $score = $info->{'score_cp' . $mpv};
709                         if ($invert) {
710                                 $score = -$score;
711                         }
712                         return $score;
713                 }
714         }
715
716         return undef;
717 }
718
719 sub long_score {
720         my ($info, $pos, $mpv) = @_;
721
722         if (defined($info->{'score_mate' . $mpv})) {
723                 my $mate = $info->{'score_mate' . $mpv};
724                 if ($pos->{'toplay'} eq 'B') {
725                         $mate = -$mate;
726                 }
727                 if ($mate > 0) {
728                         return sprintf "White mates in %u", $mate;
729                 } else {
730                         return sprintf "Black mates in %u", -$mate;
731                 }
732         } else {
733                 if (exists($info->{'score_cp' . $mpv})) {
734                         my $score = $info->{'score_cp' . $mpv} * 0.01;
735                         if ($score == 0) {
736                                 if ($info->{'tablebase'}) {
737                                         return "Theoretical draw";
738                                 } else {
739                                         return "Score:  0.00";
740                                 }
741                         }
742                         if ($pos->{'toplay'} eq 'B') {
743                                 $score = -$score;
744                         }
745                         return sprintf "Score: %+5.2f", $score;
746                 }
747         }
748
749         return undef;
750 }
751
752 my %book_cache = ();
753 sub book_info {
754         my ($fen, $board, $toplay) = @_;
755
756         if (exists($book_cache{$fen})) {
757                 return $book_cache{$fen};
758         }
759
760         my $ret = `./booklook $fen`;
761         return "" if ($ret =~ /Not found/ || $ret eq '');
762
763         my @moves = ();
764
765         for my $m (split /\n/, $ret) {
766                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
767
768                 my $pmove;
769                 if ($move eq '')  {
770                         $pmove = '(current)';
771                 } else {
772                         ($pmove) = prettyprint_pv_no_cache($board, $move);
773                         $pmove .= $annotation;
774                 }
775
776                 my $score;
777                 if ($toplay eq 'W') {
778                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
779                 } else {
780                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
781                 }
782                 my $n = $win + $draw + $lose;
783                 
784                 my $percent;
785                 if ($n == 0) {
786                         $percent = "     ";
787                 } else {
788                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
789                 }
790
791                 push @moves, [ $pmove, $n, $percent, $rating ];
792         }
793
794         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
795         
796         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
797         for my $m (@moves) {
798                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
799         }
800
801         return $text;
802 }
803
804 sub schedule_tb_lookup {
805         return if (!defined($remoteglotconf::tb_serial_key));
806         my $pos = $pos_waiting // $pos_calculating;
807         return if (exists($tb_cache{$pos->fen()}));
808
809         # If there's more than seven pieces, there's not going to be an answer,
810         # so don't bother.
811         return if ($pos->num_pieces() > 7);
812
813         # Max one at a time. If it's still relevant when it returns,
814         # schedule_tb_lookup() will be called again.
815         return if ($tb_lookup_running);
816
817         $tb_lookup_running = 1;
818         my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
819                 $remoteglotconf::tb_serial_key .
820                 '&auth.password=aquarium&type=0&fen=' . 
821                 URI::Escape::uri_escape($pos->fen());
822         print TBLOG "Downloading $url...\n";
823         AnyEvent::HTTP::http_get($url, sub {
824                 handle_tb_lookup_return(@_, $pos, $pos->fen());
825         });
826 }
827
828 sub handle_tb_lookup_return {
829         my ($body, $header, $pos, $fen) = @_;
830         print TBLOG "Response for [$fen]:\n";
831         print TBLOG $header . "\n\n";
832         print TBLOG $body . "\n\n";
833         eval {
834                 my $response = JSON::XS::decode_json($body);
835                 if ($response->{'ErrorCode'} != 0) {
836                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
837                 }
838                 my $state = $response->{'Response'}{'StateString'};
839                 if ($state eq 'COMPLETE') {
840                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
841                         if (!defined($pgn) || !$pgn->read_game()) {
842                                 warn "Error in parsing PGN\n";
843                         } else {
844                                 $pgn->quick_parse_game;
845                                 my $pvpos = $pos;
846                                 my $moves = $pgn->moves;
847                                 my @uci_moves = ();
848                                 for my $move (@$moves) {
849                                         my ($from_row, $from_col, $to_row, $to_col, $promo) = $pvpos->parse_pretty_move($move);
850                                         push @uci_moves, Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
851                                         $pvpos = $pvpos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
852                                 }
853                                 $tb_cache{$fen} = {
854                                         result => $pgn->result,
855                                         pv => \@uci_moves
856                                 };
857                                 output();
858                         }
859                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
860                         # Try again in a second. Note that if we have changed
861                         # position in the meantime, we might query a completely
862                         # different position! But that's fine.
863                 } else {
864                         die "Unknown response state " . $state;
865                 }
866
867                 # Wait a second before we schedule another one.
868                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
869                         $tb_lookup_running = 0;
870                         schedule_tb_lookup();
871                 });
872         };
873         if ($@) {
874                 warn "Error in tablebase lookup: $@";
875
876                 # Don't try this one again, but don't block new lookups either.
877                 $tb_lookup_running = 0;
878         }
879 }
880
881 sub open_engine {
882         my ($cmdline, $tag, $cb) = @_;
883         return undef if (!defined($cmdline));
884         return Engine->open($cmdline, $tag, $cb);
885 }
886
887 sub col_letter_to_num {
888         return ord(shift) - ord('a');
889 }
890
891 sub row_letter_to_num {
892         return 7 - (ord(shift) - ord('1'));
893 }
894
895 sub parse_uci_move {
896         my $move = shift;
897         my $from_col = col_letter_to_num(substr($move, 0, 1));
898         my $from_row = row_letter_to_num(substr($move, 1, 1));
899         my $to_col   = col_letter_to_num(substr($move, 2, 1));
900         my $to_row   = row_letter_to_num(substr($move, 3, 1));
901         my $promo    = substr($move, 4, 1);
902         return ($from_col, $from_row, $to_col, $to_row, $promo);
903 }