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