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