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