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