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