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