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