]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Make engine URL, move source and similar values dynamic instead of hard-coding them...
[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] eq 'name') {
486                         my $value = join(' ', @x);
487                         $engine->{'id'}{'author'} = $value;
488                         last;
489                 }
490
491                 # unknown
492                 shift @x;
493         }
494 }
495
496 sub prettyprint_pv_no_cache {
497         my ($board, @pvs) = @_;
498
499         if (scalar @pvs == 0 || !defined($pvs[0])) {
500                 return ();
501         }
502
503         my $pv = shift @pvs;
504         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
505         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
506         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
507 }
508
509 sub prettyprint_pv {
510         my ($pos, @pvs) = @_;
511
512         my $cachekey = join('', @pvs);
513         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
514                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
515         } else {
516                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
517                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
518                 return @res;
519         }
520 }
521
522 sub output {
523         #return;
524
525         return if (!defined($pos_calculating));
526
527         # Don't update too often.
528         my $age = Time::HiRes::tv_interval($latest_update);
529         if ($age < $remoteglotconf::update_max_interval) {
530                 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
531                 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
532                 return;
533         }
534         
535         my $info = $engine->{'info'};
536
537         #
538         # If we have tablebase data from a previous lookup, replace the
539         # engine data with the data from the tablebase.
540         #
541         my $fen = $pos_calculating->fen();
542         if (exists($tb_cache{$fen})) {
543                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
544                         delete $info->{$key . '1'};
545                         delete $info->{$key};
546                 }
547                 $info->{'nodes'} = 0;
548                 $info->{'nps'} = 0;
549                 $info->{'depth'} = 0;
550                 $info->{'seldepth'} = 0;
551                 $info->{'tbhits'} = 0;
552
553                 my $t = $tb_cache{$fen};
554                 my $pv = $t->{'pv'};
555                 my $matelen = int((1 + $t->{'score'}) / 2);
556                 if ($t->{'result'} eq '1/2-1/2') {
557                         $info->{'score_cp'} = 0;
558                 } elsif ($t->{'result'} eq '1-0') {
559                         if ($pos_calculating->{'toplay'} eq 'B') {
560                                 $info->{'score_mate'} = -$matelen;
561                         } else {
562                                 $info->{'score_mate'} = $matelen;
563                         }
564                 } else {
565                         if ($pos_calculating->{'toplay'} eq 'B') {
566                                 $info->{'score_mate'} = $matelen;
567                         } else {
568                                 $info->{'score_mate'} = -$matelen;
569                         }
570                 }
571                 $info->{'pv'} = $pv;
572                 $info->{'tablebase'} = 1;
573         } else {
574                 $info->{'tablebase'} = 0;
575         }
576         
577         #
578         # Some programs _always_ report MultiPV, even with only one PV.
579         # In this case, we simply use that data as if MultiPV was never
580         # specified.
581         #
582         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
583                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
584                         if (exists($info->{$key . '1'})) {
585                                 $info->{$key} = $info->{$key . '1'};
586                         }
587                 }
588         }
589         
590         #
591         # Check the PVs first. if they're invalid, just wait, as our data
592         # is most likely out of sync. This isn't a very good solution, as
593         # it can frequently miss stuff, but it's good enough for most users.
594         #
595         eval {
596                 my $dummy;
597                 if (exists($info->{'pv'})) {
598                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
599                 }
600         
601                 my $mpv = 1;
602                 while (exists($info->{'pv' . $mpv})) {
603                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
604                         ++$mpv;
605                 }
606         };
607         if ($@) {
608                 $engine->{'info'} = {};
609                 return;
610         }
611
612         output_screen();
613         output_json(0);
614         $latest_update = [Time::HiRes::gettimeofday];
615 }
616
617 sub output_screen {
618         my $info = $engine->{'info'};
619         my $id = $engine->{'id'};
620
621         my $text = 'Analysis';
622         if ($pos_calculating->{'last_move'} ne 'none') {
623                 if ($pos_calculating->{'toplay'} eq 'W') {
624                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
625                 } else {
626                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
627                 }
628                 if (exists($id->{'name'})) {
629                         $text .= ',';
630                 }
631         }
632
633         if (exists($id->{'name'})) {
634                 $text .= " by $id->{'name'}:\n\n";
635         } else {
636                 $text .= ":\n\n";
637         }
638
639         return unless (exists($pos_calculating->{'board'}));
640                 
641         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
642                 # multi-PV
643                 my $mpv = 1;
644                 while (exists($info->{'pv' . $mpv})) {
645                         $text .= sprintf "  PV%2u", $mpv;
646                         my $score = short_score($info, $pos_calculating, $mpv);
647                         $text .= "  ($score)" if (defined($score));
648
649                         my $tbhits = '';
650                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
651                                 if ($info->{'tbhits' . $mpv} == 1) {
652                                         $tbhits = ", 1 tbhit";
653                                 } else {
654                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
655                                 }
656                         }
657
658                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
659                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
660                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
661                         }
662
663                         $text .= ":\n";
664                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
665                         $text .= "\n";
666                         ++$mpv;
667                 }
668         } else {
669                 # single-PV
670                 my $score = long_score($info, $pos_calculating, '');
671                 $text .= "  $score\n" if defined($score);
672                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
673                 $text .=  "\n";
674
675                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
676                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
677                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
678                 }
679                 if (exists($info->{'seldepth'})) {
680                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
681                 }
682                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
683                         if ($info->{'tbhits'} == 1) {
684                                 $text .= ", one Syzygy hit";
685                         } else {
686                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
687                         }
688                 }
689                 $text .= "\n\n";
690         }
691
692         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
693
694         my @refutation_lines = ();
695         if (defined($engine2)) {
696                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
697                         my $info = $engine2->{'info'};
698                         last if (!exists($info->{'pv' . $mpv}));
699                         eval {
700                                 my $pv = $info->{'pv' . $mpv};
701
702                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
703                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
704                                 if (scalar @pretty_pv > 5) {
705                                         @pretty_pv = @pretty_pv[0..4];
706                                         push @pretty_pv, "...";
707                                 }
708                                 my $key = $pretty_move;
709                                 my $line = sprintf("  %-6s %6s %3s  %s",
710                                         $pretty_move,
711                                         short_score($info, $pos_calculating_second_engine, $mpv),
712                                         "d" . $info->{'depth' . $mpv},
713                                         join(', ', @pretty_pv));
714                                 push @refutation_lines, [ $key, $line ];
715                         };
716                 }
717         }
718
719         if ($#refutation_lines >= 0) {
720                 $text .= "Shallow search of all legal moves:\n\n";
721                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
722                         $text .= $line->[1] . "\n";
723                 }
724                 $text .= "\n\n";        
725         }       
726
727         if ($last_text ne $text) {
728                 print "\e[H\e[2J"; # clear the screen
729                 print $text;
730                 $last_text = $text;
731         }
732 }
733
734 sub output_json {
735         my $historic_json_only = shift;
736         my $info = $engine->{'info'};
737
738         my $json = {};
739         $json->{'position'} = $pos_calculating->to_json_hash();
740         $json->{'engine'} = $engine->{'id'};
741         if (defined($remoteglotconf::engine_url)) {
742                 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
743         }
744         if (defined($remoteglotconf::engine_details)) {
745                 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
746         }
747         if (defined($remoteglotconf::move_source)) {
748                 $json->{'move_source'} = $remoteglotconf::move_source;
749         }
750         if (defined($remoteglotconf::move_source_url)) {
751                 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
752         }
753         $json->{'score'} = long_score($info, $pos_calculating, '');
754         $json->{'short_score'} = short_score($info, $pos_calculating, '');
755         $json->{'plot_score'} = plot_score($info, $pos_calculating, '');
756         $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
757
758         $json->{'nodes'} = $info->{'nodes'};
759         $json->{'nps'} = $info->{'nps'};
760         $json->{'depth'} = $info->{'depth'};
761         $json->{'tbhits'} = $info->{'tbhits'};
762         $json->{'seldepth'} = $info->{'seldepth'};
763         $json->{'tablebase'} = $info->{'tablebase'};
764
765         $json->{'pv_uci'} = $info->{'pv'};  # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
766         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
767
768         my %refutation_lines = ();
769         my @refutation_lines = ();
770         if (defined($engine2)) {
771                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
772                         my $info = $engine2->{'info'};
773                         my $pretty_move = "";
774                         my @pretty_pv = ();
775                         last if (!exists($info->{'pv' . $mpv}));
776
777                         eval {
778                                 my $pv = $info->{'pv' . $mpv};
779                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
780                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
781                                 $refutation_lines{$pv->[0]} = {
782                                         sort_key => $pretty_move,
783                                         depth => $info->{'depth' . $mpv},
784                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
785                                         pretty_score => short_score($info, $pos_calculating, $mpv),
786                                         pretty_move => $pretty_move,
787                                         pv_pretty => \@pretty_pv,
788                                 };
789                         };
790                 }
791         }
792         $json->{'refutation_lines'} = \%refutation_lines;
793
794         # Piece together historic score information, to the degree we have it.
795         if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
796                 my %score_history = ();
797
798                 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
799                 my $pos = Position->start_pos('white', 'black');
800                 my $halfmove_num = 0;
801                 for my $move (@{$pos_calculating->{'pretty_history'}}) {
802                         my $id = id_for_pos($pos, $halfmove_num);
803                         my $ref = $dbh->selectrow_hashref($q, undef, $id);
804                         if (defined($ref)) {
805                                 $score_history{$halfmove_num} = [
806                                         $ref->{'plot_score'},
807                                         $ref->{'short_score'}
808                                 ];
809                         }
810                         ++$halfmove_num;
811                         ($pos) = $pos->make_pretty_move($move);
812                 }
813                 $q->finish;
814
815                 # If at any point we are missing 10 consecutive moves,
816                 # truncate the history there. This is so we don't get into
817                 # a situation where we e.g. start analyzing at move 45,
818                 # but we have analysis for 1. e4 from some completely different game
819                 # and thus show a huge hole.
820                 my $consecutive_missing = 0;
821                 my $truncate_until = 0;
822                 for (my $i = $halfmove_num; $i --> 0; ) {
823                         if ($consecutive_missing >= 10) {
824                                 delete $score_history{$i};
825                                 next;
826                         }
827                         if (exists($score_history{$i})) {
828                                 $consecutive_missing = 0;
829                         } else {
830                                 ++$consecutive_missing;
831                         }
832                 }
833
834                 $json->{'score_history'} = \%score_history;
835         }
836
837         # Give out a list of other games going on. (Empty is fine.)
838         if (!$historic_json_only) {
839                 my @games = ();
840
841                 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
842                 $q->execute;
843                 while (my $ref = $q->fetchrow_hashref) {
844                         eval {
845                                 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
846                                 my $other_game_json = JSON::XS::decode_json($other_game_contents);
847
848                                 die "Missing position" if (!exists($other_game_json->{'position'}));
849                                 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
850                                 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
851
852                                 push @games, {
853                                         id => $ref->{'id'},
854                                         name => "$white–$black",
855                                         url => $ref->{'url'}
856                                 };
857                         };
858                         if ($@) {
859                                 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
860                         }
861                 }
862
863                 if (scalar @games > 0) {
864                         $json->{'games'} = \@games;
865                 }
866         }
867
868         my $json_enc = JSON::XS->new;
869         $json_enc->canonical(1);
870         my $encoded = $json_enc->encode($json);
871         unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
872                 (defined($last_written_json) && $last_written_json eq $encoded)) {
873                 atomic_set_contents($remoteglotconf::json_output, $encoded);
874                 $last_written_json = $encoded;
875         }
876
877         if (exists($pos_calculating->{'pretty_history'}) &&
878             defined($remoteglotconf::json_history_dir)) {
879                 my $id = id_for_pos($pos_calculating);
880                 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
881
882                 # Overwrite old analysis (assuming it exists at all) if we're
883                 # using a different engine, or if we've calculated deeper.
884                 # nodes is used as a tiebreaker. Don't bother about Multi-PV
885                 # data; it's not that important.
886                 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
887                 my $new_depth = $json->{'depth'} // 0;
888                 my $new_nodes = $json->{'nodes'} // 0;
889                 if (!defined($old_engine) ||
890                     $old_engine ne $json->{'engine'}{'name'} ||
891                     $new_depth > $old_depth ||
892                     ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
893                         atomic_set_contents($filename, $encoded);
894                         if (defined($json->{'plot_score'})) {
895                                 local $dbh->{AutoCommit} = 0;
896                                 $dbh->do('DELETE FROM scores WHERE id=?', undef, $id);
897                                 $dbh->do('INSERT INTO scores (id, plot_score, short_score, engine, depth, nodes) VALUES (?,?,?,?,?,?)', undef,
898                                         $id, $json->{'plot_score'}, $json->{'short_score'},
899                                         $json->{'engine'}{'name'}, $new_depth, $new_nodes);
900                                 $dbh->commit;
901                         }
902                 }
903         }
904 }
905
906 sub atomic_set_contents {
907         my ($filename, $contents) = @_;
908
909         open my $fh, ">", $filename . ".tmp"
910                 or return;
911         print $fh $contents;
912         close $fh;
913         rename($filename . ".tmp", $filename);
914 }
915
916 sub id_for_pos {
917         my ($pos, $halfmove_num) = @_;
918
919         $halfmove_num //= scalar @{$pos->{'pretty_history'}};
920         (my $fen = $pos->fen()) =~ tr,/ ,-_,;
921         return "move$halfmove_num-$fen";
922 }
923
924 sub get_json_analysis_stats {
925         my $id = shift;
926         my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
927         if (defined($ref)) {
928                 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
929         } else {
930                 return ('', 0, 0);
931         }
932 }
933
934 sub uciprint {
935         my ($engine, $msg) = @_;
936         $engine->print($msg);
937         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
938 }
939
940 sub short_score {
941         my ($info, $pos, $mpv) = @_;
942
943         my $invert = ($pos->{'toplay'} eq 'B');
944         if (defined($info->{'score_mate' . $mpv})) {
945                 if ($invert) {
946                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
947                 } else {
948                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
949                 }
950         } else {
951                 if (exists($info->{'score_cp' . $mpv})) {
952                         my $score = $info->{'score_cp' . $mpv} * 0.01;
953                         if ($score == 0) {
954                                 if ($info->{'tablebase'}) {
955                                         return "TB draw";
956                                 } else {
957                                         return " 0.00";
958                                 }
959                         }
960                         if ($invert) {
961                                 $score = -$score;
962                         }
963                         return sprintf "%+5.2f", $score;
964                 }
965         }
966
967         return undef;
968 }
969
970 sub score_sort_key {
971         my ($info, $pos, $mpv, $invert) = @_;
972
973         if (defined($info->{'score_mate' . $mpv})) {
974                 my $mate = $info->{'score_mate' . $mpv};
975                 my $score;
976                 if ($mate > 0) {
977                         # Side to move mates
978                         $score = 99999 - $mate;
979                 } else {
980                         # Side to move is getting mated (note the double negative for $mate)
981                         $score = -99999 - $mate;
982                 }
983                 if ($invert) {
984                         $score = -$score;
985                 }
986                 return $score;
987         } else {
988                 if (exists($info->{'score_cp' . $mpv})) {
989                         my $score = $info->{'score_cp' . $mpv};
990                         if ($invert) {
991                                 $score = -$score;
992                         }
993                         return $score;
994                 }
995         }
996
997         return undef;
998 }
999
1000 sub long_score {
1001         my ($info, $pos, $mpv) = @_;
1002
1003         if (defined($info->{'score_mate' . $mpv})) {
1004                 my $mate = $info->{'score_mate' . $mpv};
1005                 if ($pos->{'toplay'} eq 'B') {
1006                         $mate = -$mate;
1007                 }
1008                 if ($mate > 0) {
1009                         return sprintf "White mates in %u", $mate;
1010                 } else {
1011                         return sprintf "Black mates in %u", -$mate;
1012                 }
1013         } else {
1014                 if (exists($info->{'score_cp' . $mpv})) {
1015                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1016                         if ($score == 0) {
1017                                 if ($info->{'tablebase'}) {
1018                                         return "Theoretical draw";
1019                                 } else {
1020                                         return "Score:  0.00";
1021                                 }
1022                         }
1023                         if ($pos->{'toplay'} eq 'B') {
1024                                 $score = -$score;
1025                         }
1026                         return sprintf "Score: %+5.2f", $score;
1027                 }
1028         }
1029
1030         return undef;
1031 }
1032
1033 # For graphs; a single number in centipawns, capped at +/- 500.
1034 sub plot_score {
1035         my ($info, $pos, $mpv) = @_;
1036
1037         my $invert = ($pos->{'toplay'} eq 'B');
1038         if (defined($info->{'score_mate' . $mpv})) {
1039                 my $mate = $info->{'score_mate' . $mpv};
1040                 if ($invert) {
1041                         $mate = -$mate;
1042                 }
1043                 if ($mate > 0) {
1044                         return 500;
1045                 } else {
1046                         return -500;
1047                 }
1048         } else {
1049                 if (exists($info->{'score_cp' . $mpv})) {
1050                         my $score = $info->{'score_cp' . $mpv};
1051                         if ($invert) {
1052                                 $score = -$score;
1053                         }
1054                         $score = 500 if ($score > 500);
1055                         $score = -500 if ($score < -500);
1056                         return int($score);
1057                 }
1058         }
1059
1060         return undef;
1061 }
1062
1063 my %book_cache = ();
1064 sub book_info {
1065         my ($fen, $board, $toplay) = @_;
1066
1067         if (exists($book_cache{$fen})) {
1068                 return $book_cache{$fen};
1069         }
1070
1071         my $ret = `./booklook $fen`;
1072         return "" if ($ret =~ /Not found/ || $ret eq '');
1073
1074         my @moves = ();
1075
1076         for my $m (split /\n/, $ret) {
1077                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1078
1079                 my $pmove;
1080                 if ($move eq '')  {
1081                         $pmove = '(current)';
1082                 } else {
1083                         ($pmove) = prettyprint_pv_no_cache($board, $move);
1084                         $pmove .= $annotation;
1085                 }
1086
1087                 my $score;
1088                 if ($toplay eq 'W') {
1089                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1090                 } else {
1091                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1092                 }
1093                 my $n = $win + $draw + $lose;
1094                 
1095                 my $percent;
1096                 if ($n == 0) {
1097                         $percent = "     ";
1098                 } else {
1099                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1100                 }
1101
1102                 push @moves, [ $pmove, $n, $percent, $rating ];
1103         }
1104
1105         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1106         
1107         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1108         for my $m (@moves) {
1109                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1110         }
1111
1112         return $text;
1113 }
1114
1115 sub extract_clock {
1116         my ($pgn, $pos) = @_;
1117
1118         # Look for extended PGN clock tags.
1119         my $tags = $pgn->tags;
1120         if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1121                 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1122                 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1123                 return;
1124         }
1125
1126         # Look for TCEC-style time comments.
1127         my $moves = $pgn->moves;
1128         my $comments = $pgn->comments;
1129         my $last_black_move = int((scalar @$moves) / 2);
1130         my $last_white_move = int((1 + scalar @$moves) / 2);
1131
1132         my $black_key = $last_black_move . "b";
1133         my $white_key = $last_white_move . "w";
1134
1135         if (exists($comments->{$white_key}) &&
1136             exists($comments->{$black_key}) &&
1137             $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1138             $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1139                 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1140                 $pos->{'white_clock'} = hms_to_sec($1);
1141                 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1142                 $pos->{'black_clock'} = hms_to_sec($1);
1143                 return;
1144         }
1145
1146         delete $pos->{'white_clock'};
1147         delete $pos->{'black_clock'};
1148 }
1149
1150 sub hms_to_sec {
1151         my $hms = shift;
1152         return undef if (!defined($hms));
1153         $hms =~ /(\d+):(\d+):(\d+)/;
1154         return $1 * 3600 + $2 * 60 + $3;
1155 }
1156
1157 sub find_clock_start {
1158         my ($pos, $prev_pos) = @_;
1159
1160         # If the game is over, the clock is stopped.
1161         if (exists($pos->{'result'}) &&
1162             ($pos->{'result'} eq '1-0' ||
1163              $pos->{'result'} eq '1/2-1/2' ||
1164              $pos->{'result'} eq '0-1')) {
1165                 return;
1166         }
1167
1168         # When we don't have any moves, we assume the clock hasn't started yet.
1169         if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1170                 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1171                         &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1172                 }
1173                 return;
1174         }
1175
1176         # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1177         # The history is needed for id_for_pos.
1178         if (!exists($pos->{'pretty_history'})) {
1179                 return;
1180         }
1181
1182         my $id = id_for_pos($pos);
1183         my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1184         if (defined($clock_info)) {
1185                 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1186                 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1187                 if ($pos->{'toplay'} eq 'W') {
1188                         $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1189                 } else {
1190                         $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1191                 }
1192                 return;
1193         }
1194
1195         # OK, we haven't seen this position before, so we assume the move
1196         # happened right now.
1197
1198         # See if we should do our own clock management (ie., clock information
1199         # is spurious or non-existent).
1200         if (defined($remoteglotconf::adjust_clocks_before_move)) {
1201                 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1202                 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1203                 if (defined($prev_pos->{'white_clock_target'})) {
1204                         $wc = $prev_pos->{'white_clock_target'} - time;
1205                 }
1206                 if (defined($prev_pos->{'black_clock_target'})) {
1207                         $bc = $prev_pos->{'black_clock_target'} - time;
1208                 }
1209                 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1210                 $pos->{'white_clock'} = $wc;
1211                 $pos->{'black_clock'} = $bc;
1212         }
1213
1214         my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1215         if (!exists($pos->{$key})) {
1216                 # No clock information.
1217                 return;
1218         }
1219         my $time_left = $pos->{$key};
1220         my ($white_clock_target, $black_clock_target);
1221         if ($pos->{'toplay'} eq 'W') {
1222                 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1223         } else {
1224                 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1225         }
1226         local $dbh->{AutoCommit} = 0;
1227         $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1228         $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1229                 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1230         $dbh->commit;
1231 }
1232
1233 sub schedule_tb_lookup {
1234         return if (!defined($remoteglotconf::tb_serial_key));
1235         my $pos = $pos_waiting // $pos_calculating;
1236         return if (exists($tb_cache{$pos->fen()}));
1237
1238         # If there's more than seven pieces, there's not going to be an answer,
1239         # so don't bother.
1240         return if ($pos->num_pieces() > 7);
1241
1242         # Max one at a time. If it's still relevant when it returns,
1243         # schedule_tb_lookup() will be called again.
1244         return if ($tb_lookup_running);
1245
1246         $tb_lookup_running = 1;
1247         my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1248                 $remoteglotconf::tb_serial_key .
1249                 '&auth.password=aquarium&type=0&fen=' . 
1250                 URI::Escape::uri_escape($pos->fen());
1251         print TBLOG "Downloading $url...\n";
1252         AnyEvent::HTTP::http_get($url, sub {
1253                 handle_tb_lookup_return(@_, $pos, $pos->fen());
1254         });
1255 }
1256
1257 sub handle_tb_lookup_return {
1258         my ($body, $header, $pos, $fen) = @_;
1259         print TBLOG "Response for [$fen]:\n";
1260         print TBLOG $header . "\n\n";
1261         print TBLOG $body . "\n\n";
1262         eval {
1263                 my $response = JSON::XS::decode_json($body);
1264                 if ($response->{'ErrorCode'} != 0) {
1265                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1266                 }
1267                 my $state = $response->{'Response'}{'StateString'};
1268                 if ($state eq 'COMPLETE') {
1269                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1270                         if (!defined($pgn) || !$pgn->read_game()) {
1271                                 warn "Error in parsing PGN\n";
1272                         } else {
1273                                 $pgn->quick_parse_game;
1274                                 my $pvpos = $pos;
1275                                 my $moves = $pgn->moves;
1276                                 my @uci_moves = ();
1277                                 for my $move (@$moves) {
1278                                         my $uci_move;
1279                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1280                                         push @uci_moves, $uci_move;
1281                                 }
1282                                 $tb_cache{$fen} = {
1283                                         result => $pgn->result,
1284                                         pv => \@uci_moves,
1285                                         score => $response->{'Response'}{'Score'},
1286                                 };
1287                                 output();
1288                         }
1289                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1290                         # Try again in a second. Note that if we have changed
1291                         # position in the meantime, we might query a completely
1292                         # different position! But that's fine.
1293                 } else {
1294                         die "Unknown response state " . $state;
1295                 }
1296
1297                 # Wait a second before we schedule another one.
1298                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1299                         $tb_lookup_running = 0;
1300                         schedule_tb_lookup();
1301                 });
1302         };
1303         if ($@) {
1304                 warn "Error in tablebase lookup: $@";
1305
1306                 # Don't try this one again, but don't block new lookups either.
1307                 $tb_lookup_running = 0;
1308         }
1309 }
1310
1311 sub open_engine {
1312         my ($cmdline, $tag, $cb) = @_;
1313         return undef if (!defined($cmdline));
1314         return Engine->open($cmdline, $tag, $cb);
1315 }
1316
1317 sub col_letter_to_num {
1318         return ord(shift) - ord('a');
1319 }
1320
1321 sub row_letter_to_num {
1322         return 7 - (ord(shift) - ord('1'));
1323 }
1324
1325 sub parse_uci_move {
1326         my $move = shift;
1327         my $from_col = col_letter_to_num(substr($move, 0, 1));
1328         my $from_row = row_letter_to_num(substr($move, 1, 1));
1329         my $to_col   = col_letter_to_num(substr($move, 2, 1));
1330         my $to_row   = row_letter_to_num(substr($move, 3, 1));
1331         my $promo    = substr($move, 4, 1);
1332         return ($from_col, $from_row, $to_col, $to_row, $promo);
1333 }