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