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