4e6edc68308f3524b252c765d61394126107f6cc
[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 $SIG{ALRM} = sub { output(); };
32 my $latest_update = 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 ($pos, $uci_move) = $pos->make_pretty_move($move);
270                         push @uci_moves, $uci_move;
271                 }
272                 $pos->{'history'} = \@uci_moves;
273                 $pos->{'pretty_history'} = $moves;
274
275                 # Sometimes, PGNs lose a move or two for a short while,
276                 # or people push out new ones non-atomically. 
277                 # Thus, if we PGN doesn't change names but becomes
278                 # shorter, we mistrust it for a few seconds.
279                 my $trust_pgn = 1;
280                 if (defined($last_pgn_white) && defined($last_pgn_black) &&
281                     $last_pgn_white eq $pgn->white &&
282                     $last_pgn_black eq $pgn->black &&
283                     scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
284                         if (++$pgn_hysteresis_counter < 3) {
285                                 $trust_pgn = 0; 
286                         }
287                 }
288                 if ($trust_pgn) {
289                         $last_pgn_white = $pgn->white;
290                         $last_pgn_black = $pgn->black;
291                         @last_pgn_uci_moves = @uci_moves;
292                         $pgn_hysteresis_counter = 0;
293                         handle_position($pos);
294                 }
295         }
296         
297         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
298                 fetch_pgn($url);
299         });
300 }
301
302 sub handle_position {
303         my ($pos) = @_;
304                 
305         # if this is already in the queue, ignore it
306         return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
307
308         # if we're already chewing on this and there's nothing else in the queue,
309         # also ignore it
310         return if (!defined($pos_waiting) && defined($pos_calculating) &&
311                  $pos->fen() eq $pos_calculating->fen());
312
313         # if we're already thinking on something, stop and wait for the engine
314         # to approve
315         if (defined($pos_calculating)) {
316                 if (!defined($pos_waiting)) {
317                         uciprint($engine, "stop");
318                 }
319                 if ($remoteglotconf::uci_assume_full_compliance) {
320                         $pos_waiting = $pos;
321                 } else {
322                         uciprint($engine, "position fen " . $pos->fen());
323                         uciprint($engine, "go infinite");
324                         $pos_calculating = $pos;
325                 }
326         } else {
327                 # it's wrong just to give the FEN (the move history is useful,
328                 # and per the UCI spec, we should really have sent "ucinewgame"),
329                 # but it's easier
330                 uciprint($engine, "position fen " . $pos->fen());
331                 uciprint($engine, "go infinite");
332                 $pos_calculating = $pos;
333         }
334
335         if (defined($engine2)) {
336                 if (defined($pos_calculating_second_engine)) {
337                         uciprint($engine2, "stop");
338                 } else {
339                         uciprint($engine2, "position fen " . $pos->fen());
340                         uciprint($engine2, "go infinite");
341                         $pos_calculating_second_engine = $pos;
342                 }
343                 $engine2->{'info'} = {};
344         }
345
346         $engine->{'info'} = {};
347         $last_move = time;
348
349         schedule_tb_lookup();
350
351         # 
352         # Output a command every move to note that we're
353         # still paying attention -- this is a good tradeoff,
354         # since if no move has happened in the last half
355         # hour, the analysis/relay has most likely stopped
356         # and we should stop hogging server resources.
357         #
358         $t->cmd("date");
359 }
360
361 sub parse_infos {
362         my ($engine, @x) = @_;
363         my $mpv = '';
364
365         my $info = $engine->{'info'};
366
367         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
368         for my $i (0..$#x - 1) {
369                 if ($x[$i] eq 'multipv') {
370                         $mpv = $x[$i + 1];
371                         next;
372                 }
373         }
374
375         while (scalar @x > 0) {
376                 if ($x[0] eq 'multipv') {
377                         # Dealt with above
378                         shift @x;
379                         shift @x;
380                         next;
381                 }
382                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
383                         my $key = shift @x;
384                         my $value = shift @x;
385                         $info->{$key} = $value;
386                         next;
387                 }
388                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
389                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
390                     $x[0] eq 'tbhits') {
391                         my $key = shift @x;
392                         my $value = shift @x;
393                         $info->{$key . $mpv} = $value;
394                         next;
395                 }
396                 if ($x[0] eq 'score') {
397                         shift @x;
398
399                         delete $info->{'score_cp' . $mpv};
400                         delete $info->{'score_mate' . $mpv};
401
402                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
403                                 if ($x[0] eq 'cp') {
404                                         shift @x;
405                                         $info->{'score_cp' . $mpv} = shift @x;
406                                 } elsif ($x[0] eq 'mate') {
407                                         shift @x;
408                                         $info->{'score_mate' . $mpv} = shift @x;
409                                 } else {
410                                         shift @x;
411                                 }
412                         }
413                         next;
414                 }
415                 if ($x[0] eq 'pv') {
416                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
417                         last;
418                 }
419                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
420                         last;
421                 }
422
423                 #print "unknown info '$x[0]', trying to recover...\n";
424                 #shift @x;
425                 die "Unknown info '" . join(',', @x) . "'";
426
427         }
428 }
429
430 sub parse_ids {
431         my ($engine, @x) = @_;
432
433         while (scalar @x > 0) {
434                 if ($x[0] =~ /^(name|author)$/) {
435                         my $key = shift @x;
436                         my $value = join(' ', @x);
437                         $engine->{'id'}{$key} = $value;
438                         last;
439                 }
440
441                 # unknown
442                 shift @x;
443         }
444 }
445
446 sub prettyprint_pv_no_cache {
447         my ($board, @pvs) = @_;
448
449         if (scalar @pvs == 0 || !defined($pvs[0])) {
450                 return ();
451         }
452
453         my $pv = shift @pvs;
454         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
455         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
456         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
457 }
458
459 sub prettyprint_pv {
460         my ($pos, @pvs) = @_;
461
462         my $cachekey = join('', @pvs);
463         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
464                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
465         } else {
466                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
467                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
468                 return @res;
469         }
470 }
471
472 sub output {
473         #return;
474
475         return if (!defined($pos_calculating));
476
477         # Don't update too often.
478         my $age = Time::HiRes::tv_interval($latest_update);
479         if ($age < $remoteglotconf::update_max_interval) {
480                 Time::HiRes::alarm($remoteglotconf::update_max_interval + 0.01 - $age);
481                 return;
482         }
483         
484         my $info = $engine->{'info'};
485
486         #
487         # If we have tablebase data from a previous lookup, replace the
488         # engine data with the data from the tablebase.
489         #
490         my $fen = $pos_calculating->fen();
491         if (exists($tb_cache{$fen})) {
492                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
493                         delete $info->{$key . '1'};
494                         delete $info->{$key};
495                 }
496                 $info->{'nodes'} = 0;
497                 $info->{'nps'} = 0;
498                 $info->{'depth'} = 0;
499                 $info->{'seldepth'} = 0;
500                 $info->{'tbhits'} = 0;
501
502                 my $t = $tb_cache{$fen};
503                 my $pv = $t->{'pv'};
504                 my $matelen = int((1 + scalar @$pv) / 2);
505                 if ($t->{'result'} eq '1/2-1/2') {
506                         $info->{'score_cp'} = 0;
507                 } elsif ($t->{'result'} eq '1-0') {
508                         if ($pos_calculating->{'toplay'} eq 'B') {
509                                 $info->{'score_mate'} = -$matelen;
510                         } else {
511                                 $info->{'score_mate'} = $matelen;
512                         }
513                 } else {
514                         if ($pos_calculating->{'toplay'} eq 'B') {
515                                 $info->{'score_mate'} = $matelen;
516                         } else {
517                                 $info->{'score_mate'} = -$matelen;
518                         }
519                 }
520                 $info->{'pv'} = $pv;
521                 $info->{'tablebase'} = 1;
522         } else {
523                 $info->{'tablebase'} = 0;
524         }
525         
526         #
527         # Some programs _always_ report MultiPV, even with only one PV.
528         # In this case, we simply use that data as if MultiPV was never
529         # specified.
530         #
531         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
532                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
533                         if (exists($info->{$key . '1'})) {
534                                 $info->{$key} = $info->{$key . '1'};
535                         }
536                 }
537         }
538         
539         #
540         # Check the PVs first. if they're invalid, just wait, as our data
541         # is most likely out of sync. This isn't a very good solution, as
542         # it can frequently miss stuff, but it's good enough for most users.
543         #
544         eval {
545                 my $dummy;
546                 if (exists($info->{'pv'})) {
547                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
548                 }
549         
550                 my $mpv = 1;
551                 while (exists($info->{'pv' . $mpv})) {
552                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
553                         ++$mpv;
554                 }
555         };
556         if ($@) {
557                 $engine->{'info'} = {};
558                 return;
559         }
560
561         output_screen();
562         output_json();
563         $latest_update = [Time::HiRes::gettimeofday];
564 }
565
566 sub output_screen {
567         my $info = $engine->{'info'};
568         my $id = $engine->{'id'};
569
570         my $text = 'Analysis';
571         if ($pos_calculating->{'last_move'} ne 'none') {
572                 if ($pos_calculating->{'toplay'} eq 'W') {
573                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
574                 } else {
575                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
576                 }
577                 if (exists($id->{'name'})) {
578                         $text .= ',';
579                 }
580         }
581
582         if (exists($id->{'name'})) {
583                 $text .= " by $id->{'name'}:\n\n";
584         } else {
585                 $text .= ":\n\n";
586         }
587
588         return unless (exists($pos_calculating->{'board'}));
589                 
590         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
591                 # multi-PV
592                 my $mpv = 1;
593                 while (exists($info->{'pv' . $mpv})) {
594                         $text .= sprintf "  PV%2u", $mpv;
595                         my $score = short_score($info, $pos_calculating, $mpv);
596                         $text .= "  ($score)" if (defined($score));
597
598                         my $tbhits = '';
599                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
600                                 if ($info->{'tbhits' . $mpv} == 1) {
601                                         $tbhits = ", 1 tbhit";
602                                 } else {
603                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
604                                 }
605                         }
606
607                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
608                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
609                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
610                         }
611
612                         $text .= ":\n";
613                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
614                         $text .= "\n";
615                         ++$mpv;
616                 }
617         } else {
618                 # single-PV
619                 my $score = long_score($info, $pos_calculating, '');
620                 $text .= "  $score\n" if defined($score);
621                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
622                 $text .=  "\n";
623
624                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
625                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
626                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
627                 }
628                 if (exists($info->{'seldepth'})) {
629                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
630                 }
631                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
632                         if ($info->{'tbhits'} == 1) {
633                                 $text .= ", one Syzygy hit";
634                         } else {
635                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
636                         }
637                 }
638                 $text .= "\n\n";
639         }
640
641         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
642
643         my @refutation_lines = ();
644         if (defined($engine2)) {
645                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
646                         my $info = $engine2->{'info'};
647                         last if (!exists($info->{'pv' . $mpv}));
648                         eval {
649                                 my $pv = $info->{'pv' . $mpv};
650
651                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
652                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
653                                 if (scalar @pretty_pv > 5) {
654                                         @pretty_pv = @pretty_pv[0..4];
655                                         push @pretty_pv, "...";
656                                 }
657                                 my $key = $pretty_move;
658                                 my $line = sprintf("  %-6s %6s %3s  %s",
659                                         $pretty_move,
660                                         short_score($info, $pos_calculating_second_engine, $mpv),
661                                         "d" . $info->{'depth' . $mpv},
662                                         join(', ', @pretty_pv));
663                                 push @refutation_lines, [ $key, $line ];
664                         };
665                 }
666         }
667
668         if ($#refutation_lines >= 0) {
669                 $text .= "Shallow search of all legal moves:\n\n";
670                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
671                         $text .= $line->[1] . "\n";
672                 }
673                 $text .= "\n\n";        
674         }       
675
676         if ($last_text ne $text) {
677                 print "\e[H\e[2J"; # clear the screen
678                 print $text;
679                 $last_text = $text;
680         }
681 }
682
683 sub output_json {
684         my $info = $engine->{'info'};
685
686         my $json = {};
687         $json->{'position'} = $pos_calculating->to_json_hash();
688         $json->{'id'} = $engine->{'id'};
689         $json->{'score'} = long_score($info, $pos_calculating, '');
690         $json->{'short_score'} = short_score($info, $pos_calculating, '');
691
692         $json->{'nodes'} = $info->{'nodes'};
693         $json->{'nps'} = $info->{'nps'};
694         $json->{'depth'} = $info->{'depth'};
695         $json->{'tbhits'} = $info->{'tbhits'};
696         $json->{'seldepth'} = $info->{'seldepth'};
697         $json->{'tablebase'} = $info->{'tablebase'};
698
699         # single-PV only for now
700         $json->{'pv_uci'} = $info->{'pv'};
701         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
702
703         my %refutation_lines = ();
704         my @refutation_lines = ();
705         if (defined($engine2)) {
706                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
707                         my $info = $engine2->{'info'};
708                         my $pretty_move = "";
709                         my @pretty_pv = ();
710                         last if (!exists($info->{'pv' . $mpv}));
711
712                         eval {
713                                 my $pv = $info->{'pv' . $mpv};
714                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
715                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
716                                 $refutation_lines{$pv->[0]} = {
717                                         sort_key => $pretty_move,
718                                         depth => $info->{'depth' . $mpv},
719                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
720                                         pretty_score => short_score($info, $pos_calculating, $mpv),
721                                         pretty_move => $pretty_move,
722                                         pv_pretty => \@pretty_pv,
723                                 };
724                                 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
725                         };
726                 }
727         }
728         $json->{'refutation_lines'} = \%refutation_lines;
729
730         open my $fh, ">", $remoteglotconf::json_output . ".tmp"
731                 or return;
732         print $fh JSON::XS::encode_json($json);
733         close $fh;
734         rename($remoteglotconf::json_output . ".tmp", $remoteglotconf::json_output);
735 }
736
737 sub uciprint {
738         my ($engine, $msg) = @_;
739         $engine->print($msg);
740         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
741 }
742
743 sub short_score {
744         my ($info, $pos, $mpv) = @_;
745
746         my $invert = ($pos->{'toplay'} eq 'B');
747         if (defined($info->{'score_mate' . $mpv})) {
748                 if ($invert) {
749                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
750                 } else {
751                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
752                 }
753         } else {
754                 if (exists($info->{'score_cp' . $mpv})) {
755                         my $score = $info->{'score_cp' . $mpv} * 0.01;
756                         if ($score == 0) {
757                                 if ($info->{'tablebase'}) {
758                                         return "TB draw";
759                                 } else {
760                                         return " 0.00";
761                                 }
762                         }
763                         if ($invert) {
764                                 $score = -$score;
765                         }
766                         return sprintf "%+5.2f", $score;
767                 }
768         }
769
770         return undef;
771 }
772
773 sub score_sort_key {
774         my ($info, $pos, $mpv, $invert) = @_;
775
776         if (defined($info->{'score_mate' . $mpv})) {
777                 my $mate = $info->{'score_mate' . $mpv};
778                 my $score;
779                 if ($mate > 0) {
780                         # Side to move mates
781                         $score = 99999 - $mate;
782                 } else {
783                         # Side to move is getting mated (note the double negative for $mate)
784                         $score = -99999 - $mate;
785                 }
786                 if ($invert) {
787                         $score = -$score;
788                 }
789                 return $score;
790         } else {
791                 if (exists($info->{'score_cp' . $mpv})) {
792                         my $score = $info->{'score_cp' . $mpv};
793                         if ($invert) {
794                                 $score = -$score;
795                         }
796                         return $score;
797                 }
798         }
799
800         return undef;
801 }
802
803 sub long_score {
804         my ($info, $pos, $mpv) = @_;
805
806         if (defined($info->{'score_mate' . $mpv})) {
807                 my $mate = $info->{'score_mate' . $mpv};
808                 if ($pos->{'toplay'} eq 'B') {
809                         $mate = -$mate;
810                 }
811                 if ($mate > 0) {
812                         return sprintf "White mates in %u", $mate;
813                 } else {
814                         return sprintf "Black mates in %u", -$mate;
815                 }
816         } else {
817                 if (exists($info->{'score_cp' . $mpv})) {
818                         my $score = $info->{'score_cp' . $mpv} * 0.01;
819                         if ($score == 0) {
820                                 if ($info->{'tablebase'}) {
821                                         return "Theoretical draw";
822                                 } else {
823                                         return "Score:  0.00";
824                                 }
825                         }
826                         if ($pos->{'toplay'} eq 'B') {
827                                 $score = -$score;
828                         }
829                         return sprintf "Score: %+5.2f", $score;
830                 }
831         }
832
833         return undef;
834 }
835
836 my %book_cache = ();
837 sub book_info {
838         my ($fen, $board, $toplay) = @_;
839
840         if (exists($book_cache{$fen})) {
841                 return $book_cache{$fen};
842         }
843
844         my $ret = `./booklook $fen`;
845         return "" if ($ret =~ /Not found/ || $ret eq '');
846
847         my @moves = ();
848
849         for my $m (split /\n/, $ret) {
850                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
851
852                 my $pmove;
853                 if ($move eq '')  {
854                         $pmove = '(current)';
855                 } else {
856                         ($pmove) = prettyprint_pv_no_cache($board, $move);
857                         $pmove .= $annotation;
858                 }
859
860                 my $score;
861                 if ($toplay eq 'W') {
862                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
863                 } else {
864                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
865                 }
866                 my $n = $win + $draw + $lose;
867                 
868                 my $percent;
869                 if ($n == 0) {
870                         $percent = "     ";
871                 } else {
872                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
873                 }
874
875                 push @moves, [ $pmove, $n, $percent, $rating ];
876         }
877
878         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
879         
880         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
881         for my $m (@moves) {
882                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
883         }
884
885         return $text;
886 }
887
888 sub schedule_tb_lookup {
889         return if (!defined($remoteglotconf::tb_serial_key));
890         my $pos = $pos_waiting // $pos_calculating;
891         return if (exists($tb_cache{$pos->fen()}));
892
893         # If there's more than seven pieces, there's not going to be an answer,
894         # so don't bother.
895         return if ($pos->num_pieces() > 7);
896
897         # Max one at a time. If it's still relevant when it returns,
898         # schedule_tb_lookup() will be called again.
899         return if ($tb_lookup_running);
900
901         $tb_lookup_running = 1;
902         my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
903                 $remoteglotconf::tb_serial_key .
904                 '&auth.password=aquarium&type=0&fen=' . 
905                 URI::Escape::uri_escape($pos->fen());
906         print TBLOG "Downloading $url...\n";
907         AnyEvent::HTTP::http_get($url, sub {
908                 handle_tb_lookup_return(@_, $pos, $pos->fen());
909         });
910 }
911
912 sub handle_tb_lookup_return {
913         my ($body, $header, $pos, $fen) = @_;
914         print TBLOG "Response for [$fen]:\n";
915         print TBLOG $header . "\n\n";
916         print TBLOG $body . "\n\n";
917         eval {
918                 my $response = JSON::XS::decode_json($body);
919                 if ($response->{'ErrorCode'} != 0) {
920                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
921                 }
922                 my $state = $response->{'Response'}{'StateString'};
923                 if ($state eq 'COMPLETE') {
924                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
925                         if (!defined($pgn) || !$pgn->read_game()) {
926                                 warn "Error in parsing PGN\n";
927                         } else {
928                                 $pgn->quick_parse_game;
929                                 my $pvpos = $pos;
930                                 my $moves = $pgn->moves;
931                                 my @uci_moves = ();
932                                 for my $move (@$moves) {
933                                         my ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
934                                         push @uci_moves, $uci_move;
935                                 }
936                                 $tb_cache{$fen} = {
937                                         result => $pgn->result,
938                                         pv => \@uci_moves
939                                 };
940                                 output();
941                         }
942                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
943                         # Try again in a second. Note that if we have changed
944                         # position in the meantime, we might query a completely
945                         # different position! But that's fine.
946                 } else {
947                         die "Unknown response state " . $state;
948                 }
949
950                 # Wait a second before we schedule another one.
951                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
952                         $tb_lookup_running = 0;
953                         schedule_tb_lookup();
954                 });
955         };
956         if ($@) {
957                 warn "Error in tablebase lookup: $@";
958
959                 # Don't try this one again, but don't block new lookups either.
960                 $tb_lookup_running = 0;
961         }
962 }
963
964 sub open_engine {
965         my ($cmdline, $tag, $cb) = @_;
966         return undef if (!defined($cmdline));
967         return Engine->open($cmdline, $tag, $cb);
968 }
969
970 sub col_letter_to_num {
971         return ord(shift) - ord('a');
972 }
973
974 sub row_letter_to_num {
975         return 7 - (ord(shift) - ord('1'));
976 }
977
978 sub parse_uci_move {
979         my $move = shift;
980         my $from_col = col_letter_to_num(substr($move, 0, 1));
981         my $from_row = row_letter_to_num(substr($move, 1, 1));
982         my $to_col   = col_letter_to_num(substr($move, 2, 1));
983         my $to_row   = row_letter_to_num(substr($move, 3, 1));
984         my $promo    = substr($move, 4, 1);
985         return ($from_col, $from_row, $to_col, $to_row, $promo);
986 }