function unpack(struct)

% unpack

% Mike Wolovick, 12/17/2011

% This function creates variables in the workspace out of the fields of a
% structure.  The structure must have only one element, but it can have
% many fields.

% edit, 3/16/2020:  The function can be called with the "all" string, which
% automatically unpacks all structures in the parent workspace.  If any of
% the structures have length greater than one, they are skipped with a
% warning.



% Check input:
if isstruct(struct)==0 && strcmp(struct,'all')==0
    error('Input must either be a structure or the string, "all".')
end
if strcmp(struct,'all')==0
    if length(struct)~=1
        error('Input structure must have a length of one')
    end
end

% Check if input is 'all':
if strcmp(struct,'all')
    % Get all variables from the parent workspace:
    varnames=evalin('caller','who;');
    % Loop through variables:
    for ii=1:length(varnames)
        % Check if the variable is a structure:
        thisisstruct=evalin('caller',['isstruct(',varnames{ii},');']);
        if thisisstruct
            % Check the length of the structure:
            thislength=evalin('caller',['length(',varnames{ii},');']);
            if thislength==1
                % Get the structure:
                thisstruct=evalin('caller',[varnames{ii},';']);
                % Unpack structure:
                fields=fieldnames(thisstruct);
                for jj=1:length(fields)
                    eval(['data=thisstruct.',cell2mat(fields(jj)),';'])
                    assignin('caller',cell2mat(fields(jj)),data);
                end
            else
                % Display warning:
                disp(['Warning: skipping structure ',varnames{ii},' because length not equal to 1.'])
            end
        end
    end
else
    % Unpack input:
    fields=fieldnames(struct);
    for jj=1:length(fields)
        eval(['data=struct.',cell2mat(fields(jj)),';'])
        assignin('caller',cell2mat(fields(jj)),data);
    end
end



