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