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