function addProperty(h, propstoadd, proptoaddafter)
% Adds the given property to the view

%   Copyright 2010 The MathWorks, Inc.

if nargin > 1
    if isstring(propstoadd)
        propstoadd = cellstr(propstoadd);
    end
end

if nargin > 2
    proptoaddafter = convertStringsToChars(proptoaddafter);
end

if isempty(propstoadd)
    return;
end
% Take care of default cases
if nargin == 2    
    proptoaddafter = '';    
end
for i=1:length(propstoadd)    
    if  h.hasProperty(propstoadd{i})
        property = h.getProperty(propstoadd{i});        
        if property.isTransient || ~property.isVisible
            h.removeProperty({property.Name});
        else
            propstoadd{i} = '';
        end
    end
end
propstoadd(ismember(propstoadd,''))='';
if isempty(propstoadd)
    return;
end
viewProperties = [];
if isempty(h.Properties)
    % Take shortcut        
    for i = 1:length(propstoadd)
       viewProperties = [viewProperties; DAStudio.MEViewProperty(propstoadd{i})];       
    end
    % refresh the ME
    h.Properties = viewProperties;
    return;
end
% Remove properties which need reordering
h.disableLiveliness;
viewProperties = h.Properties;
propNames = get(viewProperties, 'Name');
for i = 1:length(propstoadd)
    id = strmatch(lower(propstoadd{i}), lower(propNames), 'exact');
    if ~isempty(id)
        for m = 1:length(id)
            k = id(m);
            if ~viewProperties(k).isVisible || viewProperties(k).isTransient
                viewProperties(k) = [];
                propNames = get(viewProperties, 'Name');
                if isempty(propNames)
                    break;
                end
            end
        end
    end
end
% Now add requested properties
index = length(viewProperties);
propNames = get(viewProperties, 'Name');
if ~isempty(proptoaddafter)
   index = strmatch(lower(proptoaddafter), lower(propNames), 'exact');
   if isempty(index)
       % Add at the end.
       index = length(viewProperties);
   end
end
vProps = viewProperties(1:index);
for j = 1:length(propstoadd)
    k = strmatch(lower(propstoadd{j}), lower(propNames), 'exact');
    if isempty(k)
        vProps = [vProps; DAStudio.MEViewProperty(propstoadd{j})];
    end
    % Make sure we do not add duplicate.
    propNames = get(vProps, 'Name');
end
vProps = [vProps; viewProperties(index+1:end)];
% refresh the ME
h.enableLiveliness;
h.Properties = vProps;