function varcleanup(refname)
%VARCLEANUP Cleans up a variable created by loadVariable
%
%   VARCLEANUP(refname)
%

% Copyright 2010-2012 The MathWorks, Inc.

    [basename,fieldref] = strtok(refname,'.');
    fieldname = strtok(fieldref,'.');
    
    if evalin('base',['exist(''' basename ''')'])
        if evalin('base',['isstruct(' basename ')'])
            % Check for an open Variable Editor or Variable Comparison for
            % this field.
            isopen = comparisons.internal.variableInUse(refname);
            if ~isopen
                % It's no longer used anywhere, so we will delete the field
                % from the structure.  First take a local copy of the
                % structure.  MATLAB will avoid making copies of the actual
                % fields, since we're not going to modify their values.
                local = evalin('base',basename);
                if numel(fieldnames(local))==1
                    % There are no other field in the structure.  Delete
                    % the variable from the workspace
                    evalin('base',['clear ' basename]);
                elseif isfield(local,fieldname)
                    local = rmfield(local,fieldname);
                    assignin('base',basename,local);
                end
            end
        end
    end
end
