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