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