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