function [values, names, remaining, errorInfo, elapsed] = LoadMat(fileFullPath)
% LoadMat  Load variables from .mat file specified by fileFullPath.  It 
% calls 'load' command and uses default MAT-file version.
%
% fileFullPath is the absolute path to the .mat file
%
% The values output is cell array of data that have been loaded from the 
% .mat file and then escaped for COM.  The names output is cell array of 
% names of those variables.  The remaining output is cell array of names of 
% the remaining variables that are unable to import to LabVIEW, because the
% data types are not supported.  Having remaining variables is considered 
% partial success, not error.  All are row 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.  When error occurs, values, names 
% and remaining outputs are empty.  The elapsed is a numeric array 
% containing performance metrics.
%
    values = {};
    names = {};
    remaining = {};
    errorInfo = {};
    elapsed = zeros(1, 3);
    
    if isstring(fileFullPath)
        fileFullPath = char(fileFullPath);
    end
    
    try
        [values, names, remaining, elapsed] = localLoadMat(fileFullPath);
    catch ME
        errorInfo{1} = ME.message;
        errorInfo{2} = ME.identifier;
    end
end

% Load the variables from MAT-file
function [values, names, remaining, elapsed] = localLoadMat(fileFullPath)
    values = {};
    names = {};
    remaining = {};
    elapsed = zeros(1, 3);
    
    t0 = tic;
    S = load(fileFullPath);
    elapsed(2) = toc(t0);
    
    t0 = tic;
    C = struct2cell(S);
    N = fieldnames(S);
    for k = 1:numel(C)
        try
            V = niifm.EscapeForCom(C{k});
            values{end+1} = V;
            names{end+1} = N{k};
        catch
            remaining{end+1} = N{k};
        end
    end
    elapsed(3) = toc(t0);
end
