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