]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Fix an issue (not yet visible, really) where conversion from single multi-PV would...
[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 File::Slurp;
19 use IPC::Open2;
20 use Time::HiRes;
21 use JSON::XS;
22 use URI::Escape;
23 use DBI;
24 use DBD::Pg;
25 require 'Position.pm';
26 require 'Engine.pm';
27 require 'config.pm';
28 use strict;
29 use warnings;
30 no warnings qw(once);
31
32 # Program starts here
33 my $latest_update = undef;
34 my $output_timer = undef;
35 my $http_timer = undef;
36 my $stop_pgn_fetch = 0;
37 my $tb_retry_timer = undef;
38 my %tb_cache = ();
39 my $tb_lookup_running = 0;
40 my $last_written_json = undef;
41
42 # Persisted so we can restart.
43 # TODO: Figure out an appropriate way to deal with database restarts
44 # and/or Postgres going away entirely.
45 my $dbh = DBI->connect($remoteglotconf::dbistr, $remoteglotconf::dbiuser, $remoteglotconf::dbipass)
46         or die DBI->errstr;
47 $dbh->{RaiseError} = 1;
48
49 $| = 1;
50
51 open(FICSLOG, ">ficslog.txt")
52         or die "ficslog.txt: $!";
53 print FICSLOG "Log starting.\n";
54 select(FICSLOG);
55 $| = 1;
56
57 open(UCILOG, ">ucilog.txt")
58         or die "ucilog.txt: $!";
59 print UCILOG "Log starting.\n";
60 select(UCILOG);
61 $| = 1;
62
63 open(TBLOG, ">tblog.txt")
64         or die "tblog.txt: $!";
65 print TBLOG "Log starting.\n";
66 select(TBLOG);
67 $| = 1;
68
69 select(STDOUT);
70 umask 0022;
71
72 # open the chess engine
73 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
74 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
75 my $last_move;
76 my $last_text = '';
77 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
78
79 uciprint($engine, "setoption name UCI_AnalyseMode value true");
80 while (my ($key, $value) = each %remoteglotconf::engine_config) {
81         uciprint($engine, "setoption name $key value $value");
82 }
83 uciprint($engine, "ucinewgame");
84
85 if (defined($engine2)) {
86         uciprint($engine2, "setoption name UCI_AnalyseMode value true");
87         while (my ($key, $value) = each %remoteglotconf::engine2_config) {
88                 uciprint($engine2, "setoption name $key value $value");
89         }
90         uciprint($engine2, "setoption name MultiPV value 500");
91         uciprint($engine2, "ucinewgame");
92 }
93
94 print "Chess engine ready.\n";
95
96 # now talk to FICS
97 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
98 $t->input_log(\*FICSLOG);
99 $t->open($remoteglotconf::server);
100 $t->print($remoteglotconf::nick);
101 $t->waitfor('/Press return to enter the server/');
102 $t->cmd("");
103
104 # set some options
105 $t->cmd("set shout 0");
106 $t->cmd("set seek 0");
107 $t->cmd("set style 12");
108
109 my $ev1 = AnyEvent->io(
110         fh => fileno($t),
111         poll => 'r',
112         cb => sub {    # what callback to execute
113                 while (1) {
114                         my $line = $t->getline(Timeout => 0, errmode => 'return');
115                         return if (!defined($line));
116
117                         chomp $line;
118                         $line =~ tr/\r//d;
119                         handle_fics($line);
120                 }
121         }
122 );
123 if (defined($remoteglotconf::target)) {
124         if ($remoteglotconf::target =~ /^http:/) {
125                 fetch_pgn($remoteglotconf::target);
126         } else {
127                 $t->cmd("observe $remoteglotconf::target");
128         }
129 }
130 print "FICS ready.\n";
131
132 # Engine events have already been set up by Engine.pm.
133 EV::run;
134
135 sub handle_uci {
136         my ($engine, $line, $primary) = @_;
137
138         return if $line =~ /(upper|lower)bound/;
139
140         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
141         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
142         if ($line =~ /^info/) {
143                 my (@infos) = split / /, $line;
144                 shift @infos;
145
146                 parse_infos($engine, @infos);
147         }
148         if ($line =~ /^id/) {
149                 my (@ids) = split / /, $line;
150                 shift @ids;
151
152                 parse_ids($engine, @ids);
153         }
154         if ($line =~ /^bestmove/) {
155                 if ($primary) {
156                         return if (!$remoteglotconf::uci_assume_full_compliance);
157                         if (defined($pos_waiting)) {
158                                 uciprint($engine, "position fen " . $pos_waiting->fen());
159                                 uciprint($engine, "go infinite");
160
161                                 $pos_calculating = $pos_waiting;
162                                 $pos_waiting = undef;
163                         }
164                 } else {
165                         $engine2->{'info'} = {};
166                         my $pos = $pos_waiting // $pos_calculating;
167                         uciprint($engine2, "position fen " . $pos->fen());
168                         uciprint($engine2, "go infinite");
169                         $pos_calculating_second_engine = $pos;
170                 }
171         }
172         output();
173 }
174
175 my $getting_movelist = 0;
176 my $pos_for_movelist = undef;
177 my @uci_movelist = ();
178 my @pretty_movelist = ();
179
180 sub handle_fics {
181         my $line = shift;
182         if ($line =~ /^<12> /) {
183                 handle_position(Position->new($line));
184                 $t->cmd("moves");
185         }
186         if ($line =~ /^Movelist for game /) {
187                 my $pos = $pos_waiting // $pos_calculating;
188                 if (defined($pos)) {
189                         @uci_movelist = ();
190                         @pretty_movelist = ();
191                         $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
192                         $getting_movelist = 1;
193                 }
194         }
195         if ($getting_movelist &&
196             $line =~ /^\s* \d+\. \s+                     # move number
197                        (\S+) \s+ \( [\d:.]+ \) \s*       # first move, then time
198                        (?: (\S+) \s+ \( [\d:.]+ \) )?    # second move, then time 
199                      /x) {
200                 eval {
201                         my $uci_move;
202                         ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
203                         push @uci_movelist, $uci_move;
204                         push @pretty_movelist, $1;
205
206                         if (defined($2)) {
207                                 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
208                                 push @uci_movelist, $uci_move;
209                                 push @pretty_movelist, $2;
210                         }
211                 };
212                 if ($@) {
213                         warn "Error when getting FICS move history: $@";
214                         $getting_movelist = 0;
215                 }
216         }
217         if ($getting_movelist &&
218             $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
219                 # End of movelist.
220                 for my $pos ($pos_waiting, $pos_calculating) {
221                         next if (!defined($pos));
222                         if ($pos->fen() eq $pos_for_movelist->fen()) {
223                                 $pos->{'pretty_history'} = \@pretty_movelist;
224                         }
225                 }
226                 $getting_movelist = 0;
227         }
228         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
229                 my ($who, $msg) = ($1, $2);
230
231                 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
232
233                 if ($msg =~ /^fics (.*?)$/) {
234                         $t->cmd("tell $who Executing '$1' on FICS.");
235                         $t->cmd($1);
236                 } elsif ($msg =~ /^uci (.*?)$/) {
237                         $t->cmd("tell $who Sending '$1' to the engine.");
238                         print { $engine->{'write'} } "$1\n";
239                 } elsif ($msg =~ /^pgn (.*?)$/) {
240                         my $url = $1;
241                         $t->cmd("tell $who Starting to poll '$url'.");
242                         fetch_pgn($url);
243                 } elsif ($msg =~ /^stoppgn$/) {
244                         $t->cmd("tell $who Stopping poll.");
245                         $stop_pgn_fetch = 1;
246                         $http_timer = undef;
247                 } elsif ($msg =~ /^quit$/) {
248                         $t->cmd("tell $who Bye bye.");
249                         exit;
250                 } else {
251                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
252                 }
253         }
254         #print "FICS: [$line]\n";
255 }
256
257 # Starts periodic fetching of PGNs from the given URL.
258 sub fetch_pgn {
259         my ($url) = @_;
260         AnyEvent::HTTP::http_get($url, sub {
261                 handle_pgn(@_, $url);
262         });
263 }
264
265 my ($last_pgn_white, $last_pgn_black);
266 my @last_pgn_uci_moves = ();
267 my $pgn_hysteresis_counter = 0;
268
269 sub handle_pgn {
270         my ($body, $header, $url) = @_;
271
272         if ($stop_pgn_fetch) {
273                 $stop_pgn_fetch = 0;
274                 $http_timer = undef;
275                 return;
276         }
277
278         my $pgn = Chess::PGN::Parse->new(undef, $body);
279         if (!defined($pgn)) {
280                 warn "Error in parsing PGN from $url [body='$body']\n";
281         } elsif (!$pgn->read_game()) {
282                 warn "Error in reading PGN game from $url [body='$body']\n";
283         } elsif ($body !~ /^\[/) {
284                 warn "Malformed PGN from $url [body='$body']\n";
285         } else {
286                 eval {
287                         # Skip to the right game.
288                         while (defined($remoteglotconf::pgn_filter) &&
289                                !&$remoteglotconf::pgn_filter($pgn)) {
290                                 $pgn->read_game() or die "Out of games during filtering";
291                         }
292
293                         $pgn->parse_game({ save_comments => 'yes' });
294                         my $pos = Position->start_pos($pgn->white, $pgn->black);
295                         my $moves = $pgn->moves;
296                         my @uci_moves = ();
297                         my @repretty_moves = ();
298                         for my $move (@$moves) {
299                                 my ($npos, $uci_move) = $pos->make_pretty_move($move);
300                                 push @uci_moves, $uci_move;
301
302                                 # Re-prettyprint the move.
303                                 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
304                                 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
305                                 push @repretty_moves, $pretty;
306                                 $pos = $npos;
307                         }
308                         $pos->{'result'} = $pgn->result;
309                         $pos->{'pretty_history'} = \@repretty_moves;
310
311                         extract_clock($pgn, $pos);
312
313                         # Sometimes, PGNs lose a move or two for a short while,
314                         # or people push out new ones non-atomically. 
315                         # Thus, if we PGN doesn't change names but becomes
316                         # shorter, we mistrust it for a few seconds.
317                         my $trust_pgn = 1;
318                         if (defined($last_pgn_white) && defined($last_pgn_black) &&
319                             $last_pgn_white eq $pgn->white &&
320                             $last_pgn_black eq $pgn->black &&
321                             scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
322                                 if (++$pgn_hysteresis_counter < 3) {
323                                         $trust_pgn = 0; 
324                                 }
325                         }
326                         if ($trust_pgn) {
327                                 $last_pgn_white = $pgn->white;
328                                 $last_pgn_black = $pgn->black;
329                                 @last_pgn_uci_moves = @uci_moves;
330                                 $pgn_hysteresis_counter = 0;
331                                 handle_position($pos);
332                         }
333                 };
334                 if ($@) {
335                         warn "Error in parsing moves from $url: $@\n";
336                 }
337         }
338         
339         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
340                 fetch_pgn($url);
341         });
342 }
343
344 sub handle_position {
345         my ($pos) = @_;
346         find_clock_start($pos, $pos_calculating);
347                 
348         # if this is already in the queue, ignore it (just update the result)
349         if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
350                 $pos_waiting->{'result'} = $pos->{'result'};
351                 return;
352         }
353
354         # if we're already chewing on this and there's nothing else in the queue,
355         # also ignore it
356         if (!defined($pos_waiting) && defined($pos_calculating) &&
357             $pos->fen() eq $pos_calculating->fen()) {
358                 $pos_calculating->{'result'} = $pos->{'result'};
359                 return;
360         }
361
362         # if we're already thinking on something, stop and wait for the engine
363         # to approve
364         if (defined($pos_calculating)) {
365                 # Store the final data we have for this position in the history,
366                 # with the precise clock information we just got from the new
367                 # position. (Historic positions store the clock at the end of
368                 # the position.)
369                 #
370                 # Do not output anything new to the main analysis; that's
371                 # going to be obsolete really soon.
372                 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
373                 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
374                 delete $pos_calculating->{'white_clock_target'};
375                 delete $pos_calculating->{'black_clock_target'};
376                 output_json(1);
377
378                 if (!defined($pos_waiting)) {
379                         uciprint($engine, "stop");
380                 }
381                 if ($remoteglotconf::uci_assume_full_compliance) {
382                         $pos_waiting = $pos;
383                 } else {
384                         uciprint($engine, "position fen " . $pos->fen());
385                         uciprint($engine, "go infinite");
386                         $pos_calculating = $pos;
387                 }
388         } else {
389                 # it's wrong just to give the FEN (the move history is useful,
390                 # and per the UCI spec, we should really have sent "ucinewgame"),
391                 # but it's easier
392                 uciprint($engine, "position fen " . $pos->fen());
393                 uciprint($engine, "go infinite");
394                 $pos_calculating = $pos;
395         }
396
397         if (defined($engine2)) {
398                 if (defined($pos_calculating_second_engine)) {
399                         uciprint($engine2, "stop");
400                 } else {
401                         uciprint($engine2, "position fen " . $pos->fen());
402                         uciprint($engine2, "go infinite");
403                         $pos_calculating_second_engine = $pos;
404                 }
405                 $engine2->{'info'} = {};
406         }
407
408         $engine->{'info'} = {};
409         $last_move = time;
410
411         schedule_tb_lookup();
412
413         # 
414         # Output a command every move to note that we're
415         # still paying attention -- this is a good tradeoff,
416         # since if no move has happened in the last half
417         # hour, the analysis/relay has most likely stopped
418         # and we should stop hogging server resources.
419         #
420         $t->cmd("date");
421 }
422
423 sub parse_infos {
424         my ($engine, @x) = @_;
425         my $mpv = '';
426
427         my $info = $engine->{'info'};
428
429         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
430         for my $i (0..$#x - 1) {
431                 if ($x[$i] eq 'multipv') {
432                         $mpv = $x[$i + 1];
433                         next;
434                 }
435         }
436
437         while (scalar @x > 0) {
438                 if ($x[0] eq 'multipv') {
439                         # Dealt with above
440                         shift @x;
441                         shift @x;
442                         next;
443                 }
444                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
445                         my $key = shift @x;
446                         my $value = shift @x;
447                         $info->{$key} = $value;
448                         next;
449                 }
450                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
451                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
452                     $x[0] eq 'tbhits') {
453                         my $key = shift @x;
454                         my $value = shift @x;
455                         $info->{$key . $mpv} = $value;
456                         next;
457                 }
458                 if ($x[0] eq 'score') {
459                         shift @x;
460
461                         delete $info->{'score_cp' . $mpv};
462                         delete $info->{'score_mate' . $mpv};
463
464                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
465                                 if ($x[0] eq 'cp') {
466                                         shift @x;
467                                         $info->{'score_cp' . $mpv} = shift @x;
468                                 } elsif ($x[0] eq 'mate') {
469                                         shift @x;
470                                         $info->{'score_mate' . $mpv} = shift @x;
471                                 } else {
472                                         shift @x;
473                                 }
474                         }
475                         next;
476                 }
477                 if ($x[0] eq 'pv') {
478                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
479                         last;
480                 }
481                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
482                         last;
483                 }
484
485                 #print "unknown info '$x[0]', trying to recover...\n";
486                 #shift @x;
487                 die "Unknown info '" . join(',', @x) . "'";
488
489         }
490 }
491
492 sub parse_ids {
493         my ($engine, @x) = @_;
494
495         while (scalar @x > 0) {
496                 if ($x[0] eq 'name') {
497                         my $value = join(' ', @x);
498                         $engine->{'id'}{'author'} = $value;
499                         last;
500                 }
501
502                 # unknown
503                 shift @x;
504         }
505 }
506
507 sub prettyprint_pv_no_cache {
508         my ($board, @pvs) = @_;
509
510         if (scalar @pvs == 0 || !defined($pvs[0])) {
511                 return ();
512         }
513
514         my $pv = shift @pvs;
515         my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
516         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
517         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
518 }
519
520 sub prettyprint_pv {
521         my ($pos, @pvs) = @_;
522
523         my $cachekey = join('', @pvs);
524         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
525                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
526         } else {
527                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
528                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
529                 return @res;
530         }
531 }
532
533 sub output {
534         #return;
535
536         return if (!defined($pos_calculating));
537
538         # Don't update too often.
539         my $age = Time::HiRes::tv_interval($latest_update);
540         if ($age < $remoteglotconf::update_max_interval) {
541                 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
542                 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
543                 return;
544         }
545         
546         my $info = $engine->{'info'};
547
548         #
549         # If we have tablebase data from a previous lookup, replace the
550         # engine data with the data from the tablebase.
551         #
552         my $fen = $pos_calculating->fen();
553         if (exists($tb_cache{$fen})) {
554                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
555                         delete $info->{$key . '1'};
556                         delete $info->{$key};
557                 }
558                 $info->{'nodes'} = 0;
559                 $info->{'nps'} = 0;
560                 $info->{'depth'} = 0;
561                 $info->{'seldepth'} = 0;
562                 $info->{'tbhits'} = 0;
563
564                 my $t = $tb_cache{$fen};
565                 my $pv = $t->{'pv'};
566                 my $matelen = int((1 + $t->{'score'}) / 2);
567                 if ($t->{'result'} eq '1/2-1/2') {
568                         $info->{'score_cp'} = 0;
569                 } elsif ($t->{'result'} eq '1-0') {
570                         if ($pos_calculating->{'toplay'} eq 'B') {
571                                 $info->{'score_mate'} = -$matelen;
572                         } else {
573                                 $info->{'score_mate'} = $matelen;
574                         }
575                 } else {
576                         if ($pos_calculating->{'toplay'} eq 'B') {
577                                 $info->{'score_mate'} = $matelen;
578                         } else {
579                                 $info->{'score_mate'} = -$matelen;
580                         }
581                 }
582                 $info->{'pv'} = $pv;
583                 $info->{'tablebase'} = 1;
584         } else {
585                 $info->{'tablebase'} = 0;
586         }
587         
588         #
589         # Some programs _always_ report MultiPV, even with only one PV.
590         # In this case, we simply use that data as if MultiPV was never
591         # specified.
592         #
593         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
594                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
595                         if (exists($info->{$key . '1'})) {
596                                 $info->{$key} = $info->{$key . '1'};
597                         } else {
598                                 delete $info->{$key};
599                         }
600                 }
601         }
602         
603         #
604         # Check the PVs first. if they're invalid, just wait, as our data
605         # is most likely out of sync. This isn't a very good solution, as
606         # it can frequently miss stuff, but it's good enough for most users.
607         #
608         eval {
609                 my $dummy;
610                 if (exists($info->{'pv'})) {
611                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
612                 }
613         
614                 my $mpv = 1;
615                 while (exists($info->{'pv' . $mpv})) {
616                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
617                         ++$mpv;
618                 }
619         };
620         if ($@) {
621                 $engine->{'info'} = {};
622                 return;
623         }
624
625         output_screen();
626         output_json(0);
627         $latest_update = [Time::HiRes::gettimeofday];
628 }
629
630 sub output_screen {
631         my $info = $engine->{'info'};
632         my $id = $engine->{'id'};
633
634         my $text = 'Analysis';
635         if ($pos_calculating->{'last_move'} ne 'none') {
636                 if ($pos_calculating->{'toplay'} eq 'W') {
637                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
638                 } else {
639                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
640                 }
641                 if (exists($id->{'name'})) {
642                         $text .= ',';
643                 }
644         }
645
646         if (exists($id->{'name'})) {
647                 $text .= " by $id->{'name'}:\n\n";
648         } else {
649                 $text .= ":\n\n";
650         }
651
652         return unless (exists($pos_calculating->{'board'}));
653                 
654         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
655                 # multi-PV
656                 my $mpv = 1;
657                 while (exists($info->{'pv' . $mpv})) {
658                         $text .= sprintf "  PV%2u", $mpv;
659                         my $score = short_score($info, $pos_calculating, $mpv);
660                         $text .= "  ($score)" if (defined($score));
661
662                         my $tbhits = '';
663                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
664                                 if ($info->{'tbhits' . $mpv} == 1) {
665                                         $tbhits = ", 1 tbhit";
666                                 } else {
667                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
668                                 }
669                         }
670
671                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
672                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
673                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
674                         }
675
676                         $text .= ":\n";
677                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
678                         $text .= "\n";
679                         ++$mpv;
680                 }
681         } else {
682                 # single-PV
683                 my $score = long_score($info, $pos_calculating, '');
684                 $text .= "  $score\n" if defined($score);
685                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
686                 $text .=  "\n";
687
688                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
689                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
690                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
691                 }
692                 if (exists($info->{'seldepth'})) {
693                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
694                 }
695                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
696                         if ($info->{'tbhits'} == 1) {
697                                 $text .= ", one Syzygy hit";
698                         } else {
699                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
700                         }
701                 }
702                 $text .= "\n\n";
703         }
704
705         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
706
707         my @refutation_lines = ();
708         if (defined($engine2)) {
709                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
710                         my $info = $engine2->{'info'};
711                         last if (!exists($info->{'pv' . $mpv}));
712                         eval {
713                                 my $pv = $info->{'pv' . $mpv};
714
715                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
716                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
717                                 if (scalar @pretty_pv > 5) {
718                                         @pretty_pv = @pretty_pv[0..4];
719                                         push @pretty_pv, "...";
720                                 }
721                                 my $key = $pretty_move;
722                                 my $line = sprintf("  %-6s %6s %3s  %s",
723                                         $pretty_move,
724                                         short_score($info, $pos_calculating_second_engine, $mpv),
725                                         "d" . $info->{'depth' . $mpv},
726                                         join(', ', @pretty_pv));
727                                 push @refutation_lines, [ $key, $line ];
728                         };
729                 }
730         }
731
732         if ($#refutation_lines >= 0) {
733                 $text .= "Shallow search of all legal moves:\n\n";
734                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
735                         $text .= $line->[1] . "\n";
736                 }
737                 $text .= "\n\n";        
738         }       
739
740         if ($last_text ne $text) {
741                 print "\e[H\e[2J"; # clear the screen
742                 print $text;
743                 $last_text = $text;
744         }
745 }
746
747 sub output_json {
748         my $historic_json_only = shift;
749         my $info = $engine->{'info'};
750
751         my $json = {};
752         $json->{'position'} = $pos_calculating->to_json_hash();
753         $json->{'engine'} = $engine->{'id'};
754         if (defined($remoteglotconf::engine_url)) {
755                 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
756         }
757         if (defined($remoteglotconf::engine_details)) {
758                 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
759         }
760         if (defined($remoteglotconf::move_source)) {
761                 $json->{'move_source'} = $remoteglotconf::move_source;
762         }
763         if (defined($remoteglotconf::move_source_url)) {
764                 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
765         }
766         $json->{'score'} = long_score($info, $pos_calculating, '');
767         $json->{'short_score'} = short_score($info, $pos_calculating, '');
768         $json->{'plot_score'} = plot_score($info, $pos_calculating, '');
769         $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
770
771         $json->{'nodes'} = $info->{'nodes'};
772         $json->{'nps'} = $info->{'nps'};
773         $json->{'depth'} = $info->{'depth'};
774         $json->{'tbhits'} = $info->{'tbhits'};
775         $json->{'seldepth'} = $info->{'seldepth'};
776         $json->{'tablebase'} = $info->{'tablebase'};
777
778         $json->{'pv_uci'} = $info->{'pv'};  # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
779         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
780
781         my %refutation_lines = ();
782         my @refutation_lines = ();
783         if (defined($engine2)) {
784                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
785                         my $info = $engine2->{'info'};
786                         my $pretty_move = "";
787                         my @pretty_pv = ();
788                         last if (!exists($info->{'pv' . $mpv}));
789
790                         eval {
791                                 my $pv = $info->{'pv' . $mpv};
792                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
793                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
794                                 $refutation_lines{$pv->[0]} = {
795                                         sort_key => $pretty_move,
796                                         depth => $info->{'depth' . $mpv},
797                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
798                                         pretty_score => short_score($info, $pos_calculating, $mpv),
799                                         pretty_move => $pretty_move,
800                                         pv_pretty => \@pretty_pv,
801                                 };
802                         };
803                 }
804         }
805         $json->{'refutation_lines'} = \%refutation_lines;
806
807         # Piece together historic score information, to the degree we have it.
808         if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
809                 my %score_history = ();
810
811                 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
812                 my $pos = Position->start_pos('white', 'black');
813                 my $halfmove_num = 0;
814                 for my $move (@{$pos_calculating->{'pretty_history'}}) {
815                         my $id = id_for_pos($pos, $halfmove_num);
816                         my $ref = $dbh->selectrow_hashref($q, undef, $id);
817                         if (defined($ref)) {
818                                 $score_history{$halfmove_num} = [
819                                         $ref->{'plot_score'},
820                                         $ref->{'short_score'}
821                                 ];
822                         }
823                         ++$halfmove_num;
824                         ($pos) = $pos->make_pretty_move($move);
825                 }
826                 $q->finish;
827
828                 # If at any point we are missing 10 consecutive moves,
829                 # truncate the history there. This is so we don't get into
830                 # a situation where we e.g. start analyzing at move 45,
831                 # but we have analysis for 1. e4 from some completely different game
832                 # and thus show a huge hole.
833                 my $consecutive_missing = 0;
834                 my $truncate_until = 0;
835                 for (my $i = $halfmove_num; $i --> 0; ) {
836                         if ($consecutive_missing >= 10) {
837                                 delete $score_history{$i};
838                                 next;
839                         }
840                         if (exists($score_history{$i})) {
841                                 $consecutive_missing = 0;
842                         } else {
843                                 ++$consecutive_missing;
844                         }
845                 }
846
847                 $json->{'score_history'} = \%score_history;
848         }
849
850         # Give out a list of other games going on. (Empty is fine.)
851         if (!$historic_json_only) {
852                 my @games = ();
853
854                 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
855                 $q->execute;
856                 while (my $ref = $q->fetchrow_hashref) {
857                         eval {
858                                 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
859                                 my $other_game_json = JSON::XS::decode_json($other_game_contents);
860
861                                 die "Missing position" if (!exists($other_game_json->{'position'}));
862                                 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
863                                 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
864
865                                 push @games, {
866                                         id => $ref->{'id'},
867                                         name => "$white–$black",
868                                         url => $ref->{'url'}
869                                 };
870                         };
871                         if ($@) {
872                                 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
873                         }
874                 }
875
876                 if (scalar @games > 0) {
877                         $json->{'games'} = \@games;
878                 }
879         }
880
881         my $json_enc = JSON::XS->new;
882         $json_enc->canonical(1);
883         my $encoded = $json_enc->encode($json);
884         unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
885                 (defined($last_written_json) && $last_written_json eq $encoded)) {
886                 atomic_set_contents($remoteglotconf::json_output, $encoded);
887                 $last_written_json = $encoded;
888         }
889
890         if (exists($pos_calculating->{'pretty_history'}) &&
891             defined($remoteglotconf::json_history_dir)) {
892                 my $id = id_for_pos($pos_calculating);
893                 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
894
895                 # Overwrite old analysis (assuming it exists at all) if we're
896                 # using a different engine, or if we've calculated deeper.
897                 # nodes is used as a tiebreaker. Don't bother about Multi-PV
898                 # data; it's not that important.
899                 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
900                 my $new_depth = $json->{'depth'} // 0;
901                 my $new_nodes = $json->{'nodes'} // 0;
902                 if (!defined($old_engine) ||
903                     $old_engine ne $json->{'engine'}{'name'} ||
904                     $new_depth > $old_depth ||
905                     ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
906                         atomic_set_contents($filename, $encoded);
907                         if (defined($json->{'plot_score'})) {
908                                 $dbh->do('INSERT INTO scores (id, plot_score, short_score, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
909                                          '    ON CONFLICT (id) DO UPDATE SET ' .
910                                          '        plot_score=EXCLUDED.plot_score, ' .
911                                          '        short_score=EXCLUDED.short_score, ' .
912                                          '        engine=EXCLUDED.engine, ' .
913                                          '        depth=EXCLUDED.depth, ' .
914                                          '        nodes=EXCLUDED.nodes',
915                                         undef,
916                                         $id, $json->{'plot_score'}, $json->{'short_score'},
917                                         $json->{'engine'}{'name'}, $new_depth, $new_nodes);
918                         }
919                 }
920         }
921 }
922
923 sub atomic_set_contents {
924         my ($filename, $contents) = @_;
925
926         open my $fh, ">", $filename . ".tmp"
927                 or return;
928         print $fh $contents;
929         close $fh;
930         rename($filename . ".tmp", $filename);
931 }
932
933 sub id_for_pos {
934         my ($pos, $halfmove_num) = @_;
935
936         $halfmove_num //= scalar @{$pos->{'pretty_history'}};
937         (my $fen = $pos->fen()) =~ tr,/ ,-_,;
938         return "move$halfmove_num-$fen";
939 }
940
941 sub get_json_analysis_stats {
942         my $id = shift;
943         my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
944         if (defined($ref)) {
945                 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
946         } else {
947                 return ('', 0, 0);
948         }
949 }
950
951 sub uciprint {
952         my ($engine, $msg) = @_;
953         $engine->print($msg);
954         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
955 }
956
957 sub short_score {
958         my ($info, $pos, $mpv) = @_;
959
960         my $invert = ($pos->{'toplay'} eq 'B');
961         if (defined($info->{'score_mate' . $mpv})) {
962                 if ($invert) {
963                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
964                 } else {
965                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
966                 }
967         } else {
968                 if (exists($info->{'score_cp' . $mpv})) {
969                         my $score = $info->{'score_cp' . $mpv} * 0.01;
970                         if ($score == 0) {
971                                 if ($info->{'tablebase'}) {
972                                         return "TB draw";
973                                 } else {
974                                         return " 0.00";
975                                 }
976                         }
977                         if ($invert) {
978                                 $score = -$score;
979                         }
980                         return sprintf "%+5.2f", $score;
981                 }
982         }
983
984         return undef;
985 }
986
987 sub score_sort_key {
988         my ($info, $pos, $mpv, $invert) = @_;
989
990         if (defined($info->{'score_mate' . $mpv})) {
991                 my $mate = $info->{'score_mate' . $mpv};
992                 my $score;
993                 if ($mate > 0) {
994                         # Side to move mates
995                         $score = 99999 - $mate;
996                 } else {
997                         # Side to move is getting mated (note the double negative for $mate)
998                         $score = -99999 - $mate;
999                 }
1000                 if ($invert) {
1001                         $score = -$score;
1002                 }
1003                 return $score;
1004         } else {
1005                 if (exists($info->{'score_cp' . $mpv})) {
1006                         my $score = $info->{'score_cp' . $mpv};
1007                         if ($invert) {
1008                                 $score = -$score;
1009                         }
1010                         return $score;
1011                 }
1012         }
1013
1014         return undef;
1015 }
1016
1017 sub long_score {
1018         my ($info, $pos, $mpv) = @_;
1019
1020         if (defined($info->{'score_mate' . $mpv})) {
1021                 my $mate = $info->{'score_mate' . $mpv};
1022                 if ($pos->{'toplay'} eq 'B') {
1023                         $mate = -$mate;
1024                 }
1025                 if ($mate > 0) {
1026                         return sprintf "White mates in %u", $mate;
1027                 } else {
1028                         return sprintf "Black mates in %u", -$mate;
1029                 }
1030         } else {
1031                 if (exists($info->{'score_cp' . $mpv})) {
1032                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1033                         if ($score == 0) {
1034                                 if ($info->{'tablebase'}) {
1035                                         return "Theoretical draw";
1036                                 } else {
1037                                         return "Score:  0.00";
1038                                 }
1039                         }
1040                         if ($pos->{'toplay'} eq 'B') {
1041                                 $score = -$score;
1042                         }
1043                         return sprintf "Score: %+5.2f", $score;
1044                 }
1045         }
1046
1047         return undef;
1048 }
1049
1050 # For graphs; a single number in centipawns, capped at +/- 500.
1051 sub plot_score {
1052         my ($info, $pos, $mpv) = @_;
1053
1054         my $invert = ($pos->{'toplay'} eq 'B');
1055         if (defined($info->{'score_mate' . $mpv})) {
1056                 my $mate = $info->{'score_mate' . $mpv};
1057                 if ($invert) {
1058                         $mate = -$mate;
1059                 }
1060                 if ($mate > 0) {
1061                         return 500;
1062                 } else {
1063                         return -500;
1064                 }
1065         } else {
1066                 if (exists($info->{'score_cp' . $mpv})) {
1067                         my $score = $info->{'score_cp' . $mpv};
1068                         if ($invert) {
1069                                 $score = -$score;
1070                         }
1071                         $score = 500 if ($score > 500);
1072                         $score = -500 if ($score < -500);
1073                         return int($score);
1074                 }
1075         }
1076
1077         return undef;
1078 }
1079
1080 my %book_cache = ();
1081 sub book_info {
1082         my ($fen, $board, $toplay) = @_;
1083
1084         if (exists($book_cache{$fen})) {
1085                 return $book_cache{$fen};
1086         }
1087
1088         my $ret = `./booklook $fen`;
1089         return "" if ($ret =~ /Not found/ || $ret eq '');
1090
1091         my @moves = ();
1092
1093         for my $m (split /\n/, $ret) {
1094                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1095
1096                 my $pmove;
1097                 if ($move eq '')  {
1098                         $pmove = '(current)';
1099                 } else {
1100                         ($pmove) = prettyprint_pv_no_cache($board, $move);
1101                         $pmove .= $annotation;
1102                 }
1103
1104                 my $score;
1105                 if ($toplay eq 'W') {
1106                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1107                 } else {
1108                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1109                 }
1110                 my $n = $win + $draw + $lose;
1111                 
1112                 my $percent;
1113                 if ($n == 0) {
1114                         $percent = "     ";
1115                 } else {
1116                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1117                 }
1118
1119                 push @moves, [ $pmove, $n, $percent, $rating ];
1120         }
1121
1122         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1123         
1124         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1125         for my $m (@moves) {
1126                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1127         }
1128
1129         return $text;
1130 }
1131
1132 sub extract_clock {
1133         my ($pgn, $pos) = @_;
1134
1135         # Look for extended PGN clock tags.
1136         my $tags = $pgn->tags;
1137         if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1138                 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1139                 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1140                 return;
1141         }
1142
1143         # Look for TCEC-style time comments.
1144         my $moves = $pgn->moves;
1145         my $comments = $pgn->comments;
1146         my $last_black_move = int((scalar @$moves) / 2);
1147         my $last_white_move = int((1 + scalar @$moves) / 2);
1148
1149         my $black_key = $last_black_move . "b";
1150         my $white_key = $last_white_move . "w";
1151
1152         if (exists($comments->{$white_key}) &&
1153             exists($comments->{$black_key}) &&
1154             $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1155             $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1156                 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1157                 $pos->{'white_clock'} = hms_to_sec($1);
1158                 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1159                 $pos->{'black_clock'} = hms_to_sec($1);
1160                 return;
1161         }
1162
1163         delete $pos->{'white_clock'};
1164         delete $pos->{'black_clock'};
1165 }
1166
1167 sub hms_to_sec {
1168         my $hms = shift;
1169         return undef if (!defined($hms));
1170         $hms =~ /(\d+):(\d+):(\d+)/;
1171         return $1 * 3600 + $2 * 60 + $3;
1172 }
1173
1174 sub find_clock_start {
1175         my ($pos, $prev_pos) = @_;
1176
1177         # If the game is over, the clock is stopped.
1178         if (exists($pos->{'result'}) &&
1179             ($pos->{'result'} eq '1-0' ||
1180              $pos->{'result'} eq '1/2-1/2' ||
1181              $pos->{'result'} eq '0-1')) {
1182                 return;
1183         }
1184
1185         # When we don't have any moves, we assume the clock hasn't started yet.
1186         if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1187                 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1188                         &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1189                 }
1190                 return;
1191         }
1192
1193         # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1194         # The history is needed for id_for_pos.
1195         if (!exists($pos->{'pretty_history'})) {
1196                 return;
1197         }
1198
1199         my $id = id_for_pos($pos);
1200         my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1201         if (defined($clock_info)) {
1202                 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1203                 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1204                 if ($pos->{'toplay'} eq 'W') {
1205                         $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1206                 } else {
1207                         $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1208                 }
1209                 return;
1210         }
1211
1212         # OK, we haven't seen this position before, so we assume the move
1213         # happened right now.
1214
1215         # See if we should do our own clock management (ie., clock information
1216         # is spurious or non-existent).
1217         if (defined($remoteglotconf::adjust_clocks_before_move)) {
1218                 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1219                 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1220                 if (defined($prev_pos->{'white_clock_target'})) {
1221                         $wc = $prev_pos->{'white_clock_target'} - time;
1222                 }
1223                 if (defined($prev_pos->{'black_clock_target'})) {
1224                         $bc = $prev_pos->{'black_clock_target'} - time;
1225                 }
1226                 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1227                 $pos->{'white_clock'} = $wc;
1228                 $pos->{'black_clock'} = $bc;
1229         }
1230
1231         my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1232         if (!exists($pos->{$key})) {
1233                 # No clock information.
1234                 return;
1235         }
1236         my $time_left = $pos->{$key};
1237         my ($white_clock_target, $black_clock_target);
1238         if ($pos->{'toplay'} eq 'W') {
1239                 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1240         } else {
1241                 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1242         }
1243         local $dbh->{AutoCommit} = 0;
1244         $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1245         $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1246                 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1247         $dbh->commit;
1248 }
1249
1250 sub schedule_tb_lookup {
1251         return if (!defined($remoteglotconf::tb_serial_key));
1252         my $pos = $pos_waiting // $pos_calculating;
1253         return if (exists($tb_cache{$pos->fen()}));
1254
1255         # If there's more than seven pieces, there's not going to be an answer,
1256         # so don't bother.
1257         return if ($pos->num_pieces() > 7);
1258
1259         # Max one at a time. If it's still relevant when it returns,
1260         # schedule_tb_lookup() will be called again.
1261         return if ($tb_lookup_running);
1262
1263         $tb_lookup_running = 1;
1264         my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1265                 $remoteglotconf::tb_serial_key .
1266                 '&auth.password=aquarium&type=0&fen=' . 
1267                 URI::Escape::uri_escape($pos->fen());
1268         print TBLOG "Downloading $url...\n";
1269         AnyEvent::HTTP::http_get($url, sub {
1270                 handle_tb_lookup_return(@_, $pos, $pos->fen());
1271         });
1272 }
1273
1274 sub handle_tb_lookup_return {
1275         my ($body, $header, $pos, $fen) = @_;
1276         print TBLOG "Response for [$fen]:\n";
1277         print TBLOG $header . "\n\n";
1278         print TBLOG $body . "\n\n";
1279         eval {
1280                 my $response = JSON::XS::decode_json($body);
1281                 if ($response->{'ErrorCode'} != 0) {
1282                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1283                 }
1284                 my $state = $response->{'Response'}{'StateString'};
1285                 if ($state eq 'COMPLETE') {
1286                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1287                         if (!defined($pgn) || !$pgn->read_game()) {
1288                                 warn "Error in parsing PGN\n";
1289                         } else {
1290                                 $pgn->quick_parse_game;
1291                                 my $pvpos = $pos;
1292                                 my $moves = $pgn->moves;
1293                                 my @uci_moves = ();
1294                                 for my $move (@$moves) {
1295                                         my $uci_move;
1296                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1297                                         push @uci_moves, $uci_move;
1298                                 }
1299                                 $tb_cache{$fen} = {
1300                                         result => $pgn->result,
1301                                         pv => \@uci_moves,
1302                                         score => $response->{'Response'}{'Score'},
1303                                 };
1304                                 output();
1305                         }
1306                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1307                         # Try again in a second. Note that if we have changed
1308                         # position in the meantime, we might query a completely
1309                         # different position! But that's fine.
1310                 } else {
1311                         die "Unknown response state " . $state;
1312                 }
1313
1314                 # Wait a second before we schedule another one.
1315                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1316                         $tb_lookup_running = 0;
1317                         schedule_tb_lookup();
1318                 });
1319         };
1320         if ($@) {
1321                 warn "Error in tablebase lookup: $@";
1322
1323                 # Don't try this one again, but don't block new lookups either.
1324                 $tb_lookup_running = 0;
1325         }
1326 }
1327
1328 sub open_engine {
1329         my ($cmdline, $tag, $cb) = @_;
1330         return undef if (!defined($cmdline));
1331         return Engine->open($cmdline, $tag, $cb);
1332 }
1333
1334 sub col_letter_to_num {
1335         return ord(shift) - ord('a');
1336 }
1337
1338 sub row_letter_to_num {
1339         return 7 - (ord(shift) - ord('1'));
1340 }
1341
1342 sub parse_uci_move {
1343         my $move = shift;
1344         my $from_col = col_letter_to_num(substr($move, 0, 1));
1345         my $from_row = row_letter_to_num(substr($move, 1, 1));
1346         my $to_col   = col_letter_to_num(substr($move, 2, 1));
1347         my $to_row   = row_letter_to_num(substr($move, 3, 1));
1348         my $promo    = substr($move, 4, 1);
1349         return ($from_row, $from_col, $to_row, $to_col, $promo);
1350 }