]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
7b650477c95d8fa6727e033ef7e413c02074100f
[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 Net::Telnet;
13 use FileHandle;
14 use IPC::Open2;
15 use Time::HiRes;
16 use JSON::XS;
17 require 'Position.pm';
18 use strict;
19 use warnings;
20
21 # Configuration
22 my $server = "freechess.org";
23 my $target = "GMCarlsen";
24 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
25 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";  # undef for none
26 my $telltarget = undef;   # undef to be silent
27 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960);  # after each move
28 my $uci_assume_full_compliance = 0;                    # dangerous :-)
29 my $update_max_interval = 1.0;
30 my @masters = (
31         'Sesse',
32         'Sessse',
33         'Sesssse',
34         'greatestguns',
35         'beuki'
36 );
37
38 # Program starts here
39 $SIG{ALRM} = sub { output(); };
40 my $latest_update = undef;
41
42 $| = 1;
43
44 open(FICSLOG, ">ficslog.txt")
45         or die "ficslog.txt: $!";
46 print FICSLOG "Log starting.\n";
47 select(FICSLOG);
48 $| = 1;
49
50 open(UCILOG, ">ucilog.txt")
51         or die "ucilog.txt: $!";
52 print UCILOG "Log starting.\n";
53 select(UCILOG);
54 $| = 1;
55 select(STDOUT);
56
57 # open the chess engine
58 my $engine = open_engine($engine_cmdline, 'E1');
59 my $engine2 = open_engine($engine2_cmdline, 'E2');
60 my ($last_move, $last_tell);
61 my $last_text = '';
62 my $last_told_text = '';
63 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
64
65 uciprint($engine, "setoption name UCI_AnalyseMode value true");
66 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
67 uciprint($engine, "setoption name NalimovUsage value Rarely");
68 uciprint($engine, "setoption name Hash value 1024");
69 # uciprint($engine, "setoption name MultiPV value 2");
70 uciprint($engine, "ucinewgame");
71
72 if (defined($engine2)) {
73         uciprint($engine2, "setoption name UCI_AnalyseMode value true");
74         # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
75         uciprint($engine2, "setoption name NalimovUsage value Rarely");
76         uciprint($engine2, "setoption name Hash value 1024");
77         uciprint($engine2, "setoption name Threads value 8");
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($server);
88 $t->print("SesseBOT");
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 $t->cmd("observe $target");
97
98 # main loop
99 print "FICS ready.\n";
100 while (1) {
101         my $rin = '';
102         my $rout;
103         vec($rin, fileno($engine->{'read'}), 1) = 1;
104         if (defined($engine2)) {
105                 vec($rin, fileno($engine2->{'read'}), 1) = 1;
106         }
107         vec($rin, fileno($t), 1) = 1;
108
109         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
110         my $sleep = 1.0;
111
112         while (1) {
113                 my $line = $t->getline(Timeout => 0, errmode => 'return');
114                 last if (!defined($line));
115
116                 chomp $line;
117                 $line =~ tr/\r//d;
118                 if ($line =~ /^<12> /) {
119                         my $pos = Position->new($line);
120                         
121                         # if this is already in the queue, ignore it
122                         next if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
123
124                         # if we're already chewing on this and there's nothing else in the queue,
125                         # also ignore it
126                         next if (!defined($pos_waiting) && defined($pos_calculating) &&
127                                  $pos->fen() eq $pos_calculating->fen());
128
129                         # if we're already thinking on something, stop and wait for the engine
130                         # to approve
131                         if (defined($pos_calculating)) {
132                                 if (!defined($pos_waiting)) {
133                                         uciprint($engine, "stop");
134                                 }
135                                 if ($uci_assume_full_compliance) {
136                                         $pos_waiting = $pos;
137                                 } else {
138                                         uciprint($engine, "position fen " . $pos->fen());
139                                         uciprint($engine, "go infinite");
140                                         $pos_calculating = $pos;
141                                 }
142                         } else {
143                                 # it's wrong just to give the FEN (the move history is useful,
144                                 # and per the UCI spec, we should really have sent "ucinewgame"),
145                                 # but it's easier
146                                 uciprint($engine, "position fen " . $pos->fen());
147                                 uciprint($engine, "go infinite");
148                                 $pos_calculating = $pos;
149                         }
150
151                         if (defined($engine2)) {
152                                 if (defined($pos_calculating_second_engine)) {
153                                         uciprint($engine2, "stop");
154                                 } else {
155                                         uciprint($engine2, "position fen " . $pos->fen());
156                                         uciprint($engine2, "go infinite");
157                                         $pos_calculating_second_engine = $pos;
158                                 }
159                                 $engine2->{'info'} = {};
160                         }
161
162                         $engine->{'info'} = {};
163                         $last_move = time;
164
165                         # 
166                         # Output a command every move to note that we're
167                         # still paying attention -- this is a good tradeoff,
168                         # since if no move has happened in the last half
169                         # hour, the analysis/relay has most likely stopped
170                         # and we should stop hogging server resources.
171                         #
172                         $t->cmd("date");
173                 }
174                 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
175                         my ($who, $msg) = ($1, $2);
176
177                         next if (grep { $_ eq $who } (@masters) == 0);
178         
179                         if ($msg =~ /^fics (.*?)$/) {
180                                 $t->cmd("tell $who Executing '$1' on FICS.");
181                                 $t->cmd($1);
182                         } elsif ($msg =~ /^uci (.*?)$/) {
183                                 $t->cmd("tell $who Sending '$1' to the engine.");
184                                 print { $engine->{'write'} } "$1\n";
185                         } else {
186                                 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
187                         }
188                 }
189                 #print "FICS: [$line]\n";
190                 $sleep = 0;
191         }
192         
193         # any fun on the UCI channel?
194         if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
195                 my @lines = read_lines($engine);
196                 for my $line (@lines) {
197                         next if $line =~ /(upper|lower)bound/;
198                         handle_uci($engine, $line, 1);
199                 }
200                 $sleep = 0;
201
202                 output();
203         }
204         if (defined($engine2) && $nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
205                 my @lines = read_lines($engine2);
206                 for my $line (@lines) {
207                         next if $line =~ /(upper|lower)bound/;
208                         handle_uci($engine2, $line, 0);
209                 }
210                 $sleep = 0;
211
212                 output();
213         }
214
215         sleep $sleep;
216 }
217
218 sub handle_uci {
219         my ($engine, $line, $primary) = @_;
220
221         chomp $line;
222         $line =~ tr/\r//d;
223         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
224         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
225         if ($line =~ /^info/) {
226                 my (@infos) = split / /, $line;
227                 shift @infos;
228
229                 parse_infos($engine, @infos);
230         }
231         if ($line =~ /^id/) {
232                 my (@ids) = split / /, $line;
233                 shift @ids;
234
235                 parse_ids($engine, @ids);
236         }
237         if ($line =~ /^bestmove/) {
238                 if ($primary) {
239                         return if (!$uci_assume_full_compliance);
240                         if (defined($pos_waiting)) {
241                                 uciprint($engine, "position fen " . $pos_waiting->fen());
242                                 uciprint($engine, "go infinite");
243
244                                 $pos_calculating = $pos_waiting;
245                                 $pos_waiting = undef;
246                         }
247                 } else {
248                         $engine2->{'info'} = {};
249                         my $pos = $pos_waiting // $pos_calculating;
250                         uciprint($engine2, "position fen " . $pos->fen());
251                         uciprint($engine2, "go infinite");
252                         $pos_calculating_second_engine = $pos;
253                 }
254         }
255 }
256
257 sub parse_infos {
258         my ($engine, @x) = @_;
259         my $mpv = '';
260
261         my $info = $engine->{'info'};
262
263         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
264         for my $i (0..$#x - 1) {
265                 if ($x[$i] =~ 'multipv') {
266                         $mpv = $x[$i + 1];
267                         next;
268                 }
269         }
270
271         while (scalar @x > 0) {
272                 if ($x[0] =~ 'multipv') {
273                         # Dealt with above
274                         shift @x;
275                         shift @x;
276                         next;
277                 }
278                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
279                         my $key = shift @x;
280                         my $value = shift @x;
281                         $info->{$key} = $value;
282                         next;
283                 }
284                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
285                         my $key = shift @x;
286                         my $value = shift @x;
287                         $info->{$key . $mpv} = $value;
288                         next;
289                 }
290                 if ($x[0] eq 'score') {
291                         shift @x;
292
293                         delete $info->{'score_cp' . $mpv};
294                         delete $info->{'score_mate' . $mpv};
295
296                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
297                                 if ($x[0] eq 'cp') {
298                                         shift @x;
299                                         $info->{'score_cp' . $mpv} = shift @x;
300                                 } elsif ($x[0] eq 'mate') {
301                                         shift @x;
302                                         $info->{'score_mate' . $mpv} = shift @x;
303                                 } else {
304                                         shift @x;
305                                 }
306                         }
307                         next;
308                 }
309                 if ($x[0] eq 'pv') {
310                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
311                         last;
312                 }
313                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
314                         last;
315                 }
316
317                 #print "unknown info '$x[0]', trying to recover...\n";
318                 #shift @x;
319                 die "Unknown info '" . join(',', @x) . "'";
320
321         }
322 }
323
324 sub parse_ids {
325         my ($engine, @x) = @_;
326
327         while (scalar @x > 0) {
328                 if ($x[0] =~ /^(name|author)$/) {
329                         my $key = shift @x;
330                         my $value = join(' ', @x);
331                         $engine->{'id'}{$key} = $value;
332                         last;
333                 }
334
335                 # unknown
336                 shift @x;
337         }
338 }
339
340 sub prettyprint_pv {
341         my ($board, @pvs) = @_;
342
343         if (scalar @pvs == 0 || !defined($pvs[0])) {
344                 return ();
345         }
346
347         my $pv = shift @pvs;
348         my $from_col = col_letter_to_num(substr($pv, 0, 1));
349         my $from_row = row_letter_to_num(substr($pv, 1, 1));
350         my $to_col   = col_letter_to_num(substr($pv, 2, 1));
351         my $to_row   = row_letter_to_num(substr($pv, 3, 1));
352         my $promo    = substr($pv, 4, 1);
353
354         my $nb = $board->make_move($from_row, $from_col, $to_row, $to_col, $promo);
355         my $piece = $board->[$from_row][$from_col];
356
357         if ($piece eq '-') {
358                 die "Invalid move $pv";
359         }
360
361         # white short castling
362         if ($pv eq 'e1g1' && $piece eq 'K') {
363                 return ('0-0', prettyprint_pv($nb, @pvs));
364         }
365
366         # white long castling
367         if ($pv eq 'e1c1' && $piece eq 'K') {
368                 return ('0-0-0', prettyprint_pv($nb, @pvs));
369         }
370
371         # black short castling
372         if ($pv eq 'e8g8' && $piece eq 'k') {
373                 return ('0-0', prettyprint_pv($nb, @pvs));
374         }
375
376         # black long castling
377         if ($pv eq 'e8c8' && $piece eq 'k') {
378                 return ('0-0-0', prettyprint_pv($nb, @pvs));
379         }
380
381         my $pretty;
382
383         # check if the from-piece is a pawn
384         if (lc($piece) eq 'p') {
385                 # attack?
386                 if ($from_col != $to_col) {
387                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
388                 } else {
389                         $pretty = substr($pv, 2, 2);
390
391                         if (length($pv) == 5) {
392                                 # promotion
393                                 $pretty .= "=";
394                                 $pretty .= uc(substr($pv, 4, 1));
395
396                                 if ($piece eq 'p') {
397                                         $piece = substr($pv, 4, 1);
398                                 } else {
399                                         $piece = uc(substr($pv, 4, 1));
400                                 }
401                         }
402                 }
403         } else {
404                 $pretty = uc($piece);
405
406                 # see how many of these pieces could go here, in all
407                 my $num_total = 0;
408                 for my $col (0..7) {
409                         for my $row (0..7) {
410                                 next unless ($board->[$row][$col] eq $piece);
411                                 ++$num_total if ($board->can_reach($piece, $row, $col, $to_row, $to_col));
412                         }
413                 }
414
415                 # see how many of these pieces from the given row could go here
416                 my $num_row = 0;
417                 for my $col (0..7) {
418                         next unless ($board->[$from_row][$col] eq $piece);
419                         ++$num_row if ($board->can_reach($piece, $from_row, $col, $to_row, $to_col));
420                 }
421                 
422                 # and same for columns
423                 my $num_col = 0;
424                 for my $row (0..7) {
425                         next unless ($board->[$row][$from_col] eq $piece);
426                         ++$num_col if ($board->can_reach($piece, $row, $from_col, $to_row, $to_col));
427                 }
428                 
429                 # see if we need to disambiguate
430                 if ($num_total > 1) {
431                         if ($num_col == 1) {
432                                 $pretty .= substr($pv, 0, 1);
433                         } elsif ($num_row == 1) {
434                                 $pretty .= substr($pv, 1, 1);
435                         } else {
436                                 $pretty .= substr($pv, 0, 2);
437                         }
438                 }
439
440                 # attack?
441                 if ($board->[$to_row][$to_col] ne '-') {
442                         $pretty .= 'x';
443                 }
444
445                 $pretty .= substr($pv, 2, 2);
446         }
447
448         if ($nb->in_mate()) {
449                 $pretty .= '#';
450         } elsif ($nb->in_check() ne 'none') {
451                 $pretty .= '+';
452         }
453         return ($pretty, prettyprint_pv($nb, @pvs));
454 }
455
456 sub output {
457         #return;
458
459         return if (!defined($pos_calculating));
460
461         # Don't update too often.
462         my $age = Time::HiRes::tv_interval($latest_update);
463         if ($age < $update_max_interval) {
464                 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
465                 return;
466         }
467         
468         my $info = $engine->{'info'};
469         
470         #
471         # Some programs _always_ report MultiPV, even with only one PV.
472         # In this case, we simply use that data as if MultiPV was never
473         # specified.
474         #
475         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
476                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
477                         if (exists($info->{$key . '1'})) {
478                                 $info->{$key} = $info->{$key . '1'};
479                         }
480                 }
481         }
482         
483         #
484         # Check the PVs first. if they're invalid, just wait, as our data
485         # is most likely out of sync. This isn't a very good solution, as
486         # it can frequently miss stuff, but it's good enough for most users.
487         #
488         eval {
489                 my $dummy;
490                 if (exists($info->{'pv'})) {
491                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
492                 }
493         
494                 my $mpv = 1;
495                 while (exists($info->{'pv' . $mpv})) {
496                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
497                         ++$mpv;
498                 }
499         };
500         if ($@) {
501                 $engine->{'info'} = {};
502                 return;
503         }
504
505         output_screen();
506         output_json();
507         $latest_update = [Time::HiRes::gettimeofday];
508 }
509
510 sub output_screen {
511         my $info = $engine->{'info'};
512         my $id = $engine->{'id'};
513
514         my $text = 'Analysis';
515         if ($pos_calculating->{'last_move'} ne 'none') {
516                 if ($pos_calculating->{'toplay'} eq 'W') {
517                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
518                 } else {
519                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
520                 }
521                 if (exists($id->{'name'})) {
522                         $text .= ',';
523                 }
524         }
525
526         if (exists($id->{'name'})) {
527                 $text .= " by $id->{'name'}:\n\n";
528         } else {
529                 $text .= ":\n\n";
530         }
531
532         return unless (exists($pos_calculating->{'board'}));
533                 
534         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
535                 # multi-PV
536                 my $mpv = 1;
537                 while (exists($info->{'pv' . $mpv})) {
538                         $text .= sprintf "  PV%2u", $mpv;
539                         my $score = short_score($info, $pos_calculating, $mpv);
540                         $text .= "  ($score)" if (defined($score));
541
542                         my $tbhits = '';
543                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
544                                 if ($info->{'tbhits' . $mpv} == 1) {
545                                         $tbhits = ", 1 tbhit";
546                                 } else {
547                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
548                                 }
549                         }
550
551                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
552                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
553                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
554                         }
555
556                         $text .= ":\n";
557                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
558                         $text .= "\n";
559                         ++$mpv;
560                 }
561         } else {
562                 # single-PV
563                 my $score = long_score($info, $pos_calculating, '');
564                 $text .= "  $score\n" if defined($score);
565                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
566                 $text .=  "\n";
567
568                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
569                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
570                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
571                 }
572                 if (exists($info->{'seldepth'})) {
573                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
574                 }
575                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
576                         if ($info->{'tbhits'} == 1) {
577                                 $text .= ", one Syzygy hit";
578                         } else {
579                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
580                         }
581                 }
582                 $text .= "\n\n";
583         }
584
585         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
586
587         my @refutation_lines = ();
588         if (defined($engine2)) {
589                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
590                         my $info = $engine2->{'info'};
591                         last if (!exists($info->{'pv' . $mpv}));
592                         eval {
593                                 my $pv = $info->{'pv' . $mpv};
594
595                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
596                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
597                                 if (scalar @pretty_pv > 5) {
598                                         @pretty_pv = @pretty_pv[0..4];
599                                         push @pretty_pv, "...";
600                                 }
601                                 my $key = $pretty_move;
602                                 my $line = sprintf("  %-6s %6s %3s  %s",
603                                         $pretty_move,
604                                         short_score($info, $pos_calculating_second_engine, $mpv, 0),
605                                         "d" . $info->{'depth' . $mpv},
606                                         join(', ', @pretty_pv));
607                                 push @refutation_lines, [ $key, $line ];
608                         };
609                 }
610         }
611
612         if ($#refutation_lines >= 0) {
613                 $text .= "Shallow search of all legal moves:\n\n";
614                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
615                         $text .= $line->[1] . "\n";
616                 }
617                 $text .= "\n\n";        
618         }       
619
620         if ($last_text ne $text) {
621                 print "\e[H\e[2J"; # clear the screen
622                 print $text;
623                 $last_text = $text;
624         }
625
626         # Now construct the tell text, if any
627         return if (!defined($telltarget));
628
629         my $tell_text = '';
630
631         if (exists($id->{'name'})) {
632                 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
633         } else {
634                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
635         }
636
637         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
638                 # multi-PV
639                 my $mpv = 1;
640                 while (exists($info->{'pv' . $mpv})) {
641                         $tell_text .= sprintf "  PV%2u", $mpv;
642                         my $score = short_score($info, $pos_calculating, $mpv);
643                         $tell_text .= "  ($score)" if (defined($score));
644
645                         if (exists($info->{'depth' . $mpv})) {
646                                 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
647                         }
648
649                         $tell_text .= ": ";
650                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
651                         $tell_text .= "\n";
652                         ++$mpv;
653                 }
654         } else {
655                 # single-PV
656                 my $score = long_score($info, $pos_calculating, '');
657                 $tell_text .= "  $score\n" if defined($score);
658                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
659                 if (exists($info->{'depth'})) {
660                         $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
661                 }
662                 $tell_text .=  "\n";
663         }
664
665         # see if a new tell is called for -- it is if the delay has expired _and_
666         # this is not simply a repetition of the last one
667         if ($last_told_text ne $tell_text) {
668                 my $now = time;
669                 for my $iv (@tell_intervals) {
670                         last if ($now - $last_move < $iv);
671                         next if ($last_tell - $last_move >= $iv);
672
673                         for my $line (split /\n/, $tell_text) {
674                                 $t->print("tell $telltarget [$target] $line");
675                         }
676
677                         $last_told_text = $text;
678                         $last_tell = $now;
679
680                         last;
681                 }
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
693         $json->{'nodes'} = $info->{'nodes'};
694         $json->{'nps'} = $info->{'nps'};
695         $json->{'depth'} = $info->{'depth'};
696         $json->{'tbhits'} = $info->{'tbhits'};
697         $json->{'seldepth'} = $info->{'seldepth'};
698
699         # single-PV only for now
700         $json->{'pv_uci'} = $info->{'pv'};
701         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$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->{'board'}, $pv->[0]));
715                                 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$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, 0),
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, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
731                 or return;
732         print $fh JSON::XS::encode_json($json);
733         close $fh;
734         rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
735 }
736
737 sub uciprint {
738         my ($engine, $msg) = @_;
739         print { $engine->{'write'} } "$msg\n";
740         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
741 }
742
743 sub short_score {
744         my ($info, $pos, $mpv, $invert) = @_;
745
746         $invert //= 0;
747         if ($pos->{'toplay'} eq 'B') {
748                 $invert = !$invert;
749         }
750
751         if (defined($info->{'score_mate' . $mpv})) {
752                 if ($invert) {
753                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
754                 } else {
755                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
756                 }
757         } else {
758                 if (exists($info->{'score_cp' . $mpv})) {
759                         my $score = $info->{'score_cp' . $mpv} * 0.01;
760                         if ($score == 0) {
761                                 return " 0.00";
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                 if ($invert) {
778                         return 99999 - $info->{'score_mate' . $mpv};
779                 } else {
780                         return -(99999 - $info->{'score_mate' . $mpv});
781                 }
782         } else {
783                 if (exists($info->{'score_cp' . $mpv})) {
784                         my $score = $info->{'score_cp' . $mpv};
785                         if ($invert) {
786                                 $score = -$score;
787                         }
788                         return $score;
789                 }
790         }
791
792         return undef;
793 }
794
795 sub long_score {
796         my ($info, $pos, $mpv) = @_;
797
798         if (defined($info->{'score_mate' . $mpv})) {
799                 my $mate = $info->{'score_mate' . $mpv};
800                 if ($pos->{'toplay'} eq 'B') {
801                         $mate = -$mate;
802                 }
803                 if ($mate > 0) {
804                         return sprintf "White mates in %u", $mate;
805                 } else {
806                         return sprintf "Black mates in %u", -$mate;
807                 }
808         } else {
809                 if (exists($info->{'score_cp' . $mpv})) {
810                         my $score = $info->{'score_cp' . $mpv} * 0.01;
811                         if ($score == 0) {
812                                 return "Score:  0.00";
813                         }
814                         if ($pos->{'toplay'} eq 'B') {
815                                 $score = -$score;
816                         }
817                         return sprintf "Score: %+5.2f", $score;
818                 }
819         }
820
821         return undef;
822 }
823
824 my %book_cache = ();
825 sub book_info {
826         my ($fen, $board, $toplay) = @_;
827
828         if (exists($book_cache{$fen})) {
829                 return $book_cache{$fen};
830         }
831
832         my $ret = `./booklook $fen`;
833         return "" if ($ret =~ /Not found/ || $ret eq '');
834
835         my @moves = ();
836
837         for my $m (split /\n/, $ret) {
838                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
839
840                 my $pmove;
841                 if ($move eq '')  {
842                         $pmove = '(current)';
843                 } else {
844                         ($pmove) = prettyprint_pv($board, $move);
845                         $pmove .= $annotation;
846                 }
847
848                 my $score;
849                 if ($toplay eq 'W') {
850                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
851                 } else {
852                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
853                 }
854                 my $n = $win + $draw + $lose;
855                 
856                 my $percent;
857                 if ($n == 0) {
858                         $percent = "     ";
859                 } else {
860                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
861                 }
862
863                 push @moves, [ $pmove, $n, $percent, $rating ];
864         }
865
866         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
867         
868         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
869         for my $m (@moves) {
870                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
871         }
872
873         return $text;
874 }
875
876 sub open_engine {
877         my ($cmdline, $tag) = @_;
878
879         return undef if (!defined($cmdline));
880
881         my ($uciread, $uciwrite);
882         my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
883
884         my $engine = {
885                 pid => $pid,
886                 read => $uciread,
887                 readbuf => '',
888                 write => $uciwrite,
889                 info => {},
890                 ids => {},
891                 tag => $tag,
892         };
893
894         uciprint($engine, "uci");
895
896         # gobble the options
897         while (<$uciread>) {
898                 /uciok/ && last;
899                 handle_uci($engine, $_);
900         }
901         
902         return $engine;
903 }
904
905 sub read_lines {
906         my $engine = shift;
907
908         # 
909         # Read until we've got a full line -- if the engine sends part of
910         # a line and then stops we're pretty much hosed, but that should
911         # never happen.
912         #
913         while ($engine->{'readbuf'} !~ /\n/) {
914                 my $tmp;
915                 my $ret = sysread $engine->{'read'}, $tmp, 4096;
916
917                 if (!defined($ret)) {
918                         next if ($!{EINTR});
919                         die "error in reading from the UCI engine: $!";
920                 } elsif ($ret == 0) {
921                         die "EOF from UCI engine";
922                 }
923
924                 $engine->{'readbuf'} .= $tmp;
925         }
926
927         # Blah.
928         my @lines = ();
929         while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
930                 my $line = $1;
931                 $line =~ tr/\r\n//d;
932                 push @lines, $line;
933         }
934         return @lines;
935 }
936
937 sub col_letter_to_num {
938         return ord(shift) - ord('a');
939 }
940
941 sub row_letter_to_num {
942         return 7 - (ord(shift) - ord('1'));
943 }
944