Be more flexible about clk comments.
[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
332         return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
333
334         # if we're already chewing on this and there's nothing else in the queue,
335         # also ignore it
336         return if (!defined($pos_waiting) && defined($pos_calculating) &&
337                  $pos->fen() eq $pos_calculating->fen());
338
339         # if we're already thinking on something, stop and wait for the engine
340         # to approve
341         if (defined($pos_calculating)) {
342                 # Store the final data we have for this position in the history,
343                 # with the precise clock information we just got from the new
344                 # position. (Historic positions store the clock at the end of
345                 # the position.)
346                 #
347                 # Do not output anything new to the main analysis; that's
348                 # going to be obsolete really soon.
349                 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
350                 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
351                 delete $pos_calculating->{'white_clock_target'};
352                 delete $pos_calculating->{'black_clock_target'};
353                 output_json(1);
354
355                 if (!defined($pos_waiting)) {
356                         uciprint($engine, "stop");
357                 }
358                 if ($remoteglotconf::uci_assume_full_compliance) {
359                         $pos_waiting = $pos;
360                 } else {
361                         uciprint($engine, "position fen " . $pos->fen());
362                         uciprint($engine, "go infinite");
363                         $pos_calculating = $pos;
364                 }
365         } else {
366                 # it's wrong just to give the FEN (the move history is useful,
367                 # and per the UCI spec, we should really have sent "ucinewgame"),
368                 # but it's easier
369                 uciprint($engine, "position fen " . $pos->fen());
370                 uciprint($engine, "go infinite");
371                 $pos_calculating = $pos;
372         }
373
374         if (defined($engine2)) {
375                 if (defined($pos_calculating_second_engine)) {
376                         uciprint($engine2, "stop");
377                 } else {
378                         uciprint($engine2, "position fen " . $pos->fen());
379                         uciprint($engine2, "go infinite");
380                         $pos_calculating_second_engine = $pos;
381                 }
382                 $engine2->{'info'} = {};
383         }
384
385         $engine->{'info'} = {};
386         $last_move = time;
387
388         schedule_tb_lookup();
389
390         # 
391         # Output a command every move to note that we're
392         # still paying attention -- this is a good tradeoff,
393         # since if no move has happened in the last half
394         # hour, the analysis/relay has most likely stopped
395         # and we should stop hogging server resources.
396         #
397         $t->cmd("date");
398 }
399
400 sub parse_infos {
401         my ($engine, @x) = @_;
402         my $mpv = '';
403
404         my $info = $engine->{'info'};
405
406         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
407         for my $i (0..$#x - 1) {
408                 if ($x[$i] eq 'multipv') {
409                         $mpv = $x[$i + 1];
410                         next;
411                 }
412         }
413
414         while (scalar @x > 0) {
415                 if ($x[0] eq 'multipv') {
416                         # Dealt with above
417                         shift @x;
418                         shift @x;
419                         next;
420                 }
421                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
422                         my $key = shift @x;
423                         my $value = shift @x;
424                         $info->{$key} = $value;
425                         next;
426                 }
427                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
428                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
429                     $x[0] eq 'tbhits') {
430                         my $key = shift @x;
431                         my $value = shift @x;
432                         $info->{$key . $mpv} = $value;
433                         next;
434                 }
435                 if ($x[0] eq 'score') {
436                         shift @x;
437
438                         delete $info->{'score_cp' . $mpv};
439                         delete $info->{'score_mate' . $mpv};
440
441                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
442                                 if ($x[0] eq 'cp') {
443                                         shift @x;
444                                         $info->{'score_cp' . $mpv} = shift @x;
445                                 } elsif ($x[0] eq 'mate') {
446                                         shift @x;
447                                         $info->{'score_mate' . $mpv} = shift @x;
448                                 } else {
449                                         shift @x;
450                                 }
451                         }
452                         next;
453                 }
454                 if ($x[0] eq 'pv') {
455                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
456                         last;
457                 }
458                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
459                         last;
460                 }
461
462                 #print "unknown info '$x[0]', trying to recover...\n";
463                 #shift @x;
464                 die "Unknown info '" . join(',', @x) . "'";
465
466         }
467 }
468
469 sub parse_ids {
470         my ($engine, @x) = @_;
471
472         while (scalar @x > 0) {
473                 if ($x[0] =~ /^(name|author)$/) {
474                         my $key = shift @x;
475                         my $value = join(' ', @x);
476                         $engine->{'id'}{$key} = $value;
477                         last;
478                 }
479
480                 # unknown
481                 shift @x;
482         }
483 }
484
485 sub prettyprint_pv_no_cache {
486         my ($board, @pvs) = @_;
487
488         if (scalar @pvs == 0 || !defined($pvs[0])) {
489                 return ();
490         }
491
492         my $pv = shift @pvs;
493         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
494         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
495         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
496 }
497
498 sub prettyprint_pv {
499         my ($pos, @pvs) = @_;
500
501         my $cachekey = join('', @pvs);
502         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
503                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
504         } else {
505                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
506                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
507                 return @res;
508         }
509 }
510
511 sub output {
512         #return;
513
514         return if (!defined($pos_calculating));
515
516         # Don't update too often.
517         my $age = Time::HiRes::tv_interval($latest_update);
518         if ($age < $remoteglotconf::update_max_interval) {
519                 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
520                 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
521                 return;
522         }
523         
524         my $info = $engine->{'info'};
525
526         #
527         # If we have tablebase data from a previous lookup, replace the
528         # engine data with the data from the tablebase.
529         #
530         my $fen = $pos_calculating->fen();
531         if (exists($tb_cache{$fen})) {
532                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
533                         delete $info->{$key . '1'};
534                         delete $info->{$key};
535                 }
536                 $info->{'nodes'} = 0;
537                 $info->{'nps'} = 0;
538                 $info->{'depth'} = 0;
539                 $info->{'seldepth'} = 0;
540                 $info->{'tbhits'} = 0;
541
542                 my $t = $tb_cache{$fen};
543                 my $pv = $t->{'pv'};
544                 my $matelen = int((1 + $t->{'score'}) / 2);
545                 if ($t->{'result'} eq '1/2-1/2') {
546                         $info->{'score_cp'} = 0;
547                 } elsif ($t->{'result'} eq '1-0') {
548                         if ($pos_calculating->{'toplay'} eq 'B') {
549                                 $info->{'score_mate'} = -$matelen;
550                         } else {
551                                 $info->{'score_mate'} = $matelen;
552                         }
553                 } else {
554                         if ($pos_calculating->{'toplay'} eq 'B') {
555                                 $info->{'score_mate'} = $matelen;
556                         } else {
557                                 $info->{'score_mate'} = -$matelen;
558                         }
559                 }
560                 $info->{'pv'} = $pv;
561                 $info->{'tablebase'} = 1;
562         } else {
563                 $info->{'tablebase'} = 0;
564         }
565         
566         #
567         # Some programs _always_ report MultiPV, even with only one PV.
568         # In this case, we simply use that data as if MultiPV was never
569         # specified.
570         #
571         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
572                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
573                         if (exists($info->{$key . '1'})) {
574                                 $info->{$key} = $info->{$key . '1'};
575                         }
576                 }
577         }
578         
579         #
580         # Check the PVs first. if they're invalid, just wait, as our data
581         # is most likely out of sync. This isn't a very good solution, as
582         # it can frequently miss stuff, but it's good enough for most users.
583         #
584         eval {
585                 my $dummy;
586                 if (exists($info->{'pv'})) {
587                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
588                 }
589         
590                 my $mpv = 1;
591                 while (exists($info->{'pv' . $mpv})) {
592                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
593                         ++$mpv;
594                 }
595         };
596         if ($@) {
597                 $engine->{'info'} = {};
598                 return;
599         }
600
601         output_screen();
602         output_json(0);
603         $latest_update = [Time::HiRes::gettimeofday];
604 }
605
606 sub output_screen {
607         my $info = $engine->{'info'};
608         my $id = $engine->{'id'};
609
610         my $text = 'Analysis';
611         if ($pos_calculating->{'last_move'} ne 'none') {
612                 if ($pos_calculating->{'toplay'} eq 'W') {
613                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
614                 } else {
615                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
616                 }
617                 if (exists($id->{'name'})) {
618                         $text .= ',';
619                 }
620         }
621
622         if (exists($id->{'name'})) {
623                 $text .= " by $id->{'name'}:\n\n";
624         } else {
625                 $text .= ":\n\n";
626         }
627
628         return unless (exists($pos_calculating->{'board'}));
629                 
630         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
631                 # multi-PV
632                 my $mpv = 1;
633                 while (exists($info->{'pv' . $mpv})) {
634                         $text .= sprintf "  PV%2u", $mpv;
635                         my $score = short_score($info, $pos_calculating, $mpv);
636                         $text .= "  ($score)" if (defined($score));
637
638                         my $tbhits = '';
639                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
640                                 if ($info->{'tbhits' . $mpv} == 1) {
641                                         $tbhits = ", 1 tbhit";
642                                 } else {
643                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
644                                 }
645                         }
646
647                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
648                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
649                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
650                         }
651
652                         $text .= ":\n";
653                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
654                         $text .= "\n";
655                         ++$mpv;
656                 }
657         } else {
658                 # single-PV
659                 my $score = long_score($info, $pos_calculating, '');
660                 $text .= "  $score\n" if defined($score);
661                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
662                 $text .=  "\n";
663
664                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
665                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
666                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
667                 }
668                 if (exists($info->{'seldepth'})) {
669                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
670                 }
671                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
672                         if ($info->{'tbhits'} == 1) {
673                                 $text .= ", one Syzygy hit";
674                         } else {
675                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
676                         }
677                 }
678                 $text .= "\n\n";
679         }
680
681         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
682
683         my @refutation_lines = ();
684         if (defined($engine2)) {
685                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
686                         my $info = $engine2->{'info'};
687                         last if (!exists($info->{'pv' . $mpv}));
688                         eval {
689                                 my $pv = $info->{'pv' . $mpv};
690
691                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
692                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
693                                 if (scalar @pretty_pv > 5) {
694                                         @pretty_pv = @pretty_pv[0..4];
695                                         push @pretty_pv, "...";
696                                 }
697                                 my $key = $pretty_move;
698                                 my $line = sprintf("  %-6s %6s %3s  %s",
699                                         $pretty_move,
700                                         short_score($info, $pos_calculating_second_engine, $mpv),
701                                         "d" . $info->{'depth' . $mpv},
702                                         join(', ', @pretty_pv));
703                                 push @refutation_lines, [ $key, $line ];
704                         };
705                 }
706         }
707
708         if ($#refutation_lines >= 0) {
709                 $text .= "Shallow search of all legal moves:\n\n";
710                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
711                         $text .= $line->[1] . "\n";
712                 }
713                 $text .= "\n\n";        
714         }       
715
716         if ($last_text ne $text) {
717                 print "\e[H\e[2J"; # clear the screen
718                 print $text;
719                 $last_text = $text;
720         }
721 }
722
723 sub output_json {
724         my $historic_json_only = shift;
725         my $info = $engine->{'info'};
726
727         my $json = {};
728         $json->{'position'} = $pos_calculating->to_json_hash();
729         $json->{'id'} = $engine->{'id'};
730         $json->{'score'} = long_score($info, $pos_calculating, '');
731         $json->{'short_score'} = short_score($info, $pos_calculating, '');
732
733         $json->{'nodes'} = $info->{'nodes'};
734         $json->{'nps'} = $info->{'nps'};
735         $json->{'depth'} = $info->{'depth'};
736         $json->{'tbhits'} = $info->{'tbhits'};
737         $json->{'seldepth'} = $info->{'seldepth'};
738         $json->{'tablebase'} = $info->{'tablebase'};
739
740         $json->{'pv_uci'} = $info->{'pv'};  # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
741         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
742
743         my %refutation_lines = ();
744         my @refutation_lines = ();
745         if (defined($engine2)) {
746                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
747                         my $info = $engine2->{'info'};
748                         my $pretty_move = "";
749                         my @pretty_pv = ();
750                         last if (!exists($info->{'pv' . $mpv}));
751
752                         eval {
753                                 my $pv = $info->{'pv' . $mpv};
754                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
755                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
756                                 $refutation_lines{$pv->[0]} = {
757                                         sort_key => $pretty_move,
758                                         depth => $info->{'depth' . $mpv},
759                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
760                                         pretty_score => short_score($info, $pos_calculating, $mpv),
761                                         pretty_move => $pretty_move,
762                                         pv_pretty => \@pretty_pv,
763                                 };
764                         };
765                 }
766         }
767         $json->{'refutation_lines'} = \%refutation_lines;
768
769         my $encoded = JSON::XS::encode_json($json);
770         unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
771                 (defined($last_written_json) && $last_written_json eq $encoded)) {
772                 atomic_set_contents($remoteglotconf::json_output, $encoded);
773                 $last_written_json = $encoded;
774         }
775
776         if (exists($pos_calculating->{'pretty_history'}) &&
777             defined($remoteglotconf::json_history_dir)) {
778                 my $filename = $remoteglotconf::json_history_dir . "/" . id_for_pos($pos_calculating) . ".json";
779
780                 # Overwrite old analysis (assuming it exists at all) if we're
781                 # using a different engine, or if we've calculated deeper.
782                 # nodes is used as a tiebreaker. Don't bother about Multi-PV
783                 # data; it's not that important.
784                 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($filename);
785                 my $new_depth = $json->{'depth'} // 0;
786                 my $new_nodes = $json->{'nodes'} // 0;
787                 if (!defined($old_engine) ||
788                     $old_engine ne $json->{'id'}{'name'} ||
789                     $new_depth > $old_depth ||
790                     ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
791                         atomic_set_contents($filename, $encoded);
792                 }
793         }
794 }
795
796 sub atomic_set_contents {
797         my ($filename, $contents) = @_;
798
799         open my $fh, ">", $filename . ".tmp"
800                 or return;
801         print $fh $contents;
802         close $fh;
803         rename($filename . ".tmp", $filename);
804 }
805
806 sub id_for_pos {
807         my $pos = shift;
808
809         my $halfmove_num = scalar @{$pos->{'pretty_history'}};
810         (my $fen = $pos->fen()) =~ tr,/ ,-_,;
811         return "move$halfmove_num-$fen";
812 }
813
814 sub get_json_analysis_stats {
815         my $filename = shift;
816
817         my ($engine, $depth, $nodes);
818
819         open my $fh, "<", $filename
820                 or return undef;
821         local $/ = undef;
822         eval {
823                 my $json = JSON::XS::decode_json(<$fh>);
824                 $engine = $json->{'id'}{'name'} // die;
825                 $depth = $json->{'depth'} // 0;
826                 $nodes = $json->{'nodes'} // 0;
827         };
828         close $fh;
829         if ($@) {
830                 warn "Error in decoding $filename: $@";
831                 return undef;
832         }
833         return ($engine, $depth, $nodes);
834 }
835
836 sub uciprint {
837         my ($engine, $msg) = @_;
838         $engine->print($msg);
839         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
840 }
841
842 sub short_score {
843         my ($info, $pos, $mpv) = @_;
844
845         my $invert = ($pos->{'toplay'} eq 'B');
846         if (defined($info->{'score_mate' . $mpv})) {
847                 if ($invert) {
848                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
849                 } else {
850                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
851                 }
852         } else {
853                 if (exists($info->{'score_cp' . $mpv})) {
854                         my $score = $info->{'score_cp' . $mpv} * 0.01;
855                         if ($score == 0) {
856                                 if ($info->{'tablebase'}) {
857                                         return "TB draw";
858                                 } else {
859                                         return " 0.00";
860                                 }
861                         }
862                         if ($invert) {
863                                 $score = -$score;
864                         }
865                         return sprintf "%+5.2f", $score;
866                 }
867         }
868
869         return undef;
870 }
871
872 sub score_sort_key {
873         my ($info, $pos, $mpv, $invert) = @_;
874
875         if (defined($info->{'score_mate' . $mpv})) {
876                 my $mate = $info->{'score_mate' . $mpv};
877                 my $score;
878                 if ($mate > 0) {
879                         # Side to move mates
880                         $score = 99999 - $mate;
881                 } else {
882                         # Side to move is getting mated (note the double negative for $mate)
883                         $score = -99999 - $mate;
884                 }
885                 if ($invert) {
886                         $score = -$score;
887                 }
888                 return $score;
889         } else {
890                 if (exists($info->{'score_cp' . $mpv})) {
891                         my $score = $info->{'score_cp' . $mpv};
892                         if ($invert) {
893                                 $score = -$score;
894                         }
895                         return $score;
896                 }
897         }
898
899         return undef;
900 }
901
902 sub long_score {
903         my ($info, $pos, $mpv) = @_;
904
905         if (defined($info->{'score_mate' . $mpv})) {
906                 my $mate = $info->{'score_mate' . $mpv};
907                 if ($pos->{'toplay'} eq 'B') {
908                         $mate = -$mate;
909                 }
910                 if ($mate > 0) {
911                         return sprintf "White mates in %u", $mate;
912                 } else {
913                         return sprintf "Black mates in %u", -$mate;
914                 }
915         } else {
916                 if (exists($info->{'score_cp' . $mpv})) {
917                         my $score = $info->{'score_cp' . $mpv} * 0.01;
918                         if ($score == 0) {
919                                 if ($info->{'tablebase'}) {
920                                         return "Theoretical draw";
921                                 } else {
922                                         return "Score:  0.00";
923                                 }
924                         }
925                         if ($pos->{'toplay'} eq 'B') {
926                                 $score = -$score;
927                         }
928                         return sprintf "Score: %+5.2f", $score;
929                 }
930         }
931
932         return undef;
933 }
934
935 my %book_cache = ();
936 sub book_info {
937         my ($fen, $board, $toplay) = @_;
938
939         if (exists($book_cache{$fen})) {
940                 return $book_cache{$fen};
941         }
942
943         my $ret = `./booklook $fen`;
944         return "" if ($ret =~ /Not found/ || $ret eq '');
945
946         my @moves = ();
947
948         for my $m (split /\n/, $ret) {
949                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
950
951                 my $pmove;
952                 if ($move eq '')  {
953                         $pmove = '(current)';
954                 } else {
955                         ($pmove) = prettyprint_pv_no_cache($board, $move);
956                         $pmove .= $annotation;
957                 }
958
959                 my $score;
960                 if ($toplay eq 'W') {
961                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
962                 } else {
963                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
964                 }
965                 my $n = $win + $draw + $lose;
966                 
967                 my $percent;
968                 if ($n == 0) {
969                         $percent = "     ";
970                 } else {
971                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
972                 }
973
974                 push @moves, [ $pmove, $n, $percent, $rating ];
975         }
976
977         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
978         
979         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
980         for my $m (@moves) {
981                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
982         }
983
984         return $text;
985 }
986
987 sub extract_clock {
988         my ($pgn, $pos) = @_;
989
990         # Look for extended PGN clock tags.
991         my $tags = $pgn->tags;
992         if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
993                 $pos->{'white_clock'} = $tags->{'WhiteClock'};
994                 $pos->{'black_clock'} = $tags->{'BlackClock'};
995
996                 $pos->{'white_clock'} =~ s/\b(\d)\b/0$1/g;
997                 $pos->{'black_clock'} =~ s/\b(\d)\b/0$1/g;
998                 return;
999         }
1000
1001         # Look for TCEC-style time comments.
1002         my $moves = $pgn->moves;
1003         my $comments = $pgn->comments;
1004         my $last_black_move = int((scalar @$moves) / 2);
1005         my $last_white_move = int((1 + scalar @$moves) / 2);
1006
1007         my $black_key = $last_black_move . "b";
1008         my $white_key = $last_white_move . "w";
1009
1010         if (exists($comments->{$white_key}) &&
1011             exists($comments->{$black_key}) &&
1012             $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1013             $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1014                 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1015                 $pos->{'white_clock'} = $1;
1016                 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1017                 $pos->{'black_clock'} = $1;
1018
1019                 $pos->{'white_clock'} =~ s/\b(\d)\b/0$1/g;
1020                 $pos->{'black_clock'} =~ s/\b(\d)\b/0$1/g;
1021                 return;
1022         }
1023
1024         delete $pos->{'white_clock'};
1025         delete $pos->{'black_clock'};
1026 }
1027
1028 sub find_clock_start {
1029         my $pos = shift;
1030
1031         # If the game is over, the clock is stopped.
1032         if (exists($pos->{'result'}) &&
1033             ($pos->{'result'} eq '1-0' ||
1034              $pos->{'result'} eq '1/2-1/2' ||
1035              $pos->{'result'} eq '0-1')) {
1036                 return;
1037         }
1038
1039         # When we don't have any moves, we assume the clock hasn't started yet.
1040         if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1041                 return;
1042         }
1043
1044         # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1045         # The history is needed for id_for_pos.
1046         if (!exists($pos->{'pretty_history'})) {
1047                 return;
1048         }
1049
1050         my $id = id_for_pos($pos);
1051         if (exists($clock_target_for_pos{$id})) {
1052                 if ($pos->{'toplay'} eq 'W') {
1053                         $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1054                 } else {
1055                         $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1056                 }
1057                 return;
1058         }
1059
1060         # OK, we haven't seen this position before, so we assume the move
1061         # happened right now.
1062         my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1063         if (!exists($pos->{$key})) {
1064                 # No clock information.
1065                 return;
1066         }
1067         $pos->{$key} =~ /(\d+):(\d+):(\d+)/;
1068         my $time_left = $1 * 3600 + $2 * 60 + $3;
1069         $clock_target_for_pos{$id} = time + $time_left;
1070         if ($pos->{'toplay'} eq 'W') {
1071                 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1072         } else {
1073                 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1074         }
1075 }
1076
1077 sub schedule_tb_lookup {
1078         return if (!defined($remoteglotconf::tb_serial_key));
1079         my $pos = $pos_waiting // $pos_calculating;
1080         return if (exists($tb_cache{$pos->fen()}));
1081
1082         # If there's more than seven pieces, there's not going to be an answer,
1083         # so don't bother.
1084         return if ($pos->num_pieces() > 7);
1085
1086         # Max one at a time. If it's still relevant when it returns,
1087         # schedule_tb_lookup() will be called again.
1088         return if ($tb_lookup_running);
1089
1090         $tb_lookup_running = 1;
1091         my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1092                 $remoteglotconf::tb_serial_key .
1093                 '&auth.password=aquarium&type=0&fen=' . 
1094                 URI::Escape::uri_escape($pos->fen());
1095         print TBLOG "Downloading $url...\n";
1096         AnyEvent::HTTP::http_get($url, sub {
1097                 handle_tb_lookup_return(@_, $pos, $pos->fen());
1098         });
1099 }
1100
1101 sub handle_tb_lookup_return {
1102         my ($body, $header, $pos, $fen) = @_;
1103         print TBLOG "Response for [$fen]:\n";
1104         print TBLOG $header . "\n\n";
1105         print TBLOG $body . "\n\n";
1106         eval {
1107                 my $response = JSON::XS::decode_json($body);
1108                 if ($response->{'ErrorCode'} != 0) {
1109                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1110                 }
1111                 my $state = $response->{'Response'}{'StateString'};
1112                 if ($state eq 'COMPLETE') {
1113                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1114                         if (!defined($pgn) || !$pgn->read_game()) {
1115                                 warn "Error in parsing PGN\n";
1116                         } else {
1117                                 $pgn->quick_parse_game;
1118                                 my $pvpos = $pos;
1119                                 my $moves = $pgn->moves;
1120                                 my @uci_moves = ();
1121                                 for my $move (@$moves) {
1122                                         my $uci_move;
1123                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1124                                         push @uci_moves, $uci_move;
1125                                 }
1126                                 $tb_cache{$fen} = {
1127                                         result => $pgn->result,
1128                                         pv => \@uci_moves,
1129                                         score => $response->{'Response'}{'Score'},
1130                                 };
1131                                 output();
1132                         }
1133                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1134                         # Try again in a second. Note that if we have changed
1135                         # position in the meantime, we might query a completely
1136                         # different position! But that's fine.
1137                 } else {
1138                         die "Unknown response state " . $state;
1139                 }
1140
1141                 # Wait a second before we schedule another one.
1142                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1143                         $tb_lookup_running = 0;
1144                         schedule_tb_lookup();
1145                 });
1146         };
1147         if ($@) {
1148                 warn "Error in tablebase lookup: $@";
1149
1150                 # Don't try this one again, but don't block new lookups either.
1151                 $tb_lookup_running = 0;
1152         }
1153 }
1154
1155 sub open_engine {
1156         my ($cmdline, $tag, $cb) = @_;
1157         return undef if (!defined($cmdline));
1158         return Engine->open($cmdline, $tag, $cb);
1159 }
1160
1161 sub col_letter_to_num {
1162         return ord(shift) - ord('a');
1163 }
1164
1165 sub row_letter_to_num {
1166         return 7 - (ord(shift) - ord('1'));
1167 }
1168
1169 sub parse_uci_move {
1170         my $move = shift;
1171         my $from_col = col_letter_to_num(substr($move, 0, 1));
1172         my $from_row = row_letter_to_num(substr($move, 1, 1));
1173         my $to_col   = col_letter_to_num(substr($move, 2, 1));
1174         my $to_row   = row_letter_to_num(substr($move, 3, 1));
1175         my $promo    = substr($move, 4, 1);
1176         return ($from_col, $from_row, $to_col, $to_row, $promo);
1177 }