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