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