Fix a crash in remoteglot.pl with the new SQL stuff.
[remoteglot] / remoteglot.pl
1 #! /usr/bin/perl
2
3 #
4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 #              analysis, or for live analysis of relayed games. (Do not use for
6 #              cheating! Cheating is bad for your karma, and your abuser flag.)
7 #
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
10 #
11
12 use AnyEvent;
13 use AnyEvent::Handle;
14 use AnyEvent::HTTP;
15 use Chess::PGN::Parse;
16 use EV;
17 use Net::Telnet;
18 use FileHandle;
19 use IPC::Open2;
20 use Time::HiRes;
21 use JSON::XS;
22 use URI::Escape;
23 use Tie::Persistent;
24 use DBI;
25 use DBD::Pg;
26 require 'Position.pm';
27 require 'Engine.pm';
28 require 'config.pm';
29 use strict;
30 use warnings;
31 no warnings qw(once);
32
33 # Program starts here
34 my $latest_update = undef;
35 my $output_timer = undef;
36 my $http_timer = undef;
37 my $stop_pgn_fetch = 0;
38 my $tb_retry_timer = undef;
39 my %tb_cache = ();
40 my $tb_lookup_running = 0;
41 my $last_written_json = undef;
42
43 # Persisted so we can restart.
44 # TODO: Figure out an appropriate way to deal with database restarts
45 # and/or Postgres going away entirely.
46 my $dbh = DBI->connect($remoteglotconf::dbistr, $remoteglotconf::dbiuser, $remoteglotconf::dbipass)
47         or die DBI->errstr;
48 $dbh->{RaiseError} = 1;
49
50 $| = 1;
51
52 open(FICSLOG, ">ficslog.txt")
53         or die "ficslog.txt: $!";
54 print FICSLOG "Log starting.\n";
55 select(FICSLOG);
56 $| = 1;
57
58 open(UCILOG, ">ucilog.txt")
59         or die "ucilog.txt: $!";
60 print UCILOG "Log starting.\n";
61 select(UCILOG);
62 $| = 1;
63
64 open(TBLOG, ">tblog.txt")
65         or die "tblog.txt: $!";
66 print TBLOG "Log starting.\n";
67 select(TBLOG);
68 $| = 1;
69
70 select(STDOUT);
71
72 # open the chess engine
73 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
74 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
75 my $last_move;
76 my $last_text = '';
77 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
78
79 uciprint($engine, "setoption name UCI_AnalyseMode value true");
80 while (my ($key, $value) = each %remoteglotconf::engine_config) {
81         uciprint($engine, "setoption name $key value $value");
82 }
83 uciprint($engine, "ucinewgame");
84
85 if (defined($engine2)) {
86         uciprint($engine2, "setoption name UCI_AnalyseMode value true");
87         while (my ($key, $value) = each %remoteglotconf::engine2_config) {
88                 uciprint($engine2, "setoption name $key value $value");
89         }
90         uciprint($engine2, "setoption name MultiPV value 500");
91         uciprint($engine2, "ucinewgame");
92 }
93
94 print "Chess engine ready.\n";
95
96 # now talk to FICS
97 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
98 $t->input_log(\*FICSLOG);
99 $t->open($remoteglotconf::server);
100 $t->print($remoteglotconf::nick);
101 $t->waitfor('/Press return to enter the server/');
102 $t->cmd("");
103
104 # set some options
105 $t->cmd("set shout 0");
106 $t->cmd("set seek 0");
107 $t->cmd("set style 12");
108
109 my $ev1 = AnyEvent->io(
110         fh => fileno($t),
111         poll => 'r',
112         cb => sub {    # what callback to execute
113                 while (1) {
114                         my $line = $t->getline(Timeout => 0, errmode => 'return');
115                         return if (!defined($line));
116
117                         chomp $line;
118                         $line =~ tr/\r//d;
119                         handle_fics($line);
120                 }
121         }
122 );
123 if (defined($remoteglotconf::target)) {
124         if ($remoteglotconf::target =~ /^http:/) {
125                 fetch_pgn($remoteglotconf::target);
126         } else {
127                 $t->cmd("observe $remoteglotconf::target");
128         }
129 }
130 print "FICS ready.\n";
131
132 # Engine events have already been set up by Engine.pm.
133 EV::run;
134
135 sub handle_uci {
136         my ($engine, $line, $primary) = @_;
137
138         return if $line =~ /(upper|lower)bound/;
139
140         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
141         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
142         if ($line =~ /^info/) {
143                 my (@infos) = split / /, $line;
144                 shift @infos;
145
146                 parse_infos($engine, @infos);
147         }
148         if ($line =~ /^id/) {
149                 my (@ids) = split / /, $line;
150                 shift @ids;
151
152                 parse_ids($engine, @ids);
153         }
154         if ($line =~ /^bestmove/) {
155                 if ($primary) {
156                         return if (!$remoteglotconf::uci_assume_full_compliance);
157                         if (defined($pos_waiting)) {
158                                 uciprint($engine, "position fen " . $pos_waiting->fen());
159                                 uciprint($engine, "go infinite");
160
161                                 $pos_calculating = $pos_waiting;
162                                 $pos_waiting = undef;
163                         }
164                 } else {
165                         $engine2->{'info'} = {};
166                         my $pos = $pos_waiting // $pos_calculating;
167                         uciprint($engine2, "position fen " . $pos->fen());
168                         uciprint($engine2, "go infinite");
169                         $pos_calculating_second_engine = $pos;
170                 }
171         }
172         output();
173 }
174
175 my $getting_movelist = 0;
176 my $pos_for_movelist = undef;
177 my @uci_movelist = ();
178 my @pretty_movelist = ();
179
180 sub handle_fics {
181         my $line = shift;
182         if ($line =~ /^<12> /) {
183                 handle_position(Position->new($line));
184                 $t->cmd("moves");
185         }
186         if ($line =~ /^Movelist for game /) {
187                 my $pos = $pos_waiting // $pos_calculating;
188                 if (defined($pos)) {
189                         @uci_movelist = ();
190                         @pretty_movelist = ();
191                         $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
192                         $getting_movelist = 1;
193                 }
194         }
195         if ($getting_movelist &&
196             $line =~ /^\s* \d+\. \s+                     # move number
197                        (\S+) \s+ \( [\d:.]+ \) \s*       # first move, then time
198                        (?: (\S+) \s+ \( [\d:.]+ \) )?    # second move, then time 
199                      /x) {
200                 eval {
201                         my $uci_move;
202                         ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
203                         push @uci_movelist, $uci_move;
204                         push @pretty_movelist, $1;
205
206                         if (defined($2)) {
207                                 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
208                                 push @uci_movelist, $uci_move;
209                                 push @pretty_movelist, $2;
210                         }
211                 };
212                 if ($@) {
213                         warn "Error when getting FICS move history: $@";
214                         $getting_movelist = 0;
215                 }
216         }
217         if ($getting_movelist &&
218             $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
219                 # End of movelist.
220                 for my $pos ($pos_waiting, $pos_calculating) {
221                         next if (!defined($pos));
222                         if ($pos->fen() eq $pos_for_movelist->fen()) {
223                                 $pos->{'pretty_history'} = \@pretty_movelist;
224                         }
225                 }
226                 $getting_movelist = 0;
227         }
228         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
229                 my ($who, $msg) = ($1, $2);
230
231                 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
232
233                 if ($msg =~ /^fics (.*?)$/) {
234                         $t->cmd("tell $who Executing '$1' on FICS.");
235                         $t->cmd($1);
236                 } elsif ($msg =~ /^uci (.*?)$/) {
237                         $t->cmd("tell $who Sending '$1' to the engine.");
238                         print { $engine->{'write'} } "$1\n";
239                 } elsif ($msg =~ /^pgn (.*?)$/) {
240                         my $url = $1;
241                         $t->cmd("tell $who Starting to poll '$url'.");
242                         fetch_pgn($url);
243                 } elsif ($msg =~ /^stoppgn$/) {
244                         $t->cmd("tell $who Stopping poll.");
245                         $stop_pgn_fetch = 1;
246                         $http_timer = undef;
247                 } elsif ($msg =~ /^quit$/) {
248                         $t->cmd("tell $who Bye bye.");
249                         exit;
250                 } else {
251                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
252                 }
253         }
254         #print "FICS: [$line]\n";
255 }
256
257 # Starts periodic fetching of PGNs from the given URL.
258 sub fetch_pgn {
259         my ($url) = @_;
260         AnyEvent::HTTP::http_get($url, sub {
261                 handle_pgn(@_, $url);
262         });
263 }
264
265 my ($last_pgn_white, $last_pgn_black);
266 my @last_pgn_uci_moves = ();
267 my $pgn_hysteresis_counter = 0;
268
269 sub handle_pgn {
270         my ($body, $header, $url) = @_;
271
272         if ($stop_pgn_fetch) {
273                 $stop_pgn_fetch = 0;
274                 $http_timer = undef;
275                 return;
276         }
277
278         my $pgn = Chess::PGN::Parse->new(undef, $body);
279         if (!defined($pgn) || !$pgn->read_game() || $body !~ /^\[/) {
280                 warn "Error in parsing PGN from $url\n";
281         } else {
282                 eval {
283                         # Skip to the right game.
284                         while (defined($remoteglotconf::pgn_filter) &&
285                                !&$remoteglotconf::pgn_filter($pgn)) {
286                                 $pgn->read_game() or die "Out of games during filtering";
287                         }
288
289                         $pgn->parse_game({ save_comments => 'yes' });
290                         my $pos = Position->start_pos($pgn->white, $pgn->black);
291                         my $moves = $pgn->moves;
292                         my @uci_moves = ();
293                         for my $move (@$moves) {
294                                 my $uci_move;
295                                 ($pos, $uci_move) = $pos->make_pretty_move($move);
296                                 push @uci_moves, $uci_move;
297                         }
298                         $pos->{'result'} = $pgn->result;
299                         $pos->{'pretty_history'} = $moves;
300
301                         extract_clock($pgn, $pos);
302
303                         # Sometimes, PGNs lose a move or two for a short while,
304                         # or people push out new ones non-atomically. 
305                         # Thus, if we PGN doesn't change names but becomes
306                         # shorter, we mistrust it for a few seconds.
307                         my $trust_pgn = 1;
308                         if (defined($last_pgn_white) && defined($last_pgn_black) &&
309                             $last_pgn_white eq $pgn->white &&
310                             $last_pgn_black eq $pgn->black &&
311                             scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
312                                 if (++$pgn_hysteresis_counter < 3) {
313                                         $trust_pgn = 0; 
314                                 }
315                         }
316                         if ($trust_pgn) {
317                                 $last_pgn_white = $pgn->white;
318                                 $last_pgn_black = $pgn->black;
319                                 @last_pgn_uci_moves = @uci_moves;
320                                 $pgn_hysteresis_counter = 0;
321                                 handle_position($pos);
322                         }
323                 };
324                 if ($@) {
325                         warn "Error in parsing moves from $url: $@\n";
326                 }
327         }
328         
329         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
330                 fetch_pgn($url);
331         });
332 }
333
334 sub handle_position {
335         my ($pos) = @_;
336         find_clock_start($pos, $pos_calculating);
337                 
338         # if this is already in the queue, ignore it (just update the result)
339         if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
340                 $pos_waiting->{'result'} = $pos->{'result'};
341                 return;
342         }
343
344         # if we're already chewing on this and there's nothing else in the queue,
345         # also ignore it
346         if (!defined($pos_waiting) && defined($pos_calculating) &&
347             $pos->fen() eq $pos_calculating->fen()) {
348                 $pos_calculating->{'result'} = $pos->{'result'};
349                 return;
350         }
351
352         # if we're already thinking on something, stop and wait for the engine
353         # to approve
354         if (defined($pos_calculating)) {
355                 # Store the final data we have for this position in the history,
356                 # with the precise clock information we just got from the new
357                 # position. (Historic positions store the clock at the end of
358                 # the position.)
359                 #
360                 # Do not output anything new to the main analysis; that's
361                 # going to be obsolete really soon.
362                 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
363                 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
364                 delete $pos_calculating->{'white_clock_target'};
365                 delete $pos_calculating->{'black_clock_target'};
366                 output_json(1);
367
368                 if (!defined($pos_waiting)) {
369                         uciprint($engine, "stop");
370                 }
371                 if ($remoteglotconf::uci_assume_full_compliance) {
372                         $pos_waiting = $pos;
373                 } else {
374                         uciprint($engine, "position fen " . $pos->fen());
375                         uciprint($engine, "go infinite");
376                         $pos_calculating = $pos;
377                 }
378         } else {
379                 # it's wrong just to give the FEN (the move history is useful,
380                 # and per the UCI spec, we should really have sent "ucinewgame"),
381                 # but it's easier
382                 uciprint($engine, "position fen " . $pos->fen());
383                 uciprint($engine, "go infinite");
384                 $pos_calculating = $pos;
385         }
386
387         if (defined($engine2)) {
388                 if (defined($pos_calculating_second_engine)) {
389                         uciprint($engine2, "stop");
390                 } else {
391                         uciprint($engine2, "position fen " . $pos->fen());
392                         uciprint($engine2, "go infinite");
393                         $pos_calculating_second_engine = $pos;
394                 }
395                 $engine2->{'info'} = {};
396         }
397
398         $engine->{'info'} = {};
399         $last_move = time;
400
401         schedule_tb_lookup();
402
403         # 
404         # Output a command every move to note that we're
405         # still paying attention -- this is a good tradeoff,
406         # since if no move has happened in the last half
407         # hour, the analysis/relay has most likely stopped
408         # and we should stop hogging server resources.
409         #
410         $t->cmd("date");
411 }
412
413 sub parse_infos {
414         my ($engine, @x) = @_;
415         my $mpv = '';
416
417         my $info = $engine->{'info'};
418
419         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
420         for my $i (0..$#x - 1) {
421                 if ($x[$i] eq 'multipv') {
422                         $mpv = $x[$i + 1];
423                         next;
424                 }
425         }
426
427         while (scalar @x > 0) {
428                 if ($x[0] eq 'multipv') {
429                         # Dealt with above
430                         shift @x;
431                         shift @x;
432                         next;
433                 }
434                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
435                         my $key = shift @x;
436                         my $value = shift @x;
437                         $info->{$key} = $value;
438                         next;
439                 }
440                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
441                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
442                     $x[0] eq 'tbhits') {
443                         my $key = shift @x;
444                         my $value = shift @x;
445                         $info->{$key . $mpv} = $value;
446                         next;
447                 }
448                 if ($x[0] eq 'score') {
449                         shift @x;
450
451                         delete $info->{'score_cp' . $mpv};
452                         delete $info->{'score_mate' . $mpv};
453
454                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
455                                 if ($x[0] eq 'cp') {
456                                         shift @x;
457                                         $info->{'score_cp' . $mpv} = shift @x;
458                                 } elsif ($x[0] eq 'mate') {
459                                         shift @x;
460                                         $info->{'score_mate' . $mpv} = shift @x;
461                                 } else {
462                                         shift @x;
463                                 }
464                         }
465                         next;
466                 }
467                 if ($x[0] eq 'pv') {
468                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
469                         last;
470                 }
471                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
472                         last;
473                 }
474
475                 #print "unknown info '$x[0]', trying to recover...\n";
476                 #shift @x;
477                 die "Unknown info '" . join(',', @x) . "'";
478
479         }
480 }
481
482 sub parse_ids {
483         my ($engine, @x) = @_;
484
485         while (scalar @x > 0) {
486                 if ($x[0] =~ /^(name|author)$/) {
487                         my $key = shift @x;
488                         my $value = join(' ', @x);
489                         $engine->{'id'}{$key} = $value;
490                         last;
491                 }
492
493                 # unknown
494                 shift @x;
495         }
496 }
497
498 sub prettyprint_pv_no_cache {
499         my ($board, @pvs) = @_;
500
501         if (scalar @pvs == 0 || !defined($pvs[0])) {
502                 return ();
503         }
504
505         my $pv = shift @pvs;
506         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
507         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
508         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
509 }
510
511 sub prettyprint_pv {
512         my ($pos, @pvs) = @_;
513
514         my $cachekey = join('', @pvs);
515         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
516                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
517         } else {
518                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
519                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
520                 return @res;
521         }
522 }
523
524 sub output {
525         #return;
526
527         return if (!defined($pos_calculating));
528
529         # Don't update too often.
530         my $age = Time::HiRes::tv_interval($latest_update);
531         if ($age < $remoteglotconf::update_max_interval) {
532                 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
533                 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
534                 return;
535         }
536         
537         my $info = $engine->{'info'};
538
539         #
540         # If we have tablebase data from a previous lookup, replace the
541         # engine data with the data from the tablebase.
542         #
543         my $fen = $pos_calculating->fen();
544         if (exists($tb_cache{$fen})) {
545                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
546                         delete $info->{$key . '1'};
547                         delete $info->{$key};
548                 }
549                 $info->{'nodes'} = 0;
550                 $info->{'nps'} = 0;
551                 $info->{'depth'} = 0;
552                 $info->{'seldepth'} = 0;
553                 $info->{'tbhits'} = 0;
554
555                 my $t = $tb_cache{$fen};
556                 my $pv = $t->{'pv'};
557                 my $matelen = int((1 + $t->{'score'}) / 2);
558                 if ($t->{'result'} eq '1/2-1/2') {
559                         $info->{'score_cp'} = 0;
560                 } elsif ($t->{'result'} eq '1-0') {
561                         if ($pos_calculating->{'toplay'} eq 'B') {
562                                 $info->{'score_mate'} = -$matelen;
563                         } else {
564                                 $info->{'score_mate'} = $matelen;
565                         }
566                 } else {
567                         if ($pos_calculating->{'toplay'} eq 'B') {
568                                 $info->{'score_mate'} = $matelen;
569                         } else {
570                                 $info->{'score_mate'} = -$matelen;
571                         }
572                 }
573                 $info->{'pv'} = $pv;
574                 $info->{'tablebase'} = 1;
575         } else {
576                 $info->{'tablebase'} = 0;
577         }
578         
579         #
580         # Some programs _always_ report MultiPV, even with only one PV.
581         # In this case, we simply use that data as if MultiPV was never
582         # specified.
583         #
584         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
585                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
586                         if (exists($info->{$key . '1'})) {
587                                 $info->{$key} = $info->{$key . '1'};
588                         }
589                 }
590         }
591         
592         #
593         # Check the PVs first. if they're invalid, just wait, as our data
594         # is most likely out of sync. This isn't a very good solution, as
595         # it can frequently miss stuff, but it's good enough for most users.
596         #
597         eval {
598                 my $dummy;
599                 if (exists($info->{'pv'})) {
600                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
601                 }
602         
603                 my $mpv = 1;
604                 while (exists($info->{'pv' . $mpv})) {
605                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
606                         ++$mpv;
607                 }
608         };
609         if ($@) {
610                 $engine->{'info'} = {};
611                 return;
612         }
613
614         output_screen();
615         output_json(0);
616         $latest_update = [Time::HiRes::gettimeofday];
617 }
618
619 sub output_screen {
620         my $info = $engine->{'info'};
621         my $id = $engine->{'id'};
622
623         my $text = 'Analysis';
624         if ($pos_calculating->{'last_move'} ne 'none') {
625                 if ($pos_calculating->{'toplay'} eq 'W') {
626                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
627                 } else {
628                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
629                 }
630                 if (exists($id->{'name'})) {
631                         $text .= ',';
632                 }
633         }
634
635         if (exists($id->{'name'})) {
636                 $text .= " by $id->{'name'}:\n\n";
637         } else {
638                 $text .= ":\n\n";
639         }
640
641         return unless (exists($pos_calculating->{'board'}));
642                 
643         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
644                 # multi-PV
645                 my $mpv = 1;
646                 while (exists($info->{'pv' . $mpv})) {
647                         $text .= sprintf "  PV%2u", $mpv;
648                         my $score = short_score($info, $pos_calculating, $mpv);
649                         $text .= "  ($score)" if (defined($score));
650
651                         my $tbhits = '';
652                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
653                                 if ($info->{'tbhits' . $mpv} == 1) {
654                                         $tbhits = ", 1 tbhit";
655                                 } else {
656                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
657                                 }
658                         }
659
660                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
661                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
662                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
663                         }
664
665                         $text .= ":\n";
666                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
667                         $text .= "\n";
668                         ++$mpv;
669                 }
670         } else {
671                 # single-PV
672                 my $score = long_score($info, $pos_calculating, '');
673                 $text .= "  $score\n" if defined($score);
674                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
675                 $text .=  "\n";
676
677                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
678                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
679                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
680                 }
681                 if (exists($info->{'seldepth'})) {
682                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
683                 }
684                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
685                         if ($info->{'tbhits'} == 1) {
686                                 $text .= ", one Syzygy hit";
687                         } else {
688                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
689                         }
690                 }
691                 $text .= "\n\n";
692         }
693
694         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
695
696         my @refutation_lines = ();
697         if (defined($engine2)) {
698                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
699                         my $info = $engine2->{'info'};
700                         last if (!exists($info->{'pv' . $mpv}));
701                         eval {
702                                 my $pv = $info->{'pv' . $mpv};
703
704                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
705                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
706                                 if (scalar @pretty_pv > 5) {
707                                         @pretty_pv = @pretty_pv[0..4];
708                                         push @pretty_pv, "...";
709                                 }
710                                 my $key = $pretty_move;
711                                 my $line = sprintf("  %-6s %6s %3s  %s",
712                                         $pretty_move,
713                                         short_score($info, $pos_calculating_second_engine, $mpv),
714                                         "d" . $info->{'depth' . $mpv},
715                                         join(', ', @pretty_pv));
716                                 push @refutation_lines, [ $key, $line ];
717                         };
718                 }
719         }
720
721         if ($#refutation_lines >= 0) {
722                 $text .= "Shallow search of all legal moves:\n\n";
723                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
724                         $text .= $line->[1] . "\n";
725                 }
726                 $text .= "\n\n";        
727         }       
728
729         if ($last_text ne $text) {
730                 print "\e[H\e[2J"; # clear the screen
731                 print $text;
732                 $last_text = $text;
733         }
734 }
735
736 sub output_json {
737         my $historic_json_only = shift;
738         my $info = $engine->{'info'};
739
740         my $json = {};
741         $json->{'position'} = $pos_calculating->to_json_hash();
742         $json->{'id'} = $engine->{'id'};
743         $json->{'score'} = long_score($info, $pos_calculating, '');
744         $json->{'short_score'} = short_score($info, $pos_calculating, '');
745         $json->{'plot_score'} = plot_score($info, $pos_calculating, '');
746
747         $json->{'nodes'} = $info->{'nodes'};
748         $json->{'nps'} = $info->{'nps'};
749         $json->{'depth'} = $info->{'depth'};
750         $json->{'tbhits'} = $info->{'tbhits'};
751         $json->{'seldepth'} = $info->{'seldepth'};
752         $json->{'tablebase'} = $info->{'tablebase'};
753
754         $json->{'pv_uci'} = $info->{'pv'};  # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
755         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
756
757         my %refutation_lines = ();
758         my @refutation_lines = ();
759         if (defined($engine2)) {
760                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
761                         my $info = $engine2->{'info'};
762                         my $pretty_move = "";
763                         my @pretty_pv = ();
764                         last if (!exists($info->{'pv' . $mpv}));
765
766                         eval {
767                                 my $pv = $info->{'pv' . $mpv};
768                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
769                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
770                                 $refutation_lines{$pv->[0]} = {
771                                         sort_key => $pretty_move,
772                                         depth => $info->{'depth' . $mpv},
773                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
774                                         pretty_score => short_score($info, $pos_calculating, $mpv),
775                                         pretty_move => $pretty_move,
776                                         pv_pretty => \@pretty_pv,
777                                 };
778                         };
779                 }
780         }
781         $json->{'refutation_lines'} = \%refutation_lines;
782
783         # Piece together historic score information, to the degree we have it.
784         if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
785                 my %score_history = ();
786
787                 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
788                 my $pos = Position->start_pos('white', 'black');
789                 my $halfmove_num = 0;
790                 for my $move (@{$pos_calculating->{'pretty_history'}}) {
791                         my $id = id_for_pos($pos, $halfmove_num);
792                         my $ref = $dbh->selectrow_hashref($q, undef, $id);
793                         if (defined($ref)) {
794                                 $score_history{$halfmove_num} = [
795                                         $ref->{'plot_score'},
796                                         $ref->{'short_score'}
797                                 ];
798                         }
799                         ++$halfmove_num;
800                         ($pos) = $pos->make_pretty_move($move);
801                 }
802                 $q->finish;
803
804                 # If at any point we are missing 10 consecutive moves,
805                 # truncate the history there. This is so we don't get into
806                 # a situation where we e.g. start analyzing at move 45,
807                 # but we have analysis for 1. e4 from some completely different game
808                 # and thus show a huge hole.
809                 my $consecutive_missing = 0;
810                 my $truncate_until = 0;
811                 for (my $i = $halfmove_num; $i --> 0; ) {
812                         if ($consecutive_missing >= 10) {
813                                 delete $score_history{$i};
814                                 next;
815                         }
816                         if (exists($score_history{$i})) {
817                                 $consecutive_missing = 0;
818                         } else {
819                                 ++$consecutive_missing;
820                         }
821                 }
822
823                 $json->{'score_history'} = \%score_history;
824         }
825
826         my $json_enc = JSON::XS->new;
827         $json_enc->canonical(1);
828         my $encoded = $json_enc->encode($json);
829         unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
830                 (defined($last_written_json) && $last_written_json eq $encoded)) {
831                 atomic_set_contents($remoteglotconf::json_output, $encoded);
832                 $last_written_json = $encoded;
833         }
834
835         if (exists($pos_calculating->{'pretty_history'}) &&
836             defined($remoteglotconf::json_history_dir)) {
837                 my $id = id_for_pos($pos_calculating);
838                 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
839
840                 # Overwrite old analysis (assuming it exists at all) if we're
841                 # using a different engine, or if we've calculated deeper.
842                 # nodes is used as a tiebreaker. Don't bother about Multi-PV
843                 # data; it's not that important.
844                 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
845                 my $new_depth = $json->{'depth'} // 0;
846                 my $new_nodes = $json->{'nodes'} // 0;
847                 if (!defined($old_engine) ||
848                     $old_engine ne $json->{'id'}{'name'} ||
849                     $new_depth > $old_depth ||
850                     ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
851                         atomic_set_contents($filename, $encoded);
852                         if (defined($json->{'plot_score'})) {
853                                 local $dbh->{AutoCommit} = 0;
854                                 $dbh->do('DELETE FROM scores WHERE id=?', undef, $id);
855                                 $dbh->do('INSERT INTO scores (id, plot_score, short_score, engine, depth, nodes) VALUES (?,?,?,?,?,?)', undef,
856                                         $id, $json->{'plot_score'}, $json->{'short_score'},
857                                         $json->{'id'}{'name'}, $new_depth, $new_nodes);
858                                 $dbh->commit;
859                         }
860                 }
861         }
862 }
863
864 sub atomic_set_contents {
865         my ($filename, $contents) = @_;
866
867         open my $fh, ">", $filename . ".tmp"
868                 or return;
869         print $fh $contents;
870         close $fh;
871         rename($filename . ".tmp", $filename);
872 }
873
874 sub id_for_pos {
875         my ($pos, $halfmove_num) = @_;
876
877         $halfmove_num //= scalar @{$pos->{'pretty_history'}};
878         (my $fen = $pos->fen()) =~ tr,/ ,-_,;
879         return "move$halfmove_num-$fen";
880 }
881
882 sub get_json_analysis_stats {
883         my $id = shift;
884         my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
885         if (defined($ref)) {
886                 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
887         } else {
888                 return ('', 0, 0);
889         }
890 }
891
892 sub uciprint {
893         my ($engine, $msg) = @_;
894         $engine->print($msg);
895         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
896 }
897
898 sub short_score {
899         my ($info, $pos, $mpv) = @_;
900
901         my $invert = ($pos->{'toplay'} eq 'B');
902         if (defined($info->{'score_mate' . $mpv})) {
903                 if ($invert) {
904                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
905                 } else {
906                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
907                 }
908         } else {
909                 if (exists($info->{'score_cp' . $mpv})) {
910                         my $score = $info->{'score_cp' . $mpv} * 0.01;
911                         if ($score == 0) {
912                                 if ($info->{'tablebase'}) {
913                                         return "TB draw";
914                                 } else {
915                                         return " 0.00";
916                                 }
917                         }
918                         if ($invert) {
919                                 $score = -$score;
920                         }
921                         return sprintf "%+5.2f", $score;
922                 }
923         }
924
925         return undef;
926 }
927
928 sub score_sort_key {
929         my ($info, $pos, $mpv, $invert) = @_;
930
931         if (defined($info->{'score_mate' . $mpv})) {
932                 my $mate = $info->{'score_mate' . $mpv};
933                 my $score;
934                 if ($mate > 0) {
935                         # Side to move mates
936                         $score = 99999 - $mate;
937                 } else {
938                         # Side to move is getting mated (note the double negative for $mate)
939                         $score = -99999 - $mate;
940                 }
941                 if ($invert) {
942                         $score = -$score;
943                 }
944                 return $score;
945         } else {
946                 if (exists($info->{'score_cp' . $mpv})) {
947                         my $score = $info->{'score_cp' . $mpv};
948                         if ($invert) {
949                                 $score = -$score;
950                         }
951                         return $score;
952                 }
953         }
954
955         return undef;
956 }
957
958 sub long_score {
959         my ($info, $pos, $mpv) = @_;
960
961         if (defined($info->{'score_mate' . $mpv})) {
962                 my $mate = $info->{'score_mate' . $mpv};
963                 if ($pos->{'toplay'} eq 'B') {
964                         $mate = -$mate;
965                 }
966                 if ($mate > 0) {
967                         return sprintf "White mates in %u", $mate;
968                 } else {
969                         return sprintf "Black mates in %u", -$mate;
970                 }
971         } else {
972                 if (exists($info->{'score_cp' . $mpv})) {
973                         my $score = $info->{'score_cp' . $mpv} * 0.01;
974                         if ($score == 0) {
975                                 if ($info->{'tablebase'}) {
976                                         return "Theoretical draw";
977                                 } else {
978                                         return "Score:  0.00";
979                                 }
980                         }
981                         if ($pos->{'toplay'} eq 'B') {
982                                 $score = -$score;
983                         }
984                         return sprintf "Score: %+5.2f", $score;
985                 }
986         }
987
988         return undef;
989 }
990
991 # For graphs; a single number in centipawns, capped at +/- 500.
992 sub plot_score {
993         my ($info, $pos, $mpv) = @_;
994
995         my $invert = ($pos->{'toplay'} eq 'B');
996         if (defined($info->{'score_mate' . $mpv})) {
997                 my $mate = $info->{'score_mate' . $mpv};
998                 if ($invert) {
999                         $mate = -$mate;
1000                 }
1001                 if ($mate > 0) {
1002                         return 500;
1003                 } else {
1004                         return -500;
1005                 }
1006         } else {
1007                 if (exists($info->{'score_cp' . $mpv})) {
1008                         my $score = $info->{'score_cp' . $mpv};
1009                         if ($invert) {
1010                                 $score = -$score;
1011                         }
1012                         $score = 500 if ($score > 500);
1013                         $score = -500 if ($score < -500);
1014                         return int($score);
1015                 }
1016         }
1017
1018         return undef;
1019 }
1020
1021 my %book_cache = ();
1022 sub book_info {
1023         my ($fen, $board, $toplay) = @_;
1024
1025         if (exists($book_cache{$fen})) {
1026                 return $book_cache{$fen};
1027         }
1028
1029         my $ret = `./booklook $fen`;
1030         return "" if ($ret =~ /Not found/ || $ret eq '');
1031
1032         my @moves = ();
1033
1034         for my $m (split /\n/, $ret) {
1035                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1036
1037                 my $pmove;
1038                 if ($move eq '')  {
1039                         $pmove = '(current)';
1040                 } else {
1041                         ($pmove) = prettyprint_pv_no_cache($board, $move);
1042                         $pmove .= $annotation;
1043                 }
1044
1045                 my $score;
1046                 if ($toplay eq 'W') {
1047                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1048                 } else {
1049                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1050                 }
1051                 my $n = $win + $draw + $lose;
1052                 
1053                 my $percent;
1054                 if ($n == 0) {
1055                         $percent = "     ";
1056                 } else {
1057                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1058                 }
1059
1060                 push @moves, [ $pmove, $n, $percent, $rating ];
1061         }
1062
1063         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1064         
1065         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1066         for my $m (@moves) {
1067                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1068         }
1069
1070         return $text;
1071 }
1072
1073 sub extract_clock {
1074         my ($pgn, $pos) = @_;
1075
1076         # Look for extended PGN clock tags.
1077         my $tags = $pgn->tags;
1078         if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1079                 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1080                 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1081                 return;
1082         }
1083
1084         # Look for TCEC-style time comments.
1085         my $moves = $pgn->moves;
1086         my $comments = $pgn->comments;
1087         my $last_black_move = int((scalar @$moves) / 2);
1088         my $last_white_move = int((1 + scalar @$moves) / 2);
1089
1090         my $black_key = $last_black_move . "b";
1091         my $white_key = $last_white_move . "w";
1092
1093         if (exists($comments->{$white_key}) &&
1094             exists($comments->{$black_key}) &&
1095             $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1096             $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1097                 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1098                 $pos->{'white_clock'} = hms_to_sec($1);
1099                 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1100                 $pos->{'black_clock'} = hms_to_sec($1);
1101                 return;
1102         }
1103
1104         delete $pos->{'white_clock'};
1105         delete $pos->{'black_clock'};
1106 }
1107
1108 sub hms_to_sec {
1109         my $hms = shift;
1110         return undef if (!defined($hms));
1111         $hms =~ /(\d+):(\d+):(\d+)/;
1112         return $1 * 3600 + $2 * 60 + $3;
1113 }
1114
1115 sub find_clock_start {
1116         my ($pos, $prev_pos) = @_;
1117
1118         # If the game is over, the clock is stopped.
1119         if (exists($pos->{'result'}) &&
1120             ($pos->{'result'} eq '1-0' ||
1121              $pos->{'result'} eq '1/2-1/2' ||
1122              $pos->{'result'} eq '0-1')) {
1123                 return;
1124         }
1125
1126         # When we don't have any moves, we assume the clock hasn't started yet.
1127         if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1128                 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1129                         &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1130                 }
1131                 return;
1132         }
1133
1134         # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1135         # The history is needed for id_for_pos.
1136         if (!exists($pos->{'pretty_history'})) {
1137                 return;
1138         }
1139
1140         my $id = id_for_pos($pos);
1141         my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1142         if (defined($clock_info)) {
1143                 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1144                 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1145                 if ($pos->{'toplay'} eq 'W') {
1146                         $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1147                 } else {
1148                         $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1149                 }
1150                 return;
1151         }
1152
1153         # OK, we haven't seen this position before, so we assume the move
1154         # happened right now.
1155
1156         # See if we should do our own clock management (ie., clock information
1157         # is spurious or non-existent).
1158         if (defined($remoteglotconf::adjust_clocks_before_move)) {
1159                 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1160                 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1161                 if (defined($prev_pos->{'white_clock_target'})) {
1162                         $wc = $prev_pos->{'white_clock_target'} - time;
1163                 }
1164                 if (defined($prev_pos->{'black_clock_target'})) {
1165                         $bc = $prev_pos->{'black_clock_target'} - time;
1166                 }
1167                 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1168                 $pos->{'white_clock'} = $wc;
1169                 $pos->{'black_clock'} = $bc;
1170         }
1171
1172         my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1173         if (!exists($pos->{$key})) {
1174                 # No clock information.
1175                 return;
1176         }
1177         my $time_left = $pos->{$key};
1178         my ($white_clock_target, $black_clock_target);
1179         if ($pos->{'toplay'} eq 'W') {
1180                 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1181         } else {
1182                 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1183         }
1184         local $dbh->{AutoCommit} = 0;
1185         $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1186         $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1187                 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1188         $dbh->commit;
1189 }
1190
1191 sub schedule_tb_lookup {
1192         return if (!defined($remoteglotconf::tb_serial_key));
1193         my $pos = $pos_waiting // $pos_calculating;
1194         return if (exists($tb_cache{$pos->fen()}));
1195
1196         # If there's more than seven pieces, there's not going to be an answer,
1197         # so don't bother.
1198         return if ($pos->num_pieces() > 7);
1199
1200         # Max one at a time. If it's still relevant when it returns,
1201         # schedule_tb_lookup() will be called again.
1202         return if ($tb_lookup_running);
1203
1204         $tb_lookup_running = 1;
1205         my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1206                 $remoteglotconf::tb_serial_key .
1207                 '&auth.password=aquarium&type=0&fen=' . 
1208                 URI::Escape::uri_escape($pos->fen());
1209         print TBLOG "Downloading $url...\n";
1210         AnyEvent::HTTP::http_get($url, sub {
1211                 handle_tb_lookup_return(@_, $pos, $pos->fen());
1212         });
1213 }
1214
1215 sub handle_tb_lookup_return {
1216         my ($body, $header, $pos, $fen) = @_;
1217         print TBLOG "Response for [$fen]:\n";
1218         print TBLOG $header . "\n\n";
1219         print TBLOG $body . "\n\n";
1220         eval {
1221                 my $response = JSON::XS::decode_json($body);
1222                 if ($response->{'ErrorCode'} != 0) {
1223                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1224                 }
1225                 my $state = $response->{'Response'}{'StateString'};
1226                 if ($state eq 'COMPLETE') {
1227                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1228                         if (!defined($pgn) || !$pgn->read_game()) {
1229                                 warn "Error in parsing PGN\n";
1230                         } else {
1231                                 $pgn->quick_parse_game;
1232                                 my $pvpos = $pos;
1233                                 my $moves = $pgn->moves;
1234                                 my @uci_moves = ();
1235                                 for my $move (@$moves) {
1236                                         my $uci_move;
1237                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1238                                         push @uci_moves, $uci_move;
1239                                 }
1240                                 $tb_cache{$fen} = {
1241                                         result => $pgn->result,
1242                                         pv => \@uci_moves,
1243                                         score => $response->{'Response'}{'Score'},
1244                                 };
1245                                 output();
1246                         }
1247                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1248                         # Try again in a second. Note that if we have changed
1249                         # position in the meantime, we might query a completely
1250                         # different position! But that's fine.
1251                 } else {
1252                         die "Unknown response state " . $state;
1253                 }
1254
1255                 # Wait a second before we schedule another one.
1256                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1257                         $tb_lookup_running = 0;
1258                         schedule_tb_lookup();
1259                 });
1260         };
1261         if ($@) {
1262                 warn "Error in tablebase lookup: $@";
1263
1264                 # Don't try this one again, but don't block new lookups either.
1265                 $tb_lookup_running = 0;
1266         }
1267 }
1268
1269 sub open_engine {
1270         my ($cmdline, $tag, $cb) = @_;
1271         return undef if (!defined($cmdline));
1272         return Engine->open($cmdline, $tag, $cb);
1273 }
1274
1275 sub col_letter_to_num {
1276         return ord(shift) - ord('a');
1277 }
1278
1279 sub row_letter_to_num {
1280         return 7 - (ord(shift) - ord('1'));
1281 }
1282
1283 sub parse_uci_move {
1284         my $move = shift;
1285         my $from_col = col_letter_to_num(substr($move, 0, 1));
1286         my $from_row = row_letter_to_num(substr($move, 1, 1));
1287         my $to_col   = col_letter_to_num(substr($move, 2, 1));
1288         my $to_row   = row_letter_to_num(substr($move, 3, 1));
1289         my $promo    = substr($move, 4, 1);
1290         return ($from_col, $from_row, $to_col, $to_row, $promo);
1291 }