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