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