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