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