]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
2ebffc89f355eda4a33acc270c58e34907e8c592
[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 use strict;
18 use warnings;
19
20 # Configuration
21 my $server = "freechess.org";
22 my $target = "GMCarlsen";
23 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
24 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";
25 my $telltarget = undef;   # undef to be silent
26 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960);  # after each move
27 my $uci_assume_full_compliance = 0;                    # dangerous :-)
28 my $update_max_interval = 2.0;
29 my $second_engine_start_depth = 8;
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, $move_calculating_second_engine);
64 my %refutation_moves = ();
65
66 uciprint($engine, "setoption name UCI_AnalyseMode value true");
67 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
68 uciprint($engine, "setoption name NalimovUsage value Rarely");
69 uciprint($engine, "setoption name Hash value 1024");
70 # uciprint($engine, "setoption name MultiPV value 2");
71 uciprint($engine, "ucinewgame");
72
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 2");
79 uciprint($engine2, "ucinewgame");
80
81 print "Chess engine ready.\n";
82
83 # now talk to FICS
84 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
85 $t->input_log(\*FICSLOG);
86 $t->open($server);
87 $t->print("SesseBOT");
88 $t->waitfor('/Press return to enter the server/');
89 $t->cmd("");
90
91 # set some options
92 $t->cmd("set shout 0");
93 $t->cmd("set seek 0");
94 $t->cmd("set style 12");
95 $t->cmd("observe $target");
96
97 # main loop
98 print "FICS ready.\n";
99 while (1) {
100         my $rin = '';
101         my $rout;
102         vec($rin, fileno($engine->{'read'}), 1) = 1;
103         vec($rin, fileno($engine2->{'read'}), 1) = 1;
104         vec($rin, fileno($t), 1) = 1;
105
106         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
107         my $sleep = 1.0;
108
109         while (1) {
110                 my $line = $t->getline(Timeout => 0, errmode => 'return');
111                 last if (!defined($line));
112
113                 chomp $line;
114                 $line =~ tr/\r//d;
115                 if ($line =~ /^<12> /) {
116                         my $pos = style12_to_pos($line);
117                         
118                         # if this is already in the queue, ignore it
119                         next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
120
121                         # if we're already chewing on this and there's nothing else in the queue,
122                         # also ignore it
123                         next if (!defined($pos_waiting) && defined($pos_calculating) &&
124                                  $pos->{'fen'} eq $pos_calculating->{'fen'});
125
126                         # if we're already thinking on something, stop and wait for the engine
127                         # to approve
128                         if (defined($pos_calculating)) {
129                                 if (!defined($pos_waiting)) {
130                                         uciprint($engine, "stop");
131                                 }
132                                 if ($uci_assume_full_compliance) {
133                                         $pos_waiting = $pos;
134                                 } else {
135                                         uciprint($engine, "position fen " . $pos->{'fen'});
136                                         uciprint($engine, "go infinite");
137                                         $pos_calculating = $pos;
138                                 }
139                         } else {
140                                 # it's wrong just to give the FEN (the move history is useful,
141                                 # and per the UCI spec, we should really have sent "ucinewgame"),
142                                 # but it's easier
143                                 uciprint($engine, "position fen " . $pos->{'fen'});
144                                 uciprint($engine, "go infinite");
145                                 $pos_calculating = $pos;
146                         }
147
148                         %refutation_moves = calculate_refutation_moves($pos);
149                         if (defined($move_calculating_second_engine)) {
150                                 uciprint($engine2, "stop");
151                                 $move_calculating_second_engine = undef;
152                         } else {
153                                 give_new_move_to_second_engine($pos);
154                         }
155
156                         $engine->{'info'} = {};
157                         $engine2->{'info'} = {};
158                         $last_move = time;
159
160                         # 
161                         # Output a command every move to note that we're
162                         # still paying attention -- this is a good tradeoff,
163                         # since if no move has happened in the last half
164                         # hour, the analysis/relay has most likely stopped
165                         # and we should stop hogging server resources.
166                         #
167                         $t->cmd("date");
168                 }
169                 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
170                         my ($who, $msg) = ($1, $2);
171
172                         next if (grep { $_ eq $who } (@masters) == 0);
173         
174                         if ($msg =~ /^fics (.*?)$/) {
175                                 $t->cmd("tell $who Executing '$1' on FICS.");
176                                 $t->cmd($1);
177                         } elsif ($msg =~ /^uci (.*?)$/) {
178                                 $t->cmd("tell $who Sending '$1' to the engine.");
179                                 print { $engine->{'write'} } "$1\n";
180                         } else {
181                                 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
182                         }
183                 }
184                 #print "FICS: [$line]\n";
185                 $sleep = 0;
186         }
187         
188         # any fun on the UCI channel?
189         if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
190                 my @lines = read_lines($engine);
191                 for my $line (@lines) {
192                         next if $line =~ /(upper|lower)bound/;
193                         handle_uci($engine, $line, 1);
194                 }
195                 $sleep = 0;
196
197                 output();
198         }
199         if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
200                 my @lines = read_lines($engine2);
201                 for my $line (@lines) {
202                         next if $line =~ /(upper|lower)bound/;
203                         handle_uci($engine2, $line, 0);
204                 }
205                 $sleep = 0;
206
207                 output();
208         }
209
210         sleep $sleep;
211 }
212
213 sub handle_uci {
214         my ($engine, $line, $primary) = @_;
215
216         chomp $line;
217         $line =~ tr/\r//d;
218         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
219         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
220         if ($line =~ /^info/) {
221                 my (@infos) = split / /, $line;
222                 shift @infos;
223
224                 parse_infos($engine, @infos);
225         }
226         if ($line =~ /^id/) {
227                 my (@ids) = split / /, $line;
228                 shift @ids;
229
230                 parse_ids($engine, @ids);
231         }
232         if ($line =~ /^bestmove/) {
233                 if ($primary) {
234                         return if (!$uci_assume_full_compliance);
235                         if (defined($pos_waiting)) {
236                                 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
237                                 uciprint($engine, "go infinite");
238
239                                 $pos_calculating = $pos_waiting;
240                                 $pos_waiting = undef;
241                         }
242                 } else {
243                         if (defined($move_calculating_second_engine)) { 
244                                 my $move = $refutation_moves{$move_calculating_second_engine};
245                                 $move->{'pv'} = $engine->{'info'}{'pv'} // $engine->{'info'}{'pv1'};
246                                 $move->{'score_cp'} = $engine->{'info'}{'score_cp'} // $engine->{'info'}{'score_cp1'} // 0;
247                                 $move->{'score_mate'} = $engine->{'info'}{'score_mate'} // $engine->{'info'}{'score_mate1'};
248                                 $move->{'toplay'} = $pos_calculating->{'toplay'};
249                         }
250                         give_new_move_to_second_engine($pos_waiting // $pos_calculating);
251                 }
252         }
253 }
254
255 sub parse_infos {
256         my ($engine, @x) = @_;
257         my $mpv = '';
258
259         my $info = $engine->{'info'};
260
261         while (scalar @x > 0) {
262                 if ($x[0] =~ 'multipv') {
263                         shift @x;
264                         $mpv = shift @x;
265                         next;
266                 }
267                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
268                         my $key = shift @x;
269                         my $value = shift @x;
270                         $info->{$key} = $value;
271                         next;
272                 }
273                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
274                         my $key = shift @x;
275                         my $value = shift @x;
276                         $info->{$key . $mpv} = $value;
277                         next;
278                 }
279                 if ($x[0] eq 'score') {
280                         shift @x;
281
282                         delete $info->{'score_cp' . $mpv};
283                         delete $info->{'score_mate' . $mpv};
284
285                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
286                                 if ($x[0] eq 'cp') {
287                                         shift @x;
288                                         $info->{'score_cp' . $mpv} = shift @x;
289                                 } elsif ($x[0] eq 'mate') {
290                                         shift @x;
291                                         $info->{'score_mate' . $mpv} = shift @x;
292                                 } else {
293                                         shift @x;
294                                 }
295                         }
296                         next;
297                 }
298                 if ($x[0] eq 'pv') {
299                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
300                         last;
301                 }
302                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
303                         last;
304                 }
305
306                 #print "unknown info '$x[0]', trying to recover...\n";
307                 #shift @x;
308                 die "Unknown info '" . join(',', @x) . "'";
309
310         }
311 }
312
313 sub parse_ids {
314         my ($engine, @x) = @_;
315
316         while (scalar @x > 0) {
317                 if ($x[0] =~ /^(name|author)$/) {
318                         my $key = shift @x;
319                         my $value = join(' ', @x);
320                         $engine->{'id'}{$key} = $value;
321                         last;
322                 }
323
324                 # unknown
325                 shift @x;
326         }
327 }
328
329 sub style12_to_pos {
330         my $str = shift;
331         my %pos = ();
332         my (@x) = split / /, $str;
333         
334         $pos{'board'} = [ @x[1..8] ];
335         $pos{'toplay'} = $x[9];
336         $pos{'ep_file_num'} = $x[10];
337         $pos{'white_castle_k'} = $x[11];
338         $pos{'white_castle_q'} = $x[12];
339         $pos{'black_castle_k'} = $x[13];
340         $pos{'black_castle_q'} = $x[14];
341         $pos{'time_to_100move_rule'} = $x[15];
342         $pos{'move_num'} = $x[26];
343         $pos{'last_move'} = $x[29];
344         $pos{'fen'} = make_fen(\%pos);
345
346         return \%pos;
347 }
348
349 sub make_fen {
350         my $pos = shift;
351
352         # the board itself
353         my (@board) = @{$pos->{'board'}};
354         for my $rank (0..7) {
355                 $board[$rank] =~ s/(-+)/length($1)/ge;
356         }
357         my $fen = join('/', @board);
358
359         # white/black to move
360         $fen .= " ";
361         $fen .= lc($pos->{'toplay'});
362
363         # castling
364         my $castling = "";
365         $castling .= "K" if ($pos->{'white_castle_k'} == 1);
366         $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
367         $castling .= "k" if ($pos->{'black_castle_k'} == 1);
368         $castling .= "q" if ($pos->{'black_castle_q'} == 1);
369         $castling = "-" if ($castling eq "");
370         # $castling = "-"; # chess960
371         $fen .= " ";
372         $fen .= $castling;
373
374         # en passant
375         my $ep = "-";
376         if ($pos->{'ep_file_num'} != -1) {
377                 my $col = $pos->{'ep_file_num'};
378                 my $nep = (qw(a b c d e f g h))[$col];
379
380                 if ($pos->{'toplay'} eq 'B') {
381                         $nep .= "3";
382                 } else {
383                         $nep .= "6";
384                 }
385
386                 #
387                 # Showing the en passant square when actually no capture can be made
388                 # seems to confuse at least Rybka. Thus, check if there's actually
389                 # a pawn of the opposite side that can do the en passant move, and if
390                 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
391                 # "right" thing as per the standard, though.
392                 #
393                 if ($pos->{'toplay'} eq 'B') {
394                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
395                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
396                 } else {
397                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
398                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
399                 }
400         }
401         $fen .= " ";
402         $fen .= $ep;
403
404         # half-move clock
405         $fen .= " ";
406         $fen .= $pos->{'time_to_100move_rule'};
407
408         # full-move clock
409         $fen .= " ";
410         $fen .= $pos->{'move_num'};
411
412         return $fen;
413 }
414
415 sub make_move {
416         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
417         my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
418         my $piece = substr($board->[$from_row], $from_col, 1);
419         my @nb = @$board;
420
421         if ($piece eq '-') {
422                 die "Invalid move $move";
423         }
424
425         # white short castling
426         if ($move eq 'e1g1' && $piece eq 'K') {
427                 # king
428                 substr($nb[7], 4, 1, '-');
429                 substr($nb[7], 6, 1, $piece);
430                 
431                 # rook
432                 substr($nb[7], 7, 1, '-');
433                 substr($nb[7], 5, 1, 'R');
434                                 
435                 return \@nb;
436         }
437
438         # white long castling
439         if ($move eq 'e1c1' && $piece eq 'K') {
440                 # king
441                 substr($nb[7], 4, 1, '-');
442                 substr($nb[7], 2, 1, $piece);
443                 
444                 # rook
445                 substr($nb[7], 0, 1, '-');
446                 substr($nb[7], 3, 1, 'R');
447                                 
448                 return \@nb;
449         }
450
451         # black short castling
452         if ($move eq 'e8g8' && $piece eq 'k') {
453                 # king
454                 substr($nb[0], 4, 1, '-');
455                 substr($nb[0], 6, 1, $piece);
456                 
457                 # rook
458                 substr($nb[0], 7, 1, '-');
459                 substr($nb[0], 5, 1, 'r');
460                                 
461                 return \@nb;
462         }
463
464         # black long castling
465         if ($move eq 'e8c8' && $piece eq 'k') {
466                 # king
467                 substr($nb[0], 4, 1, '-');
468                 substr($nb[0], 2, 1, $piece);
469                 
470                 # rook
471                 substr($nb[0], 0, 1, '-');
472                 substr($nb[0], 3, 1, 'r');
473                                 
474                 return \@nb;
475         }
476
477         # check if the from-piece is a pawn
478         if (lc($piece) eq 'p') {
479                 # attack?
480                 if ($from_col != $to_col) {
481                         # en passant?
482                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
483                                 if ($piece eq 'p') {
484                                         substr($nb[$to_row + 1], $to_col, 1, '-');
485                                 } else {
486                                         substr($nb[$to_row - 1], $to_col, 1, '-');
487                                 }
488                         }
489                 } else {
490                         if ($promo ne '') {
491                                 if ($piece eq 'p') {
492                                         $piece = $promo;
493                                 } else {
494                                         $piece = uc($promo);
495                                 }
496                         }
497                 }
498         }
499
500         # update the board
501         substr($nb[$from_row], $from_col, 1, '-');
502         substr($nb[$to_row], $to_col, 1, $piece);
503
504         return \@nb;
505 }
506
507 sub prettyprint_pv {
508         my ($board, @pvs) = @_;
509
510         if (scalar @pvs == 0 || !defined($pvs[0])) {
511                 return ();
512         }
513
514         my $pv = shift @pvs;
515         my $from_col = col_letter_to_num(substr($pv, 0, 1));
516         my $from_row = row_letter_to_num(substr($pv, 1, 1));
517         my $to_col   = col_letter_to_num(substr($pv, 2, 1));
518         my $to_row   = row_letter_to_num(substr($pv, 3, 1));
519         my $promo    = substr($pv, 4, 1);
520
521         my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
522         my $piece = substr($board->[$from_row], $from_col, 1);
523
524         if ($piece eq '-') {
525                 die "Invalid move $pv";
526         }
527
528         # white short castling
529         if ($pv eq 'e1g1' && $piece eq 'K') {
530                 return ('0-0', prettyprint_pv($nb, @pvs));
531         }
532
533         # white long castling
534         if ($pv eq 'e1c1' && $piece eq 'K') {
535                 return ('0-0-0', prettyprint_pv($nb, @pvs));
536         }
537
538         # black short castling
539         if ($pv eq 'e8g8' && $piece eq 'k') {
540                 return ('0-0', prettyprint_pv($nb, @pvs));
541         }
542
543         # black long castling
544         if ($pv eq 'e8c8' && $piece eq 'k') {
545                 return ('0-0-0', prettyprint_pv($nb, @pvs));
546         }
547
548         my $pretty;
549
550         # check if the from-piece is a pawn
551         if (lc($piece) eq 'p') {
552                 # attack?
553                 if ($from_col != $to_col) {
554                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
555                 } else {
556                         $pretty = substr($pv, 2, 2);
557
558                         if (length($pv) == 5) {
559                                 # promotion
560                                 $pretty .= "=";
561                                 $pretty .= uc(substr($pv, 4, 1));
562
563                                 if ($piece eq 'p') {
564                                         $piece = substr($pv, 4, 1);
565                                 } else {
566                                         $piece = uc(substr($pv, 4, 1));
567                                 }
568                         }
569                 }
570         } else {
571                 $pretty = uc($piece);
572
573                 # see how many of these pieces could go here, in all
574                 my $num_total = 0;
575                 for my $col (0..7) {
576                         for my $row (0..7) {
577                                 next unless (substr($board->[$row], $col, 1) eq $piece);
578                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
579                         }
580                 }
581
582                 # see how many of these pieces from the given row could go here
583                 my $num_row = 0;
584                 for my $col (0..7) {
585                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
586                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
587                 }
588                 
589                 # and same for columns
590                 my $num_col = 0;
591                 for my $row (0..7) {
592                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
593                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
594                 }
595                 
596                 # see if we need to disambiguate
597                 if ($num_total > 1) {
598                         if ($num_col == 1) {
599                                 $pretty .= substr($pv, 0, 1);
600                         } elsif ($num_row == 1) {
601                                 $pretty .= substr($pv, 1, 1);
602                         } else {
603                                 $pretty .= substr($pv, 0, 2);
604                         }
605                 }
606
607                 # attack?
608                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
609                         $pretty .= 'x';
610                 }
611
612                 $pretty .= substr($pv, 2, 2);
613         }
614
615         if (in_mate($nb)) {
616                 $pretty .= '#';
617         } elsif (in_check($nb) ne 'none') {
618                 $pretty .= '+';
619         }
620         return ($pretty, prettyprint_pv($nb, @pvs));
621 }
622
623 sub output {
624         #return;
625
626         return if (!defined($pos_calculating));
627
628         # Don't update too often.
629         my $age = Time::HiRes::tv_interval($latest_update);
630         if ($age < $update_max_interval) {
631                 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
632                 return;
633         }
634         
635         my $info = $engine->{'info'};
636         
637         #
638         # Some programs _always_ report MultiPV, even with only one PV.
639         # In this case, we simply use that data as if MultiPV was never
640         # specified.
641         #
642         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
643                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
644                         if (exists($info->{$key . '1'})) {
645                                 $info->{$key} = $info->{$key . '1'};
646                         }
647                 }
648         }
649         
650         #
651         # Check the PVs first. if they're invalid, just wait, as our data
652         # is most likely out of sync. This isn't a very good solution, as
653         # it can frequently miss stuff, but it's good enough for most users.
654         #
655         eval {
656                 my $dummy;
657                 if (exists($info->{'pv'})) {
658                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
659                 }
660         
661                 my $mpv = 1;
662                 while (exists($info->{'pv' . $mpv})) {
663                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
664                         ++$mpv;
665                 }
666         };
667         if ($@) {
668                 $engine->{'info'} = {};
669                 return;
670         }
671
672         output_screen();
673         output_json();
674         $latest_update = [Time::HiRes::gettimeofday];
675 }
676
677 sub output_screen {
678         my $info = $engine->{'info'};
679         my $id = $engine->{'id'};
680
681         my $text = 'Analysis';
682         if ($pos_calculating->{'last_move'} ne 'none') {
683                 if ($pos_calculating->{'toplay'} eq 'W') {
684                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
685                 } else {
686                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
687                 }
688                 if (exists($id->{'name'})) {
689                         $text .= ',';
690                 }
691         }
692
693         if (exists($id->{'name'})) {
694                 $text .= " by $id->{'name'}:\n\n";
695         } else {
696                 $text .= ":\n\n";
697         }
698
699         return unless (exists($pos_calculating->{'board'}));
700                 
701         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
702                 # multi-PV
703                 my $mpv = 1;
704                 while (exists($info->{'pv' . $mpv})) {
705                         $text .= sprintf "  PV%2u", $mpv;
706                         my $score = short_score($info, $pos_calculating, $mpv);
707                         $text .= "  ($score)" if (defined($score));
708
709                         my $tbhits = '';
710                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
711                                 if ($info->{'tbhits' . $mpv} == 1) {
712                                         $tbhits = ", 1 tbhit";
713                                 } else {
714                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
715                                 }
716                         }
717
718                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
719                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
720                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
721                         }
722
723                         $text .= ":\n";
724                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
725                         $text .= "\n";
726                         ++$mpv;
727                 }
728         } else {
729                 # single-PV
730                 my $score = long_score($info, $pos_calculating, '');
731                 $text .= "  $score\n" if defined($score);
732                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
733                 $text .=  "\n";
734
735                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
736                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
737                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
738                 }
739                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
740                         if ($info->{'tbhits'} == 1) {
741                                 $text .= ", one Nalimov hit";
742                         } else {
743                                 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
744                         }
745                 }
746                 if (exists($info->{'seldepth'})) {
747                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
748                 }
749                 $text .= "\n\n";
750         }
751
752         #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
753
754         my @refutation_lines = ();
755         for my $move (keys %refutation_moves) {
756                 eval {
757                         my $m = $refutation_moves{$move};
758                         die if ($m->{'depth'} < $second_engine_start_depth);
759                         my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
760                         my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
761                         if (scalar @pretty_pv > 5) {
762                                 @pretty_pv = @pretty_pv[0..4];
763                                 push @pretty_pv, "...";
764                         }
765                         #my $key = score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1);
766                         my $key = $pretty_move;
767                         my $line = sprintf("  %-6s %6s %3s  %s",
768                                 $pretty_move,
769                                 short_score($refutation_moves{$move}, $pos_calculating, '', 1),
770                                 "d" . $m->{'depth'},
771                                 join(', ', @pretty_pv));
772                         push @refutation_lines, [ $key, $line ];
773                 };
774         }
775
776         if ($#refutation_lines >= 0) {
777                 $text .= "Shallow search of all legal moves:\n\n";
778                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
779                         $text .= $line->[1] . "\n";
780                 }
781                 $text .= "\n\n";        
782         }       
783
784         if ($last_text ne $text) {
785                 print "\e[H\e[2J"; # clear the screen
786                 print $text;
787                 $last_text = $text;
788         }
789
790         # Now construct the tell text, if any
791         return if (!defined($telltarget));
792
793         my $tell_text = '';
794
795         if (exists($id->{'name'})) {
796                 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
797         } else {
798                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
799         }
800
801         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
802                 # multi-PV
803                 my $mpv = 1;
804                 while (exists($info->{'pv' . $mpv})) {
805                         $tell_text .= sprintf "  PV%2u", $mpv;
806                         my $score = short_score($info, $pos_calculating, $mpv);
807                         $tell_text .= "  ($score)" if (defined($score));
808
809                         if (exists($info->{'depth' . $mpv})) {
810                                 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
811                         }
812
813                         $tell_text .= ": ";
814                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
815                         $tell_text .= "\n";
816                         ++$mpv;
817                 }
818         } else {
819                 # single-PV
820                 my $score = long_score($info, $pos_calculating, '');
821                 $tell_text .= "  $score\n" if defined($score);
822                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
823                 if (exists($info->{'depth'})) {
824                         $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
825                 }
826                 $tell_text .=  "\n";
827         }
828
829         # see if a new tell is called for -- it is if the delay has expired _and_
830         # this is not simply a repetition of the last one
831         if ($last_told_text ne $tell_text) {
832                 my $now = time;
833                 for my $iv (@tell_intervals) {
834                         last if ($now - $last_move < $iv);
835                         next if ($last_tell - $last_move >= $iv);
836
837                         for my $line (split /\n/, $tell_text) {
838                                 $t->print("tell $telltarget [$target] $line");
839                         }
840
841                         $last_told_text = $text;
842                         $last_tell = $now;
843
844                         last;
845                 }
846         }
847 }
848
849 sub output_json {
850         my $info = $engine->{'info'};
851
852         my $json = {};
853         $json->{'position'} = $pos_calculating;
854         $json->{'id'} = $engine->{'id'};
855         $json->{'score'} = long_score($info, $pos_calculating, '');
856
857         $json->{'nodes'} = $info->{'nodes'};
858         $json->{'nps'} = $info->{'nps'};
859         $json->{'depth'} = $info->{'depth'};
860         $json->{'tbhits'} = $info->{'tbhits'};
861         $json->{'seldepth'} = $info->{'seldepth'};
862
863         # single-PV only for now
864         $json->{'pv_uci'} = $info->{'pv'};
865         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
866
867         my %refutation_lines = ();
868         for my $move (keys %refutation_moves) {
869                 my $m = $refutation_moves{$move};
870                 my $pretty_move = "";
871                 my @pretty_pv = ();
872                 eval {
873                         $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
874                         @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
875                 };
876                 $refutation_lines{$move} = {
877                         sort_key => $pretty_move,
878                         depth => $m->{'depth'},
879                         score_sort_key => score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1),
880                         pretty_score => short_score($refutation_moves{$move}, $pos_calculating, '', 1),
881                         pretty_move => $pretty_move,
882                         pv_pretty => \@pretty_pv,
883                 };
884                 eval {
885                         $refutation_lines{$move}->{'pv_uci'} = [ $move, @{$m->{'pv'}} ];
886                 };
887         }
888         $json->{'refutation_lines'} = \%refutation_lines;
889
890         open my $fh, ">analysis.json.tmp"
891                 or return;
892         print $fh JSON::XS::encode_json($json);
893         close $fh;
894         rename("analysis.json.tmp", "analysis.json");   
895 }
896
897 sub find_kings {
898         my $board = shift;
899         my ($wkr, $wkc, $bkr, $bkc);
900
901         for my $row (0..7) {
902                 for my $col (0..7) {
903                         my $piece = substr($board->[$row], $col, 1);
904                         if ($piece eq 'K') {
905                                 ($wkr, $wkc) = ($row, $col);
906                         } elsif ($piece eq 'k') {
907                                 ($bkr, $bkc) = ($row, $col);
908                         }
909                 }
910         }
911
912         return ($wkr, $wkc, $bkr, $bkc);
913 }
914
915 sub in_mate {
916         my $board = shift;
917         my $check = in_check($board);
918         return 0 if ($check eq 'none');
919
920         # try all possible moves for the side in check
921         for my $row (0..7) {
922                 for my $col (0..7) {
923                         my $piece = substr($board->[$row], $col, 1);
924                         next if ($piece eq '-');
925
926                         if ($check eq 'white') {
927                                 next if ($piece eq lc($piece));
928                         } else {
929                                 next if ($piece eq uc($piece));
930                         }
931
932                         for my $dest_row (0..7) {
933                                 for my $dest_col (0..7) {
934                                         next if ($row == $dest_row && $col == $dest_col);
935                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
936
937                                         my @nb = @$board;
938                                         substr($nb[$row], $col, 1, '-');
939                                         substr($nb[$dest_row], $dest_col, 1, $piece);
940
941                                         my $new_check = in_check(\@nb);
942                                         return 0 if ($new_check ne $check && $new_check ne 'both');
943                                 }
944                         }
945                 }
946         }
947
948         # nothing to do; mate
949         return 1;
950 }
951
952 sub in_check {
953         my $board = shift;
954         my ($black_check, $white_check) = (0, 0);
955
956         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
957
958         # check all pieces for the possibility of threatening the two kings
959         for my $row (0..7) {
960                 for my $col (0..7) {
961                         my $piece = substr($board->[$row], $col, 1);
962                         next if ($piece eq '-');
963                 
964                         if (uc($piece) eq $piece) {
965                                 # white piece
966                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
967                         } else {
968                                 # black piece
969                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
970                         }
971                 }
972         }
973
974         if ($black_check && $white_check) {
975                 return 'both';
976         } elsif ($black_check) {
977                 return 'black';
978         } elsif ($white_check) {
979                 return 'white';
980         } else {
981                 return 'none';
982         }
983 }
984
985 sub can_reach {
986         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
987         
988         # can't eat your own piece
989         my $dest_piece = substr($board->[$to_row], $to_col, 1);
990         if ($dest_piece ne '-') {
991                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
992         }
993
994         if (lc($piece) eq 'k') {
995                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
996         }
997         if (lc($piece) eq 'r') {
998                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
999
1000                 # check that there's a clear passage
1001                 if ($from_row == $to_row) {
1002                         if ($from_col > $to_col) {
1003                                 ($to_col, $from_col) = ($from_col, $to_col);
1004                         }
1005
1006                         for my $c (($from_col+1)..($to_col-1)) {
1007                                 my $middle_piece = substr($board->[$to_row], $c, 1);
1008                                 return 0 if ($middle_piece ne '-');     
1009                         }
1010
1011                         return 1;
1012                 } else {
1013                         if ($from_row > $to_row) {
1014                                 ($to_row, $from_row) = ($from_row, $to_row);
1015                         }
1016
1017                         for my $r (($from_row+1)..($to_row-1)) {
1018                                 my $middle_piece = substr($board->[$r], $to_col, 1);
1019                                 return 0 if ($middle_piece ne '-');     
1020                         }
1021
1022                         return 1;
1023                 }
1024         }
1025         if (lc($piece) eq 'b') {
1026                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1027
1028                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1029                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1030
1031                 my $r = $from_row + $dr;
1032                 my $c = $from_col + $dc;
1033
1034                 while ($r != $to_row) {
1035                         my $middle_piece = substr($board->[$r], $c, 1);
1036                         return 0 if ($middle_piece ne '-');
1037                         
1038                         $r += $dr;
1039                         $c += $dc;
1040                 }
1041
1042                 return 1;
1043         }
1044         if (lc($piece) eq 'n') {
1045                 my $diff_r = abs($from_row - $to_row);
1046                 my $diff_c = abs($from_col - $to_col);
1047                 return 1 if ($diff_r == 2 && $diff_c == 1);
1048                 return 1 if ($diff_r == 1 && $diff_c == 2);
1049                 return 0;
1050         }
1051         if ($piece eq 'q') {
1052                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
1053                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
1054         }
1055         if ($piece eq 'Q') {
1056                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1057                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1058         }
1059
1060         # TODO: en passant
1061         if ($piece eq 'p') {
1062                 # black pawn
1063                 if ($to_col == $from_col && $to_row == $from_row + 1) {
1064                         return ($dest_piece eq '-');
1065                 }
1066                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1067                         my $middle_piece = substr($board->[2], $to_col, 1);
1068                         return ($dest_piece eq '-' && $middle_piece eq '-');
1069                 }
1070                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1071                         return ($dest_piece ne '-');
1072                 }
1073                 return 0;
1074         }
1075         if ($piece eq 'P') {
1076                 # white pawn
1077                 if ($to_col == $from_col && $to_row == $from_row - 1) {
1078                         return ($dest_piece eq '-');
1079                 }
1080                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1081                         my $middle_piece = substr($board->[5], $to_col, 1);
1082                         return ($dest_piece eq '-' && $middle_piece eq '-');
1083                 }
1084                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1085                         return ($dest_piece ne '-');
1086                 }
1087                 return 0;
1088         }
1089         
1090         # unknown piece
1091         return 0;
1092 }
1093
1094 sub uciprint {
1095         my ($engine, $msg) = @_;
1096         print { $engine->{'write'} } "$msg\n";
1097         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1098 }
1099
1100 sub short_score {
1101         my ($info, $pos, $mpv, $invert) = @_;
1102
1103         $invert //= 0;
1104         if ($pos->{'toplay'} eq 'B') {
1105                 $invert = !$invert;
1106         }
1107
1108         if (defined($info->{'score_mate' . $mpv})) {
1109                 if ($invert) {
1110                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1111                 } else {
1112                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
1113                 }
1114         } else {
1115                 if (exists($info->{'score_cp' . $mpv})) {
1116                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1117                         if ($score == 0) {
1118                                 return " 0.00";
1119                         }
1120                         if ($invert) {
1121                                 $score = -$score;
1122                         }
1123                         return sprintf "%+5.2f", $score;
1124                 }
1125         }
1126
1127         return undef;
1128 }
1129
1130 sub score_sort_key {
1131         my ($info, $pos, $mpv, $invert) = @_;
1132
1133         $invert //= 0;
1134         if ($pos->{'toplay'} eq 'B') {
1135                 $invert = !$invert;
1136         }
1137
1138         if (defined($info->{'score_mate' . $mpv})) {
1139                 if ($invert) {
1140                         return -(99999 - $info->{'score_mate' . $mpv});
1141                 } else {
1142                         return 99999 - $info->{'score_mate' . $mpv};
1143                 }
1144         } else {
1145                 if (exists($info->{'score_cp' . $mpv})) {
1146                         my $score = $info->{'score_cp' . $mpv};
1147                         if ($score == 0) {
1148                                 return " 0.00";
1149                         }
1150                         if ($invert) {
1151                                 $score = -$score;
1152                         }
1153                         return $score;
1154                 }
1155         }
1156
1157         return undef;
1158 }
1159
1160 sub long_score {
1161         my ($info, $pos, $mpv) = @_;
1162
1163         if (defined($info->{'score_mate' . $mpv})) {
1164                 my $mate = $info->{'score_mate' . $mpv};
1165                 if ($pos->{'toplay'} eq 'B') {
1166                         $mate = -$mate;
1167                 }
1168                 if ($mate > 0) {
1169                         return sprintf "White mates in %u", $mate;
1170                 } else {
1171                         return sprintf "Black mates in %u", -$mate;
1172                 }
1173         } else {
1174                 if (exists($info->{'score_cp' . $mpv})) {
1175                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1176                         if ($pos->{'toplay'} eq 'B') {
1177                                 $score = -$score;
1178                         }
1179                         return sprintf "Score: %+5.2f", $score;
1180                 }
1181         }
1182
1183         return undef;
1184 }
1185
1186 my %book_cache = ();
1187 sub book_info {
1188         my ($fen, $board, $toplay) = @_;
1189
1190         if (exists($book_cache{$fen})) {
1191                 return $book_cache{$fen};
1192         }
1193
1194         my $ret = `./booklook $fen`;
1195         return "" if ($ret =~ /Not found/ || $ret eq '');
1196
1197         my @moves = ();
1198
1199         for my $m (split /\n/, $ret) {
1200                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1201
1202                 my $pmove;
1203                 if ($move eq '')  {
1204                         $pmove = '(current)';
1205                 } else {
1206                         ($pmove) = prettyprint_pv($board, $move);
1207                         $pmove .= $annotation;
1208                 }
1209
1210                 my $score;
1211                 if ($toplay eq 'W') {
1212                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1213                 } else {
1214                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1215                 }
1216                 my $n = $win + $draw + $lose;
1217                 
1218                 my $percent;
1219                 if ($n == 0) {
1220                         $percent = "     ";
1221                 } else {
1222                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1223                 }
1224
1225                 push @moves, [ $pmove, $n, $percent, $rating ];
1226         }
1227
1228         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1229         
1230         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1231         for my $m (@moves) {
1232                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1233         }
1234
1235         return $text;
1236 }
1237
1238 sub open_engine {
1239         my ($cmdline, $tag) = @_;
1240         my ($uciread, $uciwrite);
1241         my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1242
1243         my $engine = {
1244                 pid => $pid,
1245                 read => $uciread,
1246                 readbuf => '',
1247                 write => $uciwrite,
1248                 info => {},
1249                 ids => {},
1250                 tag => $tag,
1251         };
1252
1253         uciprint($engine, "uci");
1254
1255         # gobble the options
1256         while (<$uciread>) {
1257                 /uciok/ && last;
1258                 handle_uci($engine, $_);
1259         }
1260         
1261         return $engine;
1262 }
1263
1264 sub read_lines {
1265         my $engine = shift;
1266
1267         # 
1268         # Read until we've got a full line -- if the engine sends part of
1269         # a line and then stops we're pretty much hosed, but that should
1270         # never happen.
1271         #
1272         while ($engine->{'readbuf'} !~ /\n/) {
1273                 my $tmp;
1274                 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1275
1276                 if (!defined($ret)) {
1277                         next if ($!{EINTR});
1278                         die "error in reading from the UCI engine: $!";
1279                 } elsif ($ret == 0) {
1280                         die "EOF from UCI engine";
1281                 }
1282
1283                 $engine->{'readbuf'} .= $tmp;
1284         }
1285
1286         # Blah.
1287         my @lines = ();
1288         while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1289                 my $line = $1;
1290                 $line =~ tr/\r\n//d;
1291                 push @lines, $line;
1292         }
1293         return @lines;
1294 }
1295
1296 # Find all possible legal moves.
1297 sub calculate_refutation_moves {
1298         my $pos = shift;
1299         my $board = $pos->{'board'};
1300         my %refutation_moves = ();
1301         for my $col (0..7) {
1302                 for my $row (0..7) {
1303                         my $piece = substr($board->[$row], $col, 1);
1304
1305                         # Check that there's a piece of the right color on this square.
1306                         next if ($piece eq '-');
1307                         if ($pos->{'toplay'} eq 'W') {
1308                                 next if ($piece ne uc($piece));
1309                         } else {
1310                                 next if ($piece ne lc($piece));
1311                         }
1312
1313                         for my $to_col (0..7) {
1314                                 for my $to_row (0..7) {
1315                                         next if ($col == $to_col && $row == $to_row);
1316                                         next unless (can_reach($board, $piece, $row, $col, $to_row, $to_col));
1317
1318                                         my $promo = "";  # FIXME
1319                                         my $nb = make_move($board, $row, $col, $to_row, $to_col, $promo);
1320                                         my $check = in_check($nb);
1321                                         next if ($check eq 'both');
1322                                         if ($pos->{'toplay'} eq 'W') {
1323                                                 next if ($check eq 'white');
1324                                         } else {
1325                                                 next if ($check eq 'black');
1326                                         }
1327                                         my $move = move_to_uci_notation($row, $col, $to_row, $to_col, $promo);
1328                                         $refutation_moves{$move} = { depth => $second_engine_start_depth - 1, score_cp => 0, pv => '' };
1329                                 }
1330                         }
1331                 }
1332         }
1333         return %refutation_moves;
1334 }
1335
1336 sub give_new_move_to_second_engine {
1337         my $pos = shift;
1338                                 
1339         # Find the move that's been analyzed the shortest but is most promising.
1340         # Tie-break on UCI move representation.
1341         my $best_move = undef;
1342         for my $move (sort keys %refutation_moves) {
1343                 if (!defined($best_move)) {
1344                         $best_move = $move;
1345                         next;
1346                 }
1347                 my $best = $refutation_moves{$best_move};
1348                 my $this = $refutation_moves{$move};
1349
1350                 if ($this->{'depth'} < $best->{'depth'} ||
1351                     ($this->{'depth'} == $best->{'depth'} && $this->{'score_cp'} < $best->{'score_cp'})) {
1352                         $best_move = $move;
1353                         next;
1354                 }
1355         }
1356
1357         my $m = $refutation_moves{$best_move};
1358         ++$m->{'depth'};
1359         uciprint($engine2, "position fen " . $pos->{'fen'} . " moves " . $best_move);
1360         uciprint($engine2, "go depth " . $m->{'depth'});
1361         $move_calculating_second_engine = $best_move;
1362 }
1363
1364 sub col_letter_to_num {
1365         return ord(shift) - ord('a');
1366 }
1367
1368 sub row_letter_to_num {
1369         return 7 - (ord(shift) - ord('1'));
1370 }
1371
1372 sub move_to_uci_notation {
1373         my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1374         $promo //= "";
1375         return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);
1376 }