]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Support defaulting to a PGN for fetching.
[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 sub handle_pgn {
204         my ($body, $header, $url) = @_;
205         my $pgn = Chess::PGN::Parse->new(undef, $body);
206         if (!defined($pgn) || !$pgn->read_game()) {
207                 warn "Error in parsing PGN from $url\n";
208         } else {
209                 $pgn->quick_parse_game;
210                 my $pos = Position->start_pos($pgn->white, $pgn->black);
211                 my $moves = $pgn->moves;
212                 my @uci_moves = ();
213                 for my $move (@$moves) {
214                         my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
215                         push @uci_moves, Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
216                         $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
217                 }
218                 $pos->{'history'} = \@uci_moves;
219                 $pos->{'pretty_history'} = $moves;
220                 handle_position($pos);
221         }
222         
223         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
224                 fetch_pgn($url);
225         });
226 }
227
228 sub handle_position {
229         my ($pos) = @_;
230                 
231         # if this is already in the queue, ignore it
232         return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
233
234         # if we're already chewing on this and there's nothing else in the queue,
235         # also ignore it
236         return if (!defined($pos_waiting) && defined($pos_calculating) &&
237                  $pos->fen() eq $pos_calculating->fen());
238
239         # if we're already thinking on something, stop and wait for the engine
240         # to approve
241         if (defined($pos_calculating)) {
242                 if (!defined($pos_waiting)) {
243                         uciprint($engine, "stop");
244                 }
245                 if ($remoteglotconf::uci_assume_full_compliance) {
246                         $pos_waiting = $pos;
247                 } else {
248                         uciprint($engine, "position fen " . $pos->fen());
249                         uciprint($engine, "go infinite");
250                         $pos_calculating = $pos;
251                 }
252         } else {
253                 # it's wrong just to give the FEN (the move history is useful,
254                 # and per the UCI spec, we should really have sent "ucinewgame"),
255                 # but it's easier
256                 uciprint($engine, "position fen " . $pos->fen());
257                 uciprint($engine, "go infinite");
258                 $pos_calculating = $pos;
259         }
260
261         if (defined($engine2)) {
262                 if (defined($pos_calculating_second_engine)) {
263                         uciprint($engine2, "stop");
264                 } else {
265                         uciprint($engine2, "position fen " . $pos->fen());
266                         uciprint($engine2, "go infinite");
267                         $pos_calculating_second_engine = $pos;
268                 }
269                 $engine2->{'info'} = {};
270         }
271
272         $engine->{'info'} = {};
273         $last_move = time;
274
275         schedule_tb_lookup();
276
277         # 
278         # Output a command every move to note that we're
279         # still paying attention -- this is a good tradeoff,
280         # since if no move has happened in the last half
281         # hour, the analysis/relay has most likely stopped
282         # and we should stop hogging server resources.
283         #
284         $t->cmd("date");
285 }
286
287 sub parse_infos {
288         my ($engine, @x) = @_;
289         my $mpv = '';
290
291         my $info = $engine->{'info'};
292
293         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
294         for my $i (0..$#x - 1) {
295                 if ($x[$i] eq 'multipv') {
296                         $mpv = $x[$i + 1];
297                         next;
298                 }
299         }
300
301         while (scalar @x > 0) {
302                 if ($x[0] eq 'multipv') {
303                         # Dealt with above
304                         shift @x;
305                         shift @x;
306                         next;
307                 }
308                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
309                         my $key = shift @x;
310                         my $value = shift @x;
311                         $info->{$key} = $value;
312                         next;
313                 }
314                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
315                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
316                     $x[0] eq 'tbhits') {
317                         my $key = shift @x;
318                         my $value = shift @x;
319                         $info->{$key . $mpv} = $value;
320                         next;
321                 }
322                 if ($x[0] eq 'score') {
323                         shift @x;
324
325                         delete $info->{'score_cp' . $mpv};
326                         delete $info->{'score_mate' . $mpv};
327
328                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
329                                 if ($x[0] eq 'cp') {
330                                         shift @x;
331                                         $info->{'score_cp' . $mpv} = shift @x;
332                                 } elsif ($x[0] eq 'mate') {
333                                         shift @x;
334                                         $info->{'score_mate' . $mpv} = shift @x;
335                                 } else {
336                                         shift @x;
337                                 }
338                         }
339                         next;
340                 }
341                 if ($x[0] eq 'pv') {
342                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
343                         last;
344                 }
345                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
346                         last;
347                 }
348
349                 #print "unknown info '$x[0]', trying to recover...\n";
350                 #shift @x;
351                 die "Unknown info '" . join(',', @x) . "'";
352
353         }
354 }
355
356 sub parse_ids {
357         my ($engine, @x) = @_;
358
359         while (scalar @x > 0) {
360                 if ($x[0] =~ /^(name|author)$/) {
361                         my $key = shift @x;
362                         my $value = join(' ', @x);
363                         $engine->{'id'}{$key} = $value;
364                         last;
365                 }
366
367                 # unknown
368                 shift @x;
369         }
370 }
371
372 sub prettyprint_pv_no_cache {
373         my ($board, @pvs) = @_;
374
375         if (scalar @pvs == 0 || !defined($pvs[0])) {
376                 return ();
377         }
378
379         my $pv = shift @pvs;
380         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
381         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
382         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
383 }
384
385 sub prettyprint_pv {
386         my ($pos, @pvs) = @_;
387
388         my $cachekey = join('', @pvs);
389         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
390                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
391         } else {
392                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
393                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
394                 return @res;
395         }
396 }
397
398 sub output {
399         #return;
400
401         return if (!defined($pos_calculating));
402
403         # Don't update too often.
404         my $age = Time::HiRes::tv_interval($latest_update);
405         if ($age < $remoteglotconf::update_max_interval) {
406                 Time::HiRes::alarm($remoteglotconf::update_max_interval + 0.01 - $age);
407                 return;
408         }
409         
410         my $info = $engine->{'info'};
411
412         #
413         # If we have tablebase data from a previous lookup, replace the
414         # engine data with the data from the tablebase.
415         #
416         my $fen = $pos_calculating->fen();
417         if (exists($tb_cache{$fen})) {
418                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
419                         delete $info->{$key . '1'};
420                         delete $info->{$key};
421                 }
422                 $info->{'nodes'} = 0;
423                 $info->{'nps'} = 0;
424                 $info->{'depth'} = 0;
425                 $info->{'seldepth'} = 0;
426                 $info->{'tbhits'} = 0;
427
428                 my $t = $tb_cache{$fen};
429                 my $pv = $t->{'pv'};
430                 my $matelen = int((1 + scalar @$pv) / 2);
431                 if ($t->{'result'} eq '1/2-1/2') {
432                         $info->{'score_cp'} = 0;
433                 } elsif ($t->{'result'} eq '1-0') {
434                         if ($pos_calculating->{'toplay'} eq 'B') {
435                                 $info->{'score_mate'} = -$matelen;
436                         } else {
437                                 $info->{'score_mate'} = $matelen;
438                         }
439                 } else {
440                         if ($pos_calculating->{'toplay'} eq 'B') {
441                                 $info->{'score_mate'} = $matelen;
442                         } else {
443                                 $info->{'score_mate'} = -$matelen;
444                         }
445                 }
446                 $info->{'pv'} = $pv;
447                 $info->{'tablebase'} = 1;
448         } else {
449                 $info->{'tablebase'} = 0;
450         }
451         
452         #
453         # Some programs _always_ report MultiPV, even with only one PV.
454         # In this case, we simply use that data as if MultiPV was never
455         # specified.
456         #
457         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
458                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
459                         if (exists($info->{$key . '1'})) {
460                                 $info->{$key} = $info->{$key . '1'};
461                         }
462                 }
463         }
464         
465         #
466         # Check the PVs first. if they're invalid, just wait, as our data
467         # is most likely out of sync. This isn't a very good solution, as
468         # it can frequently miss stuff, but it's good enough for most users.
469         #
470         eval {
471                 my $dummy;
472                 if (exists($info->{'pv'})) {
473                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
474                 }
475         
476                 my $mpv = 1;
477                 while (exists($info->{'pv' . $mpv})) {
478                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
479                         ++$mpv;
480                 }
481         };
482         if ($@) {
483                 $engine->{'info'} = {};
484                 return;
485         }
486
487         output_screen();
488         output_json();
489         $latest_update = [Time::HiRes::gettimeofday];
490 }
491
492 sub output_screen {
493         my $info = $engine->{'info'};
494         my $id = $engine->{'id'};
495
496         my $text = 'Analysis';
497         if ($pos_calculating->{'last_move'} ne 'none') {
498                 if ($pos_calculating->{'toplay'} eq 'W') {
499                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
500                 } else {
501                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
502                 }
503                 if (exists($id->{'name'})) {
504                         $text .= ',';
505                 }
506         }
507
508         if (exists($id->{'name'})) {
509                 $text .= " by $id->{'name'}:\n\n";
510         } else {
511                 $text .= ":\n\n";
512         }
513
514         return unless (exists($pos_calculating->{'board'}));
515                 
516         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
517                 # multi-PV
518                 my $mpv = 1;
519                 while (exists($info->{'pv' . $mpv})) {
520                         $text .= sprintf "  PV%2u", $mpv;
521                         my $score = short_score($info, $pos_calculating, $mpv);
522                         $text .= "  ($score)" if (defined($score));
523
524                         my $tbhits = '';
525                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
526                                 if ($info->{'tbhits' . $mpv} == 1) {
527                                         $tbhits = ", 1 tbhit";
528                                 } else {
529                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
530                                 }
531                         }
532
533                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
534                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
535                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
536                         }
537
538                         $text .= ":\n";
539                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
540                         $text .= "\n";
541                         ++$mpv;
542                 }
543         } else {
544                 # single-PV
545                 my $score = long_score($info, $pos_calculating, '');
546                 $text .= "  $score\n" if defined($score);
547                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
548                 $text .=  "\n";
549
550                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
551                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
552                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
553                 }
554                 if (exists($info->{'seldepth'})) {
555                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
556                 }
557                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
558                         if ($info->{'tbhits'} == 1) {
559                                 $text .= ", one Syzygy hit";
560                         } else {
561                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
562                         }
563                 }
564                 $text .= "\n\n";
565         }
566
567         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
568
569         my @refutation_lines = ();
570         if (defined($engine2)) {
571                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
572                         my $info = $engine2->{'info'};
573                         last if (!exists($info->{'pv' . $mpv}));
574                         eval {
575                                 my $pv = $info->{'pv' . $mpv};
576
577                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
578                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
579                                 if (scalar @pretty_pv > 5) {
580                                         @pretty_pv = @pretty_pv[0..4];
581                                         push @pretty_pv, "...";
582                                 }
583                                 my $key = $pretty_move;
584                                 my $line = sprintf("  %-6s %6s %3s  %s",
585                                         $pretty_move,
586                                         short_score($info, $pos_calculating_second_engine, $mpv),
587                                         "d" . $info->{'depth' . $mpv},
588                                         join(', ', @pretty_pv));
589                                 push @refutation_lines, [ $key, $line ];
590                         };
591                 }
592         }
593
594         if ($#refutation_lines >= 0) {
595                 $text .= "Shallow search of all legal moves:\n\n";
596                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
597                         $text .= $line->[1] . "\n";
598                 }
599                 $text .= "\n\n";        
600         }       
601
602         if ($last_text ne $text) {
603                 print "\e[H\e[2J"; # clear the screen
604                 print $text;
605                 $last_text = $text;
606         }
607 }
608
609 sub output_json {
610         my $info = $engine->{'info'};
611
612         my $json = {};
613         $json->{'position'} = $pos_calculating->to_json_hash();
614         $json->{'id'} = $engine->{'id'};
615         $json->{'score'} = long_score($info, $pos_calculating, '');
616         $json->{'short_score'} = short_score($info, $pos_calculating, '');
617
618         $json->{'nodes'} = $info->{'nodes'};
619         $json->{'nps'} = $info->{'nps'};
620         $json->{'depth'} = $info->{'depth'};
621         $json->{'tbhits'} = $info->{'tbhits'};
622         $json->{'seldepth'} = $info->{'seldepth'};
623         $json->{'tablebase'} = $info->{'tablebase'};
624
625         # single-PV only for now
626         $json->{'pv_uci'} = $info->{'pv'};
627         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
628
629         my %refutation_lines = ();
630         my @refutation_lines = ();
631         if (defined($engine2)) {
632                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
633                         my $info = $engine2->{'info'};
634                         my $pretty_move = "";
635                         my @pretty_pv = ();
636                         last if (!exists($info->{'pv' . $mpv}));
637
638                         eval {
639                                 my $pv = $info->{'pv' . $mpv};
640                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
641                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
642                                 $refutation_lines{$pv->[0]} = {
643                                         sort_key => $pretty_move,
644                                         depth => $info->{'depth' . $mpv},
645                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
646                                         pretty_score => short_score($info, $pos_calculating, $mpv),
647                                         pretty_move => $pretty_move,
648                                         pv_pretty => \@pretty_pv,
649                                 };
650                                 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
651                         };
652                 }
653         }
654         $json->{'refutation_lines'} = \%refutation_lines;
655
656         open my $fh, ">", $remoteglotconf::json_output . ".tmp"
657                 or return;
658         print $fh JSON::XS::encode_json($json);
659         close $fh;
660         rename($remoteglotconf::json_output . ".tmp", $remoteglotconf::json_output);
661 }
662
663 sub uciprint {
664         my ($engine, $msg) = @_;
665         $engine->print($msg);
666         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
667 }
668
669 sub short_score {
670         my ($info, $pos, $mpv) = @_;
671
672         my $invert = ($pos->{'toplay'} eq 'B');
673         if (defined($info->{'score_mate' . $mpv})) {
674                 if ($invert) {
675                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
676                 } else {
677                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
678                 }
679         } else {
680                 if (exists($info->{'score_cp' . $mpv})) {
681                         my $score = $info->{'score_cp' . $mpv} * 0.01;
682                         if ($score == 0) {
683                                 if ($info->{'tablebase'}) {
684                                         return "TB draw";
685                                 } else {
686                                         return " 0.00";
687                                 }
688                         }
689                         if ($invert) {
690                                 $score = -$score;
691                         }
692                         return sprintf "%+5.2f", $score;
693                 }
694         }
695
696         return undef;
697 }
698
699 sub score_sort_key {
700         my ($info, $pos, $mpv, $invert) = @_;
701
702         if (defined($info->{'score_mate' . $mpv})) {
703                 my $mate = $info->{'score_mate' . $mpv};
704                 my $score;
705                 if ($mate > 0) {
706                         # Side to move mates
707                         $score = 99999 - $mate;
708                 } else {
709                         # Side to move is getting mated (note the double negative for $mate)
710                         $score = -99999 - $mate;
711                 }
712                 if ($invert) {
713                         $score = -$score;
714                 }
715                 return $score;
716         } else {
717                 if (exists($info->{'score_cp' . $mpv})) {
718                         my $score = $info->{'score_cp' . $mpv};
719                         if ($invert) {
720                                 $score = -$score;
721                         }
722                         return $score;
723                 }
724         }
725
726         return undef;
727 }
728
729 sub long_score {
730         my ($info, $pos, $mpv) = @_;
731
732         if (defined($info->{'score_mate' . $mpv})) {
733                 my $mate = $info->{'score_mate' . $mpv};
734                 if ($pos->{'toplay'} eq 'B') {
735                         $mate = -$mate;
736                 }
737                 if ($mate > 0) {
738                         return sprintf "White mates in %u", $mate;
739                 } else {
740                         return sprintf "Black mates in %u", -$mate;
741                 }
742         } else {
743                 if (exists($info->{'score_cp' . $mpv})) {
744                         my $score = $info->{'score_cp' . $mpv} * 0.01;
745                         if ($score == 0) {
746                                 if ($info->{'tablebase'}) {
747                                         return "Theoretical draw";
748                                 } else {
749                                         return "Score:  0.00";
750                                 }
751                         }
752                         if ($pos->{'toplay'} eq 'B') {
753                                 $score = -$score;
754                         }
755                         return sprintf "Score: %+5.2f", $score;
756                 }
757         }
758
759         return undef;
760 }
761
762 my %book_cache = ();
763 sub book_info {
764         my ($fen, $board, $toplay) = @_;
765
766         if (exists($book_cache{$fen})) {
767                 return $book_cache{$fen};
768         }
769
770         my $ret = `./booklook $fen`;
771         return "" if ($ret =~ /Not found/ || $ret eq '');
772
773         my @moves = ();
774
775         for my $m (split /\n/, $ret) {
776                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
777
778                 my $pmove;
779                 if ($move eq '')  {
780                         $pmove = '(current)';
781                 } else {
782                         ($pmove) = prettyprint_pv_no_cache($board, $move);
783                         $pmove .= $annotation;
784                 }
785
786                 my $score;
787                 if ($toplay eq 'W') {
788                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
789                 } else {
790                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
791                 }
792                 my $n = $win + $draw + $lose;
793                 
794                 my $percent;
795                 if ($n == 0) {
796                         $percent = "     ";
797                 } else {
798                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
799                 }
800
801                 push @moves, [ $pmove, $n, $percent, $rating ];
802         }
803
804         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
805         
806         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
807         for my $m (@moves) {
808                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
809         }
810
811         return $text;
812 }
813
814 sub schedule_tb_lookup {
815         return if (!defined($remoteglotconf::tb_serial_key));
816         my $pos = $pos_waiting // $pos_calculating;
817         return if (exists($tb_cache{$pos->fen()}));
818
819         # If there's more than seven pieces, there's not going to be an answer,
820         # so don't bother.
821         return if ($pos->num_pieces() > 7);
822
823         # Max one at a time. If it's still relevant when it returns,
824         # schedule_tb_lookup() will be called again.
825         return if ($tb_lookup_running);
826
827         $tb_lookup_running = 1;
828         my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
829                 $remoteglotconf::tb_serial_key .
830                 '&auth.password=aquarium&type=0&fen=' . 
831                 URI::Escape::uri_escape($pos->fen());
832         print TBLOG "Downloading $url...\n";
833         AnyEvent::HTTP::http_get($url, sub {
834                 handle_tb_lookup_return(@_, $pos, $pos->fen());
835         });
836 }
837
838 sub handle_tb_lookup_return {
839         my ($body, $header, $pos, $fen) = @_;
840         print TBLOG "Response for [$fen]:\n";
841         print TBLOG $header . "\n\n";
842         print TBLOG $body . "\n\n";
843         eval {
844                 my $response = JSON::XS::decode_json($body);
845                 if ($response->{'ErrorCode'} != 0) {
846                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
847                 }
848                 my $state = $response->{'Response'}{'StateString'};
849                 if ($state eq 'COMPLETE') {
850                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
851                         if (!defined($pgn) || !$pgn->read_game()) {
852                                 warn "Error in parsing PGN\n";
853                         } else {
854                                 $pgn->quick_parse_game;
855                                 my $pvpos = $pos;
856                                 my $moves = $pgn->moves;
857                                 my @uci_moves = ();
858                                 for my $move (@$moves) {
859                                         my ($from_row, $from_col, $to_row, $to_col, $promo) = $pvpos->parse_pretty_move($move);
860                                         push @uci_moves, Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
861                                         $pvpos = $pvpos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
862                                 }
863                                 $tb_cache{$fen} = {
864                                         result => $pgn->result,
865                                         pv => \@uci_moves
866                                 };
867                                 output();
868                         }
869                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
870                         # Try again in a second. Note that if we have changed
871                         # position in the meantime, we might query a completely
872                         # different position! But that's fine.
873                 } else {
874                         die "Unknown response state " . $state;
875                 }
876
877                 # Wait a second before we schedule another one.
878                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
879                         $tb_lookup_running = 0;
880                         schedule_tb_lookup();
881                 });
882         };
883         if ($@) {
884                 warn "Error in tablebase lookup: $@";
885
886                 # Don't try this one again, but don't block new lookups either.
887                 $tb_lookup_running = 0;
888         }
889 }
890
891 sub open_engine {
892         my ($cmdline, $tag, $cb) = @_;
893         return undef if (!defined($cmdline));
894         return Engine->open($cmdline, $tag, $cb);
895 }
896
897 sub col_letter_to_num {
898         return ord(shift) - ord('a');
899 }
900
901 sub row_letter_to_num {
902         return 7 - (ord(shift) - ord('1'));
903 }
904
905 sub parse_uci_move {
906         my $move = shift;
907         my $from_col = col_letter_to_num(substr($move, 0, 1));
908         my $from_row = row_letter_to_num(substr($move, 1, 1));
909         my $to_col   = col_letter_to_num(substr($move, 2, 1));
910         my $to_row   = row_letter_to_num(substr($move, 3, 1));
911         my $promo    = substr($move, 4, 1);
912         return ($from_col, $from_row, $to_col, $to_row, $promo);
913 }