]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Make stoppgn more robust.
[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 FileHandle;
19 use IPC::Open2;
20 use Time::HiRes;
21 use JSON::XS;
22 use URI::Escape;
23 require 'Position.pm';
24 require 'Engine.pm';
25 require 'config.pm';
26 use strict;
27 use warnings;
28 no warnings qw(once);
29
30 # Program starts here
31 my $latest_update = undef;
32 my $output_timer = undef;
33 my $http_timer = undef;
34 my $stop_pgn_fetch = 0;
35 my $tb_retry_timer = undef;
36 my %tb_cache = ();
37 my $tb_lookup_running = 0;
38
39 $| = 1;
40
41 open(FICSLOG, ">ficslog.txt")
42         or die "ficslog.txt: $!";
43 print FICSLOG "Log starting.\n";
44 select(FICSLOG);
45 $| = 1;
46
47 open(UCILOG, ">ucilog.txt")
48         or die "ucilog.txt: $!";
49 print UCILOG "Log starting.\n";
50 select(UCILOG);
51 $| = 1;
52
53 open(TBLOG, ">tblog.txt")
54         or die "tblog.txt: $!";
55 print TBLOG "Log starting.\n";
56 select(TBLOG);
57 $| = 1;
58
59 select(STDOUT);
60
61 # open the chess engine
62 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
63 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
64 my $last_move;
65 my $last_text = '';
66 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
67
68 uciprint($engine, "setoption name UCI_AnalyseMode value true");
69 while (my ($key, $value) = each %remoteglotconf::engine_config) {
70         uciprint($engine, "setoption name $key value $value");
71 }
72 uciprint($engine, "ucinewgame");
73
74 if (defined($engine2)) {
75         uciprint($engine2, "setoption name UCI_AnalyseMode value true");
76         while (my ($key, $value) = each %remoteglotconf::engine2_config) {
77                 uciprint($engine2, "setoption name $key value $value");
78         }
79         uciprint($engine2, "setoption name MultiPV value 500");
80         uciprint($engine2, "ucinewgame");
81 }
82
83 print "Chess engine ready.\n";
84
85 # now talk to FICS
86 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
87 $t->input_log(\*FICSLOG);
88 $t->open($remoteglotconf::server);
89 $t->print($remoteglotconf::nick);
90 $t->waitfor('/Press return to enter the server/');
91 $t->cmd("");
92
93 # set some options
94 $t->cmd("set shout 0");
95 $t->cmd("set seek 0");
96 $t->cmd("set style 12");
97
98 my $ev1 = AnyEvent->io(
99         fh => fileno($t),
100         poll => 'r',
101         cb => sub {    # what callback to execute
102                 while (1) {
103                         my $line = $t->getline(Timeout => 0, errmode => 'return');
104                         return if (!defined($line));
105
106                         chomp $line;
107                         $line =~ tr/\r//d;
108                         handle_fics($line);
109                 }
110         }
111 );
112 if (defined($remoteglotconf::target)) {
113         if ($remoteglotconf::target =~ /^http:/) {
114                 fetch_pgn($remoteglotconf::target);
115         } else {
116                 $t->cmd("observe $remoteglotconf::target");
117         }
118 }
119 print "FICS ready.\n";
120
121 # Engine events have already been set up by Engine.pm.
122 EV::run;
123
124 sub handle_uci {
125         my ($engine, $line, $primary) = @_;
126
127         return if $line =~ /(upper|lower)bound/;
128
129         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
130         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
131         if ($line =~ /^info/) {
132                 my (@infos) = split / /, $line;
133                 shift @infos;
134
135                 parse_infos($engine, @infos);
136         }
137         if ($line =~ /^id/) {
138                 my (@ids) = split / /, $line;
139                 shift @ids;
140
141                 parse_ids($engine, @ids);
142         }
143         if ($line =~ /^bestmove/) {
144                 if ($primary) {
145                         return if (!$remoteglotconf::uci_assume_full_compliance);
146                         if (defined($pos_waiting)) {
147                                 uciprint($engine, "position fen " . $pos_waiting->fen());
148                                 uciprint($engine, "go infinite");
149
150                                 $pos_calculating = $pos_waiting;
151                                 $pos_waiting = undef;
152                         }
153                 } else {
154                         $engine2->{'info'} = {};
155                         my $pos = $pos_waiting // $pos_calculating;
156                         uciprint($engine2, "position fen " . $pos->fen());
157                         uciprint($engine2, "go infinite");
158                         $pos_calculating_second_engine = $pos;
159                 }
160         }
161         output();
162 }
163
164 my $getting_movelist = 0;
165 my $pos_for_movelist = undef;
166 my @uci_movelist = ();
167 my @pretty_movelist = ();
168
169 sub handle_fics {
170         my $line = shift;
171         if ($line =~ /^<12> /) {
172                 handle_position(Position->new($line));
173                 $t->cmd("moves");
174         }
175         if ($line =~ /^Movelist for game /) {
176                 my $pos = $pos_waiting // $pos_calculating;
177                 if (defined($pos)) {
178                         @uci_movelist = ();
179                         @pretty_movelist = ();
180                         $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
181                         $getting_movelist = 1;
182                 }
183         }
184         if ($getting_movelist &&
185             $line =~ /^\s* \d+\. \s+                     # move number
186                        (\S+) \s+ \( [\d:.]+ \) \s*       # first move, then time
187                        (?: (\S+) \s+ \( [\d:.]+ \) )?    # second move, then time 
188                      /x) {
189                 eval {
190                         my $uci_move;
191                         ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
192                         push @uci_movelist, $uci_move;
193                         push @pretty_movelist, $1;
194
195                         if (defined($2)) {
196                                 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
197                                 push @uci_movelist, $uci_move;
198                                 push @pretty_movelist, $2;
199                         }
200                 };
201                 if ($@) {
202                         warn "Error when getting FICS move history: $@";
203                         $getting_movelist = 0;
204                 }
205         }
206         if ($getting_movelist &&
207             $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
208                 # End of movelist.
209                 for my $pos ($pos_waiting, $pos_calculating) {
210                         next if (!defined($pos));
211                         if ($pos->fen() eq $pos_for_movelist->fen()) {
212                                 $pos->{'history'} = \@uci_movelist;
213                                 $pos->{'pretty_history'} = \@pretty_movelist;
214                         }
215                 }
216                 $getting_movelist = 0;
217         }
218         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
219                 my ($who, $msg) = ($1, $2);
220
221                 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
222
223                 if ($msg =~ /^fics (.*?)$/) {
224                         $t->cmd("tell $who Executing '$1' on FICS.");
225                         $t->cmd($1);
226                 } elsif ($msg =~ /^uci (.*?)$/) {
227                         $t->cmd("tell $who Sending '$1' to the engine.");
228                         print { $engine->{'write'} } "$1\n";
229                 } elsif ($msg =~ /^pgn (.*?)$/) {
230                         my $url = $1;
231                         $t->cmd("tell $who Starting to poll '$url'.");
232                         fetch_pgn($url);
233                 } elsif ($msg =~ /^stoppgn$/) {
234                         $t->cmd("tell $who Stopping poll.");
235                         $stop_pgn_fetch = 1;
236                         $http_timer = undef;
237                 } elsif ($msg =~ /^quit$/) {
238                         $t->cmd("tell $who Bye bye.");
239                         exit;
240                 } else {
241                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
242                 }
243         }
244         #print "FICS: [$line]\n";
245 }
246
247 # Starts periodic fetching of PGNs from the given URL.
248 sub fetch_pgn {
249         my ($url) = @_;
250         AnyEvent::HTTP::http_get($url, sub {
251                 handle_pgn(@_, $url);
252         });
253 }
254
255 my ($last_pgn_white, $last_pgn_black);
256 my @last_pgn_uci_moves = ();
257 my $pgn_hysteresis_counter = 0;
258
259 sub handle_pgn {
260         my ($body, $header, $url) = @_;
261
262         if ($stop_pgn_fetch) {
263                 $stop_pgn_fetch = 0;
264                 $http_timer = undef;
265                 return;
266         }
267
268         my $pgn = Chess::PGN::Parse->new(undef, $body);
269         if (!defined($pgn) || !$pgn->read_game()) {
270                 warn "Error in parsing PGN from $url\n";
271         } else {
272                 $pgn->quick_parse_game;
273                 my $pos = Position->start_pos($pgn->white, $pgn->black);
274                 my $moves = $pgn->moves;
275                 my @uci_moves = ();
276                 for my $move (@$moves) {
277                         my $uci_move;
278                         ($pos, $uci_move) = $pos->make_pretty_move($move);
279                         push @uci_moves, $uci_move;
280                 }
281                 $pos->{'history'} = \@uci_moves;
282                 $pos->{'pretty_history'} = $moves;
283
284                 # Sometimes, PGNs lose a move or two for a short while,
285                 # or people push out new ones non-atomically. 
286                 # Thus, if we PGN doesn't change names but becomes
287                 # shorter, we mistrust it for a few seconds.
288                 my $trust_pgn = 1;
289                 if (defined($last_pgn_white) && defined($last_pgn_black) &&
290                     $last_pgn_white eq $pgn->white &&
291                     $last_pgn_black eq $pgn->black &&
292                     scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
293                         if (++$pgn_hysteresis_counter < 3) {
294                                 $trust_pgn = 0; 
295                         }
296                 }
297                 if ($trust_pgn) {
298                         $last_pgn_white = $pgn->white;
299                         $last_pgn_black = $pgn->black;
300                         @last_pgn_uci_moves = @uci_moves;
301                         $pgn_hysteresis_counter = 0;
302                         handle_position($pos);
303                 }
304         }
305         
306         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
307                 fetch_pgn($url);
308         });
309 }
310
311 sub handle_position {
312         my ($pos) = @_;
313                 
314         # if this is already in the queue, ignore it
315         return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
316
317         # if we're already chewing on this and there's nothing else in the queue,
318         # also ignore it
319         return if (!defined($pos_waiting) && defined($pos_calculating) &&
320                  $pos->fen() eq $pos_calculating->fen());
321
322         # if we're already thinking on something, stop and wait for the engine
323         # to approve
324         if (defined($pos_calculating)) {
325                 if (!defined($pos_waiting)) {
326                         uciprint($engine, "stop");
327                 }
328                 if ($remoteglotconf::uci_assume_full_compliance) {
329                         $pos_waiting = $pos;
330                 } else {
331                         uciprint($engine, "position fen " . $pos->fen());
332                         uciprint($engine, "go infinite");
333                         $pos_calculating = $pos;
334                 }
335         } else {
336                 # it's wrong just to give the FEN (the move history is useful,
337                 # and per the UCI spec, we should really have sent "ucinewgame"),
338                 # but it's easier
339                 uciprint($engine, "position fen " . $pos->fen());
340                 uciprint($engine, "go infinite");
341                 $pos_calculating = $pos;
342         }
343
344         if (defined($engine2)) {
345                 if (defined($pos_calculating_second_engine)) {
346                         uciprint($engine2, "stop");
347                 } else {
348                         uciprint($engine2, "position fen " . $pos->fen());
349                         uciprint($engine2, "go infinite");
350                         $pos_calculating_second_engine = $pos;
351                 }
352                 $engine2->{'info'} = {};
353         }
354
355         $engine->{'info'} = {};
356         $last_move = time;
357
358         schedule_tb_lookup();
359
360         # 
361         # Output a command every move to note that we're
362         # still paying attention -- this is a good tradeoff,
363         # since if no move has happened in the last half
364         # hour, the analysis/relay has most likely stopped
365         # and we should stop hogging server resources.
366         #
367         $t->cmd("date");
368 }
369
370 sub parse_infos {
371         my ($engine, @x) = @_;
372         my $mpv = '';
373
374         my $info = $engine->{'info'};
375
376         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
377         for my $i (0..$#x - 1) {
378                 if ($x[$i] eq 'multipv') {
379                         $mpv = $x[$i + 1];
380                         next;
381                 }
382         }
383
384         while (scalar @x > 0) {
385                 if ($x[0] eq 'multipv') {
386                         # Dealt with above
387                         shift @x;
388                         shift @x;
389                         next;
390                 }
391                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
392                         my $key = shift @x;
393                         my $value = shift @x;
394                         $info->{$key} = $value;
395                         next;
396                 }
397                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
398                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
399                     $x[0] eq 'tbhits') {
400                         my $key = shift @x;
401                         my $value = shift @x;
402                         $info->{$key . $mpv} = $value;
403                         next;
404                 }
405                 if ($x[0] eq 'score') {
406                         shift @x;
407
408                         delete $info->{'score_cp' . $mpv};
409                         delete $info->{'score_mate' . $mpv};
410
411                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
412                                 if ($x[0] eq 'cp') {
413                                         shift @x;
414                                         $info->{'score_cp' . $mpv} = shift @x;
415                                 } elsif ($x[0] eq 'mate') {
416                                         shift @x;
417                                         $info->{'score_mate' . $mpv} = shift @x;
418                                 } else {
419                                         shift @x;
420                                 }
421                         }
422                         next;
423                 }
424                 if ($x[0] eq 'pv') {
425                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
426                         last;
427                 }
428                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
429                         last;
430                 }
431
432                 #print "unknown info '$x[0]', trying to recover...\n";
433                 #shift @x;
434                 die "Unknown info '" . join(',', @x) . "'";
435
436         }
437 }
438
439 sub parse_ids {
440         my ($engine, @x) = @_;
441
442         while (scalar @x > 0) {
443                 if ($x[0] =~ /^(name|author)$/) {
444                         my $key = shift @x;
445                         my $value = join(' ', @x);
446                         $engine->{'id'}{$key} = $value;
447                         last;
448                 }
449
450                 # unknown
451                 shift @x;
452         }
453 }
454
455 sub prettyprint_pv_no_cache {
456         my ($board, @pvs) = @_;
457
458         if (scalar @pvs == 0 || !defined($pvs[0])) {
459                 return ();
460         }
461
462         my $pv = shift @pvs;
463         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
464         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
465         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
466 }
467
468 sub prettyprint_pv {
469         my ($pos, @pvs) = @_;
470
471         my $cachekey = join('', @pvs);
472         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
473                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
474         } else {
475                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
476                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
477                 return @res;
478         }
479 }
480
481 sub output {
482         #return;
483
484         return if (!defined($pos_calculating));
485
486         # Don't update too often.
487         my $age = Time::HiRes::tv_interval($latest_update);
488         if ($age < $remoteglotconf::update_max_interval) {
489                 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
490                 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
491                 return;
492         }
493         
494         my $info = $engine->{'info'};
495
496         #
497         # If we have tablebase data from a previous lookup, replace the
498         # engine data with the data from the tablebase.
499         #
500         my $fen = $pos_calculating->fen();
501         if (exists($tb_cache{$fen})) {
502                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
503                         delete $info->{$key . '1'};
504                         delete $info->{$key};
505                 }
506                 $info->{'nodes'} = 0;
507                 $info->{'nps'} = 0;
508                 $info->{'depth'} = 0;
509                 $info->{'seldepth'} = 0;
510                 $info->{'tbhits'} = 0;
511
512                 my $t = $tb_cache{$fen};
513                 my $pv = $t->{'pv'};
514                 my $matelen = int((1 + scalar @$pv) / 2);
515                 if ($t->{'result'} eq '1/2-1/2') {
516                         $info->{'score_cp'} = 0;
517                 } elsif ($t->{'result'} eq '1-0') {
518                         if ($pos_calculating->{'toplay'} eq 'B') {
519                                 $info->{'score_mate'} = -$matelen;
520                         } else {
521                                 $info->{'score_mate'} = $matelen;
522                         }
523                 } else {
524                         if ($pos_calculating->{'toplay'} eq 'B') {
525                                 $info->{'score_mate'} = $matelen;
526                         } else {
527                                 $info->{'score_mate'} = -$matelen;
528                         }
529                 }
530                 $info->{'pv'} = $pv;
531                 $info->{'tablebase'} = 1;
532         } else {
533                 $info->{'tablebase'} = 0;
534         }
535         
536         #
537         # Some programs _always_ report MultiPV, even with only one PV.
538         # In this case, we simply use that data as if MultiPV was never
539         # specified.
540         #
541         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
542                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
543                         if (exists($info->{$key . '1'})) {
544                                 $info->{$key} = $info->{$key . '1'};
545                         }
546                 }
547         }
548         
549         #
550         # Check the PVs first. if they're invalid, just wait, as our data
551         # is most likely out of sync. This isn't a very good solution, as
552         # it can frequently miss stuff, but it's good enough for most users.
553         #
554         eval {
555                 my $dummy;
556                 if (exists($info->{'pv'})) {
557                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
558                 }
559         
560                 my $mpv = 1;
561                 while (exists($info->{'pv' . $mpv})) {
562                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
563                         ++$mpv;
564                 }
565         };
566         if ($@) {
567                 $engine->{'info'} = {};
568                 return;
569         }
570
571         output_screen();
572         output_json();
573         $latest_update = [Time::HiRes::gettimeofday];
574 }
575
576 sub output_screen {
577         my $info = $engine->{'info'};
578         my $id = $engine->{'id'};
579
580         my $text = 'Analysis';
581         if ($pos_calculating->{'last_move'} ne 'none') {
582                 if ($pos_calculating->{'toplay'} eq 'W') {
583                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
584                 } else {
585                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
586                 }
587                 if (exists($id->{'name'})) {
588                         $text .= ',';
589                 }
590         }
591
592         if (exists($id->{'name'})) {
593                 $text .= " by $id->{'name'}:\n\n";
594         } else {
595                 $text .= ":\n\n";
596         }
597
598         return unless (exists($pos_calculating->{'board'}));
599                 
600         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
601                 # multi-PV
602                 my $mpv = 1;
603                 while (exists($info->{'pv' . $mpv})) {
604                         $text .= sprintf "  PV%2u", $mpv;
605                         my $score = short_score($info, $pos_calculating, $mpv);
606                         $text .= "  ($score)" if (defined($score));
607
608                         my $tbhits = '';
609                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
610                                 if ($info->{'tbhits' . $mpv} == 1) {
611                                         $tbhits = ", 1 tbhit";
612                                 } else {
613                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
614                                 }
615                         }
616
617                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
618                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
619                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
620                         }
621
622                         $text .= ":\n";
623                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
624                         $text .= "\n";
625                         ++$mpv;
626                 }
627         } else {
628                 # single-PV
629                 my $score = long_score($info, $pos_calculating, '');
630                 $text .= "  $score\n" if defined($score);
631                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
632                 $text .=  "\n";
633
634                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
635                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
636                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
637                 }
638                 if (exists($info->{'seldepth'})) {
639                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
640                 }
641                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
642                         if ($info->{'tbhits'} == 1) {
643                                 $text .= ", one Syzygy hit";
644                         } else {
645                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
646                         }
647                 }
648                 $text .= "\n\n";
649         }
650
651         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
652
653         my @refutation_lines = ();
654         if (defined($engine2)) {
655                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
656                         my $info = $engine2->{'info'};
657                         last if (!exists($info->{'pv' . $mpv}));
658                         eval {
659                                 my $pv = $info->{'pv' . $mpv};
660
661                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
662                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
663                                 if (scalar @pretty_pv > 5) {
664                                         @pretty_pv = @pretty_pv[0..4];
665                                         push @pretty_pv, "...";
666                                 }
667                                 my $key = $pretty_move;
668                                 my $line = sprintf("  %-6s %6s %3s  %s",
669                                         $pretty_move,
670                                         short_score($info, $pos_calculating_second_engine, $mpv),
671                                         "d" . $info->{'depth' . $mpv},
672                                         join(', ', @pretty_pv));
673                                 push @refutation_lines, [ $key, $line ];
674                         };
675                 }
676         }
677
678         if ($#refutation_lines >= 0) {
679                 $text .= "Shallow search of all legal moves:\n\n";
680                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
681                         $text .= $line->[1] . "\n";
682                 }
683                 $text .= "\n\n";        
684         }       
685
686         if ($last_text ne $text) {
687                 print "\e[H\e[2J"; # clear the screen
688                 print $text;
689                 $last_text = $text;
690         }
691 }
692
693 sub output_json {
694         my $info = $engine->{'info'};
695
696         my $json = {};
697         $json->{'position'} = $pos_calculating->to_json_hash();
698         $json->{'id'} = $engine->{'id'};
699         $json->{'score'} = long_score($info, $pos_calculating, '');
700         $json->{'short_score'} = short_score($info, $pos_calculating, '');
701
702         $json->{'nodes'} = $info->{'nodes'};
703         $json->{'nps'} = $info->{'nps'};
704         $json->{'depth'} = $info->{'depth'};
705         $json->{'tbhits'} = $info->{'tbhits'};
706         $json->{'seldepth'} = $info->{'seldepth'};
707         $json->{'tablebase'} = $info->{'tablebase'};
708
709         # single-PV only for now
710         $json->{'pv_uci'} = $info->{'pv'};
711         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
712
713         my %refutation_lines = ();
714         my @refutation_lines = ();
715         if (defined($engine2)) {
716                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
717                         my $info = $engine2->{'info'};
718                         my $pretty_move = "";
719                         my @pretty_pv = ();
720                         last if (!exists($info->{'pv' . $mpv}));
721
722                         eval {
723                                 my $pv = $info->{'pv' . $mpv};
724                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
725                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
726                                 $refutation_lines{$pv->[0]} = {
727                                         sort_key => $pretty_move,
728                                         depth => $info->{'depth' . $mpv},
729                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
730                                         pretty_score => short_score($info, $pos_calculating, $mpv),
731                                         pretty_move => $pretty_move,
732                                         pv_pretty => \@pretty_pv,
733                                 };
734                                 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
735                         };
736                 }
737         }
738         $json->{'refutation_lines'} = \%refutation_lines;
739
740         open my $fh, ">", $remoteglotconf::json_output . ".tmp"
741                 or return;
742         print $fh JSON::XS::encode_json($json);
743         close $fh;
744         rename($remoteglotconf::json_output . ".tmp", $remoteglotconf::json_output);
745 }
746
747 sub uciprint {
748         my ($engine, $msg) = @_;
749         $engine->print($msg);
750         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
751 }
752
753 sub short_score {
754         my ($info, $pos, $mpv) = @_;
755
756         my $invert = ($pos->{'toplay'} eq 'B');
757         if (defined($info->{'score_mate' . $mpv})) {
758                 if ($invert) {
759                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
760                 } else {
761                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
762                 }
763         } else {
764                 if (exists($info->{'score_cp' . $mpv})) {
765                         my $score = $info->{'score_cp' . $mpv} * 0.01;
766                         if ($score == 0) {
767                                 if ($info->{'tablebase'}) {
768                                         return "TB draw";
769                                 } else {
770                                         return " 0.00";
771                                 }
772                         }
773                         if ($invert) {
774                                 $score = -$score;
775                         }
776                         return sprintf "%+5.2f", $score;
777                 }
778         }
779
780         return undef;
781 }
782
783 sub score_sort_key {
784         my ($info, $pos, $mpv, $invert) = @_;
785
786         if (defined($info->{'score_mate' . $mpv})) {
787                 my $mate = $info->{'score_mate' . $mpv};
788                 my $score;
789                 if ($mate > 0) {
790                         # Side to move mates
791                         $score = 99999 - $mate;
792                 } else {
793                         # Side to move is getting mated (note the double negative for $mate)
794                         $score = -99999 - $mate;
795                 }
796                 if ($invert) {
797                         $score = -$score;
798                 }
799                 return $score;
800         } else {
801                 if (exists($info->{'score_cp' . $mpv})) {
802                         my $score = $info->{'score_cp' . $mpv};
803                         if ($invert) {
804                                 $score = -$score;
805                         }
806                         return $score;
807                 }
808         }
809
810         return undef;
811 }
812
813 sub long_score {
814         my ($info, $pos, $mpv) = @_;
815
816         if (defined($info->{'score_mate' . $mpv})) {
817                 my $mate = $info->{'score_mate' . $mpv};
818                 if ($pos->{'toplay'} eq 'B') {
819                         $mate = -$mate;
820                 }
821                 if ($mate > 0) {
822                         return sprintf "White mates in %u", $mate;
823                 } else {
824                         return sprintf "Black mates in %u", -$mate;
825                 }
826         } else {
827                 if (exists($info->{'score_cp' . $mpv})) {
828                         my $score = $info->{'score_cp' . $mpv} * 0.01;
829                         if ($score == 0) {
830                                 if ($info->{'tablebase'}) {
831                                         return "Theoretical draw";
832                                 } else {
833                                         return "Score:  0.00";
834                                 }
835                         }
836                         if ($pos->{'toplay'} eq 'B') {
837                                 $score = -$score;
838                         }
839                         return sprintf "Score: %+5.2f", $score;
840                 }
841         }
842
843         return undef;
844 }
845
846 my %book_cache = ();
847 sub book_info {
848         my ($fen, $board, $toplay) = @_;
849
850         if (exists($book_cache{$fen})) {
851                 return $book_cache{$fen};
852         }
853
854         my $ret = `./booklook $fen`;
855         return "" if ($ret =~ /Not found/ || $ret eq '');
856
857         my @moves = ();
858
859         for my $m (split /\n/, $ret) {
860                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
861
862                 my $pmove;
863                 if ($move eq '')  {
864                         $pmove = '(current)';
865                 } else {
866                         ($pmove) = prettyprint_pv_no_cache($board, $move);
867                         $pmove .= $annotation;
868                 }
869
870                 my $score;
871                 if ($toplay eq 'W') {
872                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
873                 } else {
874                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
875                 }
876                 my $n = $win + $draw + $lose;
877                 
878                 my $percent;
879                 if ($n == 0) {
880                         $percent = "     ";
881                 } else {
882                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
883                 }
884
885                 push @moves, [ $pmove, $n, $percent, $rating ];
886         }
887
888         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
889         
890         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
891         for my $m (@moves) {
892                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
893         }
894
895         return $text;
896 }
897
898 sub schedule_tb_lookup {
899         return if (!defined($remoteglotconf::tb_serial_key));
900         my $pos = $pos_waiting // $pos_calculating;
901         return if (exists($tb_cache{$pos->fen()}));
902
903         # If there's more than seven pieces, there's not going to be an answer,
904         # so don't bother.
905         return if ($pos->num_pieces() > 7);
906
907         # Max one at a time. If it's still relevant when it returns,
908         # schedule_tb_lookup() will be called again.
909         return if ($tb_lookup_running);
910
911         $tb_lookup_running = 1;
912         my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
913                 $remoteglotconf::tb_serial_key .
914                 '&auth.password=aquarium&type=0&fen=' . 
915                 URI::Escape::uri_escape($pos->fen());
916         print TBLOG "Downloading $url...\n";
917         AnyEvent::HTTP::http_get($url, sub {
918                 handle_tb_lookup_return(@_, $pos, $pos->fen());
919         });
920 }
921
922 sub handle_tb_lookup_return {
923         my ($body, $header, $pos, $fen) = @_;
924         print TBLOG "Response for [$fen]:\n";
925         print TBLOG $header . "\n\n";
926         print TBLOG $body . "\n\n";
927         eval {
928                 my $response = JSON::XS::decode_json($body);
929                 if ($response->{'ErrorCode'} != 0) {
930                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
931                 }
932                 my $state = $response->{'Response'}{'StateString'};
933                 if ($state eq 'COMPLETE') {
934                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
935                         if (!defined($pgn) || !$pgn->read_game()) {
936                                 warn "Error in parsing PGN\n";
937                         } else {
938                                 $pgn->quick_parse_game;
939                                 my $pvpos = $pos;
940                                 my $moves = $pgn->moves;
941                                 my @uci_moves = ();
942                                 for my $move (@$moves) {
943                                         my $uci_move;
944                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
945                                         push @uci_moves, $uci_move;
946                                 }
947                                 $tb_cache{$fen} = {
948                                         result => $pgn->result,
949                                         pv => \@uci_moves
950                                 };
951                                 output();
952                         }
953                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
954                         # Try again in a second. Note that if we have changed
955                         # position in the meantime, we might query a completely
956                         # different position! But that's fine.
957                 } else {
958                         die "Unknown response state " . $state;
959                 }
960
961                 # Wait a second before we schedule another one.
962                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
963                         $tb_lookup_running = 0;
964                         schedule_tb_lookup();
965                 });
966         };
967         if ($@) {
968                 warn "Error in tablebase lookup: $@";
969
970                 # Don't try this one again, but don't block new lookups either.
971                 $tb_lookup_running = 0;
972         }
973 }
974
975 sub open_engine {
976         my ($cmdline, $tag, $cb) = @_;
977         return undef if (!defined($cmdline));
978         return Engine->open($cmdline, $tag, $cb);
979 }
980
981 sub col_letter_to_num {
982         return ord(shift) - ord('a');
983 }
984
985 sub row_letter_to_num {
986         return 7 - (ord(shift) - ord('1'));
987 }
988
989 sub parse_uci_move {
990         my $move = shift;
991         my $from_col = col_letter_to_num(substr($move, 0, 1));
992         my $from_row = row_letter_to_num(substr($move, 1, 1));
993         my $to_col   = col_letter_to_num(substr($move, 2, 1));
994         my $to_row   = row_letter_to_num(substr($move, 3, 1));
995         my $promo    = substr($move, 4, 1);
996         return ($from_col, $from_row, $to_col, $to_row, $promo);
997 }