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