Fix a castling edge case in Chess960 positions where the kings start on the e-file...
[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 $pv = shift @pvs;
539         my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
540         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
541         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
542 }
543
544 sub prettyprint_pv {
545         my ($pos, @pvs) = @_;
546
547         my $cachekey = join('', @pvs);
548         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
549                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
550         } else {
551                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
552                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
553                 return @res;
554         }
555 }
556
557 my %tbprobe_cache = ();
558
559 sub complete_using_tbprobe {
560         my ($pos, $info, $mpv) = @_;
561
562         # We need Fathom installed to do standalone TB probes.
563         return if (!defined($remoteglotconf::fathom_cmdline));
564
565         # If we already have a mate, don't bother; in some cases, it would even be
566         # better than a tablebase score.
567         return if defined($info->{'score_mate' . $mpv});
568
569         # If we have a draw or near-draw score, there's also not much interesting
570         # we could add from a tablebase. We only really want mates.
571         return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
572
573         # Run through the PV until we are at a 6-man position.
574         # TODO: We could in theory only have 5-man data.
575         my @pv = @{$info->{'pv' . $mpv}};
576         my $key = $pos->fen() . " " . join('', @pv);
577         my @moves = ();
578         if (exists($tbprobe_cache{$key})) {
579                 @moves = @{$tbprobe_cache{$key}};
580         } else {
581                 if ($mpv ne '') {
582                         # Force doing at least one move of the PV.
583                         my $move = shift @pv;
584                         push @moves, $move;
585                         $pos = $pos->make_move(parse_uci_move($move));
586                 }
587
588                 while ($pos->num_pieces() > 7 && $#pv > -1) {
589                         my $move = shift @pv;
590                         push @moves, $move;
591                         $pos = $pos->make_move(parse_uci_move($move));
592                 }
593
594                 return if ($pos->num_pieces() > 7);
595
596                 my $fen = $pos->fen();
597                 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
598                 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
599                 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
600                 $pgn->quick_parse_game;
601                 $info->{'pv' . $mpv} = \@moves;
602
603                 # Splice the PV from the tablebase onto what we have so far.
604                 for my $move (@{$pgn->moves}) {
605                         last if $move eq '#';
606                         last if $move eq '1-0';
607                         last if $move eq '0-1';
608                         last if $move eq '1/2-1/2';
609                         my $uci_move;
610                         ($pos, $uci_move) = $pos->make_pretty_move($move);
611                         push @moves, $uci_move;
612                 }
613
614                 $tbprobe_cache{$key} = \@moves;
615         }
616
617         $info->{'pv' . $mpv} = \@moves;
618
619         my $matelen = int((1 + scalar @moves) / 2);
620         if ((scalar @moves) % 2 == 0) {
621                 $info->{'score_mate' . $mpv} = -$matelen;
622         } else {
623                 $info->{'score_mate' . $mpv} = $matelen;
624         }
625 }
626
627 sub output {
628         #return;
629
630         return if (!defined($pos_calculating));
631
632         # Don't update too often.
633         my $age = Time::HiRes::tv_interval($latest_update);
634         if ($age < $remoteglotconf::update_max_interval) {
635                 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
636                 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
637                 return;
638         }
639         
640         my $info = $engine->{'info'};
641
642         #
643         # If we have tablebase data from a previous lookup, replace the
644         # engine data with the data from the tablebase.
645         #
646         my $fen = $pos_calculating->fen();
647         if (exists($tb_cache{$fen})) {
648                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
649                         delete $info->{$key . '1'};
650                         delete $info->{$key};
651                 }
652                 $info->{'nodes'} = 0;
653                 $info->{'nps'} = 0;
654                 $info->{'depth'} = 0;
655                 $info->{'seldepth'} = 0;
656                 $info->{'tbhits'} = 0;
657
658                 my $t = $tb_cache{$fen};
659                 my $pv = $t->{'pv'};
660                 my $matelen = int((1 + $t->{'score'}) / 2);
661                 if ($t->{'result'} eq '1/2-1/2') {
662                         $info->{'score_cp'} = 0;
663                 } elsif ($t->{'result'} eq '1-0') {
664                         if ($pos_calculating->{'toplay'} eq 'B') {
665                                 $info->{'score_mate'} = -$matelen;
666                         } else {
667                                 $info->{'score_mate'} = $matelen;
668                         }
669                 } else {
670                         if ($pos_calculating->{'toplay'} eq 'B') {
671                                 $info->{'score_mate'} = $matelen;
672                         } else {
673                                 $info->{'score_mate'} = -$matelen;
674                         }
675                 }
676                 $info->{'pv'} = $pv;
677                 $info->{'tablebase'} = 1;
678         } else {
679                 $info->{'tablebase'} = 0;
680         }
681         
682         #
683         # Some programs _always_ report MultiPV, even with only one PV.
684         # In this case, we simply use that data as if MultiPV was never
685         # specified.
686         #
687         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
688                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
689                         if (exists($info->{$key . '1'})) {
690                                 $info->{$key} = $info->{$key . '1'};
691                         } else {
692                                 delete $info->{$key};
693                         }
694                 }
695         }
696         
697         #
698         # Check the PVs first. if they're invalid, just wait, as our data
699         # is most likely out of sync. This isn't a very good solution, as
700         # it can frequently miss stuff, but it's good enough for most users.
701         #
702         eval {
703                 my $dummy;
704                 if (exists($info->{'pv'})) {
705                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
706                 }
707         
708                 my $mpv = 1;
709                 while (exists($info->{'pv' . $mpv})) {
710                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
711                         ++$mpv;
712                 }
713         };
714         if ($@) {
715                 $engine->{'info'} = {};
716                 return;
717         }
718
719         # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
720         if (exists($info->{'pv'})) {
721                 complete_using_tbprobe($pos_calculating, $info, '');
722         }
723
724         my $mpv = 1;
725         while (exists($info->{'pv' . $mpv})) {
726                 complete_using_tbprobe($pos_calculating, $info, $mpv);
727                 ++$mpv;
728         }
729
730         output_screen();
731         output_json(0);
732         $latest_update = [Time::HiRes::gettimeofday];
733 }
734
735 sub output_screen {
736         my $info = $engine->{'info'};
737         my $id = $engine->{'id'};
738
739         my $text = 'Analysis';
740         if ($pos_calculating->{'last_move'} ne 'none') {
741                 if ($pos_calculating->{'toplay'} eq 'W') {
742                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
743                 } else {
744                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
745                 }
746                 if (exists($id->{'name'})) {
747                         $text .= ',';
748                 }
749         }
750
751         if (exists($id->{'name'})) {
752                 $text .= " by $id->{'name'}:\n\n";
753         } else {
754                 $text .= ":\n\n";
755         }
756
757         return unless (exists($pos_calculating->{'board'}));
758                 
759         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
760                 # multi-PV
761                 my $mpv = 1;
762                 while (exists($info->{'pv' . $mpv})) {
763                         $text .= sprintf "  PV%2u", $mpv;
764                         my $score = short_score($info, $pos_calculating, $mpv);
765                         $text .= "  ($score)" if (defined($score));
766
767                         my $tbhits = '';
768                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
769                                 if ($info->{'tbhits' . $mpv} == 1) {
770                                         $tbhits = ", 1 tbhit";
771                                 } else {
772                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
773                                 }
774                         }
775
776                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
777                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
778                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
779                         }
780
781                         $text .= ":\n";
782                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
783                         $text .= "\n";
784                         ++$mpv;
785                 }
786         } else {
787                 # single-PV
788                 my $score = long_score($info, $pos_calculating, '');
789                 $text .= "  $score\n" if defined($score);
790                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
791                 $text .=  "\n";
792
793                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
794                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
795                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
796                 }
797                 if (exists($info->{'seldepth'})) {
798                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
799                 }
800                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
801                         if ($info->{'tbhits'} == 1) {
802                                 $text .= ", one Syzygy hit";
803                         } else {
804                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
805                         }
806                 }
807                 $text .= "\n\n";
808         }
809
810         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
811
812         my @refutation_lines = ();
813         if (defined($engine2)) {
814                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
815                         my $info = $engine2->{'info'};
816                         last if (!exists($info->{'pv' . $mpv}));
817                         eval {
818                                 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
819                                 my $pv = $info->{'pv' . $mpv};
820                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
821                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
822                                 if (scalar @pretty_pv > 5) {
823                                         @pretty_pv = @pretty_pv[0..4];
824                                         push @pretty_pv, "...";
825                                 }
826                                 my $key = $pretty_move;
827                                 my $line = sprintf("  %-6s %6s %3s  %s",
828                                         $pretty_move,
829                                         short_score($info, $pos_calculating_second_engine, $mpv),
830                                         "d" . $info->{'depth' . $mpv},
831                                         join(', ', @pretty_pv));
832                                 push @refutation_lines, [ $key, $line ];
833                         };
834                 }
835         }
836
837         if ($#refutation_lines >= 0) {
838                 $text .= "Shallow search of all legal moves:\n\n";
839                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
840                         $text .= $line->[1] . "\n";
841                 }
842                 $text .= "\n\n";        
843         }       
844
845         if ($last_text ne $text) {
846                 print "\e[H\e[2J"; # clear the screen
847                 print $text;
848                 $last_text = $text;
849         }
850 }
851
852 sub output_json {
853         my $historic_json_only = shift;
854         my $info = $engine->{'info'};
855
856         my $json = {};
857         $json->{'position'} = $pos_calculating->to_json_hash();
858         $json->{'engine'} = $engine->{'id'};
859         if (defined($remoteglotconf::engine_url)) {
860                 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
861         }
862         if (defined($remoteglotconf::engine_details)) {
863                 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
864         }
865         my @grpc_backends = ();
866         if (defined($remoteglotconf::engine_grpc_backend)) {
867                 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
868         }
869         if (defined($remoteglotconf::engine2_grpc_backend)) {
870                 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
871         }
872         $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
873         if (defined($remoteglotconf::move_source)) {
874                 $json->{'move_source'} = $remoteglotconf::move_source;
875         }
876         if (defined($remoteglotconf::move_source_url)) {
877                 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
878         }
879         $json->{'score'} = score_digest($info, $pos_calculating, '');
880         $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
881
882         $json->{'nodes'} = $info->{'nodes'};
883         $json->{'nps'} = $info->{'nps'};
884         $json->{'depth'} = $info->{'depth'};
885         $json->{'tbhits'} = $info->{'tbhits'};
886         $json->{'seldepth'} = $info->{'seldepth'};
887         $json->{'tablebase'} = $info->{'tablebase'};
888         $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
889
890         my %refutation_lines = ();
891         my @refutation_lines = ();
892         if (defined($engine2)) {
893                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
894                         my $info = $engine2->{'info'};
895                         my $pretty_move = "";
896                         my @pretty_pv = ();
897                         last if (!exists($info->{'pv' . $mpv}));
898
899                         eval {
900                                 complete_using_tbprobe($pos_calculating, $info, $mpv);
901                                 my $pv = $info->{'pv' . $mpv};
902                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
903                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
904                                 $refutation_lines{$pretty_move} = {
905                                         depth => $info->{'depth' . $mpv},
906                                         score => score_digest($info, $pos_calculating, $mpv),
907                                         move => $pretty_move,
908                                         pv => \@pretty_pv,
909                                 };
910                         };
911                 }
912         }
913         $json->{'refutation_lines'} = \%refutation_lines;
914
915         # Piece together historic score information, to the degree we have it.
916         if (!$historic_json_only && exists($pos_calculating->{'history'})) {
917                 my %score_history = ();
918
919                 local $dbh->{AutoCommit} = 0;
920                 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
921                 my $pos;
922                 if (exists($pos_calculating->{'start_fen'})) {
923                         $pos = Position->from_fen($pos_calculating->{'start_fen'});
924                 } else {
925                         $pos = Position->start_pos('white', 'black');
926                 }
927                 $pos->{'chess960'} = $pos_calculating->{'chess960'};
928                 my $halfmove_num = 0;
929                 for my $move (@{$pos_calculating->{'history'}}) {
930                         my $id = id_for_pos($pos, $halfmove_num);
931                         my $ref = $dbh->selectrow_hashref($q, undef, $id);
932                         if (defined($ref)) {
933                                 $score_history{$halfmove_num} = [
934                                         $ref->{'score_type'},
935                                         $ref->{'score_value'}
936                                 ];
937                         }
938                         ++$halfmove_num;
939                         ($pos) = $pos->make_pretty_move($move);
940                 }
941                 $q->finish;
942                 $dbh->commit;
943
944                 # If at any point we are missing 10 consecutive moves,
945                 # truncate the history there. This is so we don't get into
946                 # a situation where we e.g. start analyzing at move 45,
947                 # but we have analysis for 1. e4 from some completely different game
948                 # and thus show a huge hole.
949                 my $consecutive_missing = 0;
950                 my $truncate_until = 0;
951                 for (my $i = $halfmove_num; $i --> 0; ) {
952                         if ($consecutive_missing >= 10) {
953                                 delete $score_history{$i};
954                                 next;
955                         }
956                         if (exists($score_history{$i})) {
957                                 $consecutive_missing = 0;
958                         } else {
959                                 ++$consecutive_missing;
960                         }
961                 }
962
963                 $json->{'score_history'} = \%score_history;
964         }
965
966         # Give out a list of other games going on. (Empty is fine.)
967         # TODO: Don't bother reading our own file, the data will be stale anyway.
968         if (!$historic_json_only) {
969                 my @games = ();
970
971                 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
972                 $q->execute;
973                 while (my $ref = $q->fetchrow_hashref) {
974                         eval {
975                                 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
976                                 my $other_game_json = JSON::XS::decode_json($other_game_contents);
977
978                                 die "Missing position" if (!exists($other_game_json->{'position'}));
979                                 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
980                                 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
981
982                                 my $game = {
983                                         id => $ref->{'id'},
984                                         name => "$white–$black",
985                                         url => $ref->{'url'},
986                                         hashurl => $ref->{'hash_url'},
987                                 };
988                                 if (defined($other_game_json->{'position'}{'result'})) {
989                                         $game->{'result'} = $other_game_json->{'position'}{'result'};
990                                 } else {
991                                         $game->{'score'} = $other_game_json->{'score'};
992                                 }
993                                 push @games, $game;
994                         };
995                         if ($@) {
996                                 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
997                         }
998                 }
999
1000                 if (scalar @games > 0) {
1001                         $json->{'games'} = \@games;
1002                 }
1003         }
1004
1005         my $json_enc = JSON::XS->new;
1006         $json_enc->canonical(1);
1007         my $encoded = $json_enc->encode($json);
1008         unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
1009                 (defined($last_written_json) && $last_written_json eq $encoded)) {
1010                 atomic_set_contents($remoteglotconf::json_output, $encoded);
1011                 $last_written_json = $encoded;
1012         }
1013
1014         if (exists($pos_calculating->{'history'}) &&
1015             defined($remoteglotconf::json_history_dir)) {
1016                 my $id = id_for_pos($pos_calculating);
1017                 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
1018
1019                 # Overwrite old analysis (assuming it exists at all) if we're
1020                 # using a different engine, or if we've calculated deeper.
1021                 # nodes is used as a tiebreaker. Don't bother about Multi-PV
1022                 # data; it's not that important.
1023                 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1024                 my $new_depth = $json->{'depth'} // 0;
1025                 my $new_nodes = $json->{'nodes'} // 0;
1026                 if (!defined($old_engine) ||
1027                     $old_engine ne $json->{'engine'}{'name'} ||
1028                     $new_depth > $old_depth ||
1029                     ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1030                         atomic_set_contents($filename, $encoded);
1031                         if (defined($json->{'score'})) {
1032                                 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1033                                          '    ON CONFLICT (id) DO UPDATE SET ' .
1034                                          '        score_type=EXCLUDED.score_type, ' .
1035                                          '        score_value=EXCLUDED.score_value, ' .
1036                                          '        engine=EXCLUDED.engine, ' .
1037                                          '        depth=EXCLUDED.depth, ' .
1038                                          '        nodes=EXCLUDED.nodes',
1039                                         undef,
1040                                         $id, $json->{'score'}[0], $json->{'score'}[1],
1041                                         $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1042                         }
1043                 }
1044         }
1045 }
1046
1047 sub atomic_set_contents {
1048         my ($filename, $contents) = @_;
1049
1050         open my $fh, ">", $filename . ".tmp"
1051                 or return;
1052         print $fh $contents;
1053         close $fh;
1054         rename($filename . ".tmp", $filename);
1055 }
1056
1057 sub id_for_pos {
1058         my ($pos, $halfmove_num) = @_;
1059
1060         $halfmove_num //= scalar @{$pos->{'history'}};
1061         (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1062         return "move$halfmove_num-$fen";
1063 }
1064
1065 sub get_json_analysis_stats {
1066         my $id = shift;
1067         my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1068         if (defined($ref)) {
1069                 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1070         } else {
1071                 return ('', 0, 0);
1072         }
1073 }
1074
1075 sub uciprint {
1076         my ($engine, $msg) = @_;
1077         $engine->print($msg);
1078         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1079 }
1080
1081 sub short_score {
1082         my ($info, $pos, $mpv) = @_;
1083
1084         my $invert = ($pos->{'toplay'} eq 'B');
1085         if (defined($info->{'score_mate' . $mpv})) {
1086                 if ($invert) {
1087                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1088                 } else {
1089                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
1090                 }
1091         } else {
1092                 if (exists($info->{'score_cp' . $mpv})) {
1093                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1094                         if ($score == 0) {
1095                                 if ($info->{'tablebase'}) {
1096                                         return "TB draw";
1097                                 } else {
1098                                         return " 0.00";
1099                                 }
1100                         }
1101                         if ($invert) {
1102                                 $score = -$score;
1103                         }
1104                         return sprintf "%+5.2f", $score;
1105                 }
1106         }
1107
1108         return undef;
1109 }
1110
1111 # Sufficient for computing long_score, short_score, plot_score and
1112 # (with side-to-play information) score_sort_key.
1113 sub score_digest {
1114         my ($info, $pos, $mpv) = @_;
1115
1116         if (defined($info->{'score_mate' . $mpv})) {
1117                 my $mate = $info->{'score_mate' . $mpv};
1118                 if ($pos->{'toplay'} eq 'B') {
1119                         $mate = -$mate;
1120                 }
1121                 return ['m', $mate];
1122         } else {
1123                 if (exists($info->{'score_cp' . $mpv})) {
1124                         my $score = $info->{'score_cp' . $mpv};
1125                         if ($pos->{'toplay'} eq 'B') {
1126                                 $score = -$score;
1127                         }
1128                         if ($score == 0 && $info->{'tablebase'}) {
1129                                 return ['d', undef];
1130                         } else {
1131                                 return ['cp', int($score)];
1132                         }
1133                 }
1134         }
1135
1136         return undef;
1137 }
1138
1139 sub long_score {
1140         my ($info, $pos, $mpv) = @_;
1141
1142         if (defined($info->{'score_mate' . $mpv})) {
1143                 my $mate = $info->{'score_mate' . $mpv};
1144                 if ($pos->{'toplay'} eq 'B') {
1145                         $mate = -$mate;
1146                 }
1147                 if ($mate > 0) {
1148                         return sprintf "White mates in %u", $mate;
1149                 } else {
1150                         return sprintf "Black mates in %u", -$mate;
1151                 }
1152         } else {
1153                 if (exists($info->{'score_cp' . $mpv})) {
1154                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1155                         if ($score == 0) {
1156                                 if ($info->{'tablebase'}) {
1157                                         return "Theoretical draw";
1158                                 } else {
1159                                         return "Score:  0.00";
1160                                 }
1161                         }
1162                         if ($pos->{'toplay'} eq 'B') {
1163                                 $score = -$score;
1164                         }
1165                         return sprintf "Score: %+5.2f", $score;
1166                 }
1167         }
1168
1169         return undef;
1170 }
1171
1172 # For graphs; a single number in centipawns, capped at +/- 500.
1173 sub plot_score {
1174         my ($info, $pos, $mpv) = @_;
1175
1176         my $invert = ($pos->{'toplay'} eq 'B');
1177         if (defined($info->{'score_mate' . $mpv})) {
1178                 my $mate = $info->{'score_mate' . $mpv};
1179                 if ($invert) {
1180                         $mate = -$mate;
1181                 }
1182                 if ($mate > 0) {
1183                         return 500;
1184                 } else {
1185                         return -500;
1186                 }
1187         } else {
1188                 if (exists($info->{'score_cp' . $mpv})) {
1189                         my $score = $info->{'score_cp' . $mpv};
1190                         if ($invert) {
1191                                 $score = -$score;
1192                         }
1193                         $score = 500 if ($score > 500);
1194                         $score = -500 if ($score < -500);
1195                         return int($score);
1196                 }
1197         }
1198
1199         return undef;
1200 }
1201
1202 my %book_cache = ();
1203 sub book_info {
1204         my ($fen, $board, $toplay) = @_;
1205
1206         if (exists($book_cache{$fen})) {
1207                 return $book_cache{$fen};
1208         }
1209
1210         my $ret = `./booklook $fen`;
1211         return "" if ($ret =~ /Not found/ || $ret eq '');
1212
1213         my @moves = ();
1214
1215         for my $m (split /\n/, $ret) {
1216                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1217
1218                 my $pmove;
1219                 if ($move eq '')  {
1220                         $pmove = '(current)';
1221                 } else {
1222                         ($pmove) = prettyprint_pv_no_cache($board, $move);
1223                         $pmove .= $annotation;
1224                 }
1225
1226                 my $score;
1227                 if ($toplay eq 'W') {
1228                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1229                 } else {
1230                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1231                 }
1232                 my $n = $win + $draw + $lose;
1233                 
1234                 my $percent;
1235                 if ($n == 0) {
1236                         $percent = "     ";
1237                 } else {
1238                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1239                 }
1240
1241                 push @moves, [ $pmove, $n, $percent, $rating ];
1242         }
1243
1244         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1245         
1246         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1247         for my $m (@moves) {
1248                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1249         }
1250
1251         return $text;
1252 }
1253
1254 sub extract_clock {
1255         my ($pgn, $pos) = @_;
1256
1257         # Look for extended PGN clock tags.
1258         my $tags = $pgn->tags;
1259         if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1260                 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1261                 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1262                 return;
1263         }
1264
1265         # Look for TCEC-style time comments.
1266         my $moves = $pgn->moves;
1267         my $comments = $pgn->comments;
1268         my $last_black_move = int((scalar @$moves) / 2);
1269         my $last_white_move = int((1 + scalar @$moves) / 2);
1270
1271         my $black_key = $last_black_move . "b";
1272         my $white_key = $last_white_move . "w";
1273
1274         if (exists($comments->{$white_key}) &&
1275             exists($comments->{$black_key}) &&
1276             $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1277             $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1278                 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1279                 $pos->{'white_clock'} = hms_to_sec($1);
1280                 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1281                 $pos->{'black_clock'} = hms_to_sec($1);
1282                 return;
1283         }
1284
1285         delete $pos->{'white_clock'};
1286         delete $pos->{'black_clock'};
1287 }
1288
1289 sub hms_to_sec {
1290         my $hms = shift;
1291         return undef if (!defined($hms));
1292         $hms =~ /(\d+):(\d+):(\d+)/;
1293         return $1 * 3600 + $2 * 60 + $3;
1294 }
1295
1296 sub find_clock_start {
1297         my ($pos, $prev_pos) = @_;
1298
1299         # If the game is over, the clock is stopped.
1300         if (exists($pos->{'result'}) &&
1301             ($pos->{'result'} eq '1-0' ||
1302              $pos->{'result'} eq '1/2-1/2' ||
1303              $pos->{'result'} eq '0-1')) {
1304                 return;
1305         }
1306
1307         # When we don't have any moves, we assume the clock hasn't started yet.
1308         if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1309                 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1310                         &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1311                 }
1312                 return;
1313         }
1314
1315         # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1316         # The history is needed for id_for_pos.
1317         if (!exists($pos->{'history'})) {
1318                 return;
1319         }
1320
1321         my $id = id_for_pos($pos);
1322         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);
1323         if (defined($clock_info)) {
1324                 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1325                 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1326                 if ($pos->{'toplay'} eq 'W') {
1327                         $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1328                 } else {
1329                         $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1330                 }
1331                 return;
1332         }
1333
1334         # OK, we haven't seen this position before, so we assume the move
1335         # happened right now.
1336
1337         # See if we should do our own clock management (ie., clock information
1338         # is spurious or non-existent).
1339         if (defined($remoteglotconf::adjust_clocks_before_move)) {
1340                 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1341                 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1342                 if (defined($prev_pos->{'white_clock_target'})) {
1343                         $wc = $prev_pos->{'white_clock_target'} - time;
1344                 }
1345                 if (defined($prev_pos->{'black_clock_target'})) {
1346                         $bc = $prev_pos->{'black_clock_target'} - time;
1347                 }
1348                 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1349                 $pos->{'white_clock'} = $wc;
1350                 $pos->{'black_clock'} = $bc;
1351         }
1352
1353         my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1354         if (!exists($pos->{$key})) {
1355                 # No clock information.
1356                 return;
1357         }
1358         my $time_left = $pos->{$key};
1359         my ($white_clock_target, $black_clock_target);
1360         if ($pos->{'toplay'} eq 'W') {
1361                 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1362         } else {
1363                 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1364         }
1365         local $dbh->{AutoCommit} = 0;
1366         $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1367         $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1368                 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1369         $dbh->commit;
1370 }
1371
1372 sub schedule_tb_lookup {
1373         return if (!defined($remoteglotconf::tb_serial_key));
1374         my $pos = $pos_calculating;
1375         return if (exists($tb_cache{$pos->fen()}));
1376
1377         # If there's more than seven pieces, there's not going to be an answer,
1378         # so don't bother.
1379         return if ($pos->num_pieces() > 7);
1380
1381         # Max one at a time. If it's still relevant when it returns,
1382         # schedule_tb_lookup() will be called again.
1383         return if ($tb_lookup_running);
1384
1385         $tb_lookup_running = 1;
1386         my $url = 'http://tb7-api.chessok.com:6904/tasks/addtask?auth.login=' .
1387                 $remoteglotconf::tb_serial_key .
1388                 '&auth.password=aquarium&type=0&fen=' . 
1389                 URI::Escape::uri_escape($pos->fen());
1390         print TBLOG "Downloading $url...\n";
1391         AnyEvent::HTTP::http_get($url, sub {
1392                 handle_tb_lookup_return(@_, $pos, $pos->fen());
1393         });
1394 }
1395
1396 sub handle_tb_lookup_return {
1397         my ($body, $header, $pos, $fen) = @_;
1398         print TBLOG "Response for [$fen]:\n";
1399         print TBLOG $header . "\n\n";
1400         print TBLOG $body . "\n\n";
1401         eval {
1402                 my $response = JSON::XS::decode_json($body);
1403                 if ($response->{'ErrorCode'} != 0) {
1404                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1405                 }
1406                 my $state = $response->{'Response'}{'StateString'};
1407                 if ($state eq 'COMPLETE') {
1408                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1409                         if (!defined($pgn) || !$pgn->read_game()) {
1410                                 warn "Error in parsing PGN\n";
1411                         } else {
1412                                 $pgn->quick_parse_game;
1413                                 my $pvpos = $pos;
1414                                 my $moves = $pgn->moves;
1415                                 my @uci_moves = ();
1416                                 for my $move (@$moves) {
1417                                         my $uci_move;
1418                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1419                                         push @uci_moves, $uci_move;
1420                                 }
1421                                 $tb_cache{$fen} = {
1422                                         result => $pgn->result,
1423                                         pv => \@uci_moves,
1424                                         score => $response->{'Response'}{'Score'},
1425                                 };
1426                                 output();
1427                         }
1428                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1429                         # Try again in a second. Note that if we have changed
1430                         # position in the meantime, we might query a completely
1431                         # different position! But that's fine.
1432                 } else {
1433                         die "Unknown response state " . $state;
1434                 }
1435
1436                 # Wait a second before we schedule another one.
1437                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1438                         $tb_lookup_running = 0;
1439                         schedule_tb_lookup();
1440                 });
1441         };
1442         if ($@) {
1443                 warn "Error in tablebase lookup: $@";
1444
1445                 # Don't try this one again, but don't block new lookups either.
1446                 $tb_lookup_running = 0;
1447         }
1448 }
1449
1450 sub open_engine {
1451         my ($cmdline, $tag, $cb) = @_;
1452         return undef if (!defined($cmdline));
1453         return Engine->open($cmdline, $tag, $cb);
1454 }
1455
1456 sub col_letter_to_num {
1457         return ord(shift) - ord('a');
1458 }
1459
1460 sub row_letter_to_num {
1461         return 7 - (ord(shift) - ord('1'));
1462 }
1463
1464 sub parse_uci_move {
1465         my $move = shift;
1466         my $from_col = col_letter_to_num(substr($move, 0, 1));
1467         my $from_row = row_letter_to_num(substr($move, 1, 1));
1468         my $to_col   = col_letter_to_num(substr($move, 2, 1));
1469         my $to_row   = row_letter_to_num(substr($move, 3, 1));
1470         my $promo    = substr($move, 4, 1);
1471         return ($from_row, $from_col, $to_row, $to_col, $promo);
1472 }
1473
1474 sub setoptions {
1475         my ($engine, $config) = @_;
1476         uciprint($engine, "setoption name UCI_AnalyseMode value true");
1477         uciprint($engine, "setoption name Analysis Contempt value Off");
1478         if (exists($config->{'Threads'})) {  # Threads first, because clearing hash can be multithreaded then.
1479                 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1480         }
1481         while (my ($key, $value) = each %$config) {
1482                 next if $key eq 'Threads';
1483                 uciprint($engine, "setoption name $key value $value");
1484         }
1485 }