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