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