+sub extract_clock {
+ my ($pgn, $pos) = @_;
+
+ # Look for extended PGN clock tags.
+ my $tags = $pgn->tags;
+ if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
+ $pos->{'white_clock'} = $tags->{'WhiteClock'};
+ $pos->{'black_clock'} = $tags->{'BlackClock'};
+
+ $pos->{'white_clock'} =~ s/\b(\d)\b/0$1/g;
+ $pos->{'black_clock'} =~ s/\b(\d)\b/0$1/g;
+ return;
+ }
+
+ # Look for TCEC-style time comments.
+ my $moves = $pgn->moves;
+ my $comments = $pgn->comments;
+ my $last_black_move = int((scalar @$moves) / 2);
+ my $last_white_move = int((1 + scalar @$moves) / 2);
+
+ my $black_key = $last_black_move . "b";
+ my $white_key = $last_white_move . "w";
+
+ if (exists($comments->{$white_key}) &&
+ exists($comments->{$black_key}) &&
+ $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/ &&
+ $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/) {
+ $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/;
+ $pos->{'white_clock'} = $1;
+ $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/;
+ $pos->{'black_clock'} = $1;
+ return;
+ }
+}
+
+sub find_clock_start {
+ my $pos = shift;
+
+ # If the game is over, the clock is stopped.
+ if (exists($pos->{'result'}) &&
+ ($pos->{'result'} eq '1-0' ||
+ $pos->{'result'} eq '1/2-1/2' ||
+ $pos->{'result'} eq '0-1')) {
+ return;
+ }
+
+ # When we don't have any moves, we assume the clock hasn't started yet.
+ if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
+ return;
+ }
+
+ # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
+ if (!exists($pos->{'pretty_history'})) {
+ return;
+ }
+
+ my $id = id_for_pos($pos);
+ if (exists($clock_target_for_pos{$id})) {
+ if ($pos->{'toplay'} eq 'W') {
+ $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
+ } else {
+ $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
+ }
+ return;
+ }
+
+ # OK, we haven't seen this position before, so we assume the move
+ # happened right now.
+ my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
+ if (!exists($pos->{$key})) {
+ # No clock information.
+ return;
+ }
+ $pos->{$key} =~ /(\d+):(\d+):(\d+)/;
+ my $time_left = $1 * 3600 + $2 * 60 + $3;
+ $clock_target_for_pos{$id} = time + $time_left;
+ if ($pos->{'toplay'} eq 'W') {
+ $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
+ } else {
+ $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
+ }
+}
+