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