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