+ my $encoded = JSON::XS::encode_json($json);
+ atomic_set_contents($remoteglotconf::json_output, $encoded);
+
+ if (exists($pos_calculating->{'history'}) &&
+ defined($remoteglotconf::json_history_dir)) {
+ my $halfmove_num = scalar @{$pos_calculating->{'history'}};
+ (my $fen = $pos_calculating->fen()) =~ tr,/ ,-_,;
+ my $filename = $remoteglotconf::json_history_dir . "/move$halfmove_num-$fen.json";
+
+ # Overwrite old analysis (assuming it exists at all) if we're
+ # using a different engine, or if we've calculated deeper.
+ # nodes is used as a tiebreaker. Don't bother about Multi-PV
+ # data; it's not that important.
+ my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($filename);
+ my $new_depth = $json->{'depth'} // 0;
+ my $new_nodes = $json->{'nodes'} // 0;
+ if (!defined($old_engine) ||
+ $old_engine ne $json->{'id'}{'name'} ||
+ $new_depth > $old_depth ||
+ ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
+ atomic_set_contents($filename, $encoded);
+ }
+ }
+}
+
+sub atomic_set_contents {
+ my ($filename, $contents) = @_;
+
+ open my $fh, ">", $filename . ".tmp"