function [OK, out] = remoteBlockExecution(action, varargin)
%remoteBlockExecution Wrapper around remoteBlockExecutionPlain.

% Copyright 2020 The MathWorks, Inc.

% PCT_Java_Transition_TODO(g2331699) remove this file when MDA serialization works correctly.

switch action
  case 'prelude'
    [commHCell, fcnHandles, keysToClear, preludeExcept] = iUnpackPreludeArgs(varargin{:});
    [OK, out] = spmdlang.remoteBlockExecutionPlain(action, commHCell, fcnHandles, keysToClear, preludeExcept);
  otherwise
    [OK, out] = spmdlang.remoteBlockExecutionPlain(action, varargin{:});
end

try
    out = distcompserialize(out);
catch E
    OK = false;
    stackFilesToIgnore = {'remoteBlockExecutionPlain'};
    out = distcompserialize(ParallelException.hBuildFromRemoteException(E, stackFilesToIgnore));
end
end

function [commHCell, fcnHandles, keysToClear, preludeExcept] = iUnpackPreludeArgs(serComms, serFcns, keysToClear)
try
    commHCell = distcompdeserialize(serComms);
    fcnHandles = distcompdeserialize(serFcns);
catch preludeExcept
    dctSchedulerMessage(0, 'Error deserializing SPMD inputs.', preludeExcept);
end
preludeExcept = MException.empty();
end
