function [errorInfo, elapsed] = SaveMat(fileFullPath, variables, varNames)
% SaveMat  Save variables to .mat file specified by fileFullPath.  It calls
% 'save' command and uses default MAT-file version.
%
% variables is a cell array containing all values to be saved.  All values
% should be escaped.  varNames is a cell array containing corresponding 
% variable names to be used in the MAT-file.  Both are column vectors.
%
% The errorInfo output returns an error if the script produced an error 
% or an empty cell array if there were no errors.  The errorInfo cell array
% contains 2 char vectors.  The first is the error message.  The second 
% cell is the error message ID string.  The elapsed is a numeric array 
% containing performance metrics.
%

    errorInfo = {};
    elapsed = zeros(1, 3);

    if isstring(fileFullPath)
        fileFullPath = char(fileFullPath);
    end
    
    try
        elapsed = localSaveMat(fileFullPath, variables, varNames);
    catch ME
        errorInfo{1} = ME.message;
        if strcmp(ME.identifier, 'NI:')
            errorInfo{2} = ME.identifier;
        elseif length(ME.stack) >= 3 && strcmp(ME.stack(end-2).name, 'UnescapeForCom')
            errorInfo{2} = 'NI:SetVariable';
        elseif length(ME.stack) >= 2 && strcmp(ME.stack(end-1).name, 'localSaveMat')
            errorInfo{2} = ME.identifier;
        else
            errorInfo{2} = 'NI:Unexpected';
        end
    end
end

% Save the variables to MAT-file
function elapsed = localSaveMat(fileFullPath, variables, varNames)
    elapsed = zeros(1, 3);
    t0 = tic;
    for k = 1:numel(variables)
        variables{k} = niifm.UnescapeForCom(variables{k});
    end
    elapsed(1) = toc(t0);
    
    t0 = tic;
    % Put variables in struct to avoid name conflict.  If varNames are
    % invalid, cell2struct throws 'Invalid field name "<name>"' error
    S = cell2struct(variables, varNames);
    save(fileFullPath, '-struct', 'S');
    elapsed(2) = toc(t0);
end

