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