function remove(targetObjects, varargin)
%TARGET.REMOVE    Remove target feature objects from memory.
%   TARGET.REMOVE(targetFeatureObjects) removes the specified target
%   feature objects from memory. targetFeatureObjects can be a scalar or 
%   vector of target feature objects. If the target feature object was 
%   added with data persistence ('UserInstall' set to true), TARGET.REMOVE 
%   will end data persistence across sessions.
%
%   TARGET.REMOVE(targetFeatureClass, targetFeatureObjectIdentifier)
%   removes a target feature object from memory using the specified class 
%   and identifier. If a target feature object does not exist in memory, no
%   action is performed.
%
%   See also TARGET.CREATE, TARGET.ADD, TARGET.GET

%   Copyright 2018 The MathWorks, Inc.

    if nargin > 2
        error(message('MATLAB:maxrhs'));
    end

    targetObjectInstances = target.Object.empty();
    tr = targetrepository.create();

    if isa(targetObjects, 'target.Object')
        targetObjectInstances = targetObjects(:);
    elseif iscell(targetObjects)
        % could be a cell of strings, or a cell of objects
        targetElements = cellfun(@(e) isa(e, 'target.Object') && isscalar(e), targetObjects);
        
        if all(targetElements)            
            targetObjectInstances = [targetObjects{:}];
        elseif any(targetElements)
            error(message('targetrepository:Command:CellArrayMustContainTargetObjects'));
        end        
    end
    
    if isempty(targetObjectInstances)
        % We should have some form of string type
        stringArgument1 = string(targetObjects);
        
        if (isStringScalar(stringArgument1) && ~ismissing(stringArgument1))
            % Now we have a scalar string, we know this is a class
            % definition and varargin{1} will be the scalar identifier
            identifier = string(varargin{1});
            if (~isStringScalar(identifier) || ismissing(identifier))
                error(message('targetrepository:Command:InvalidIdentifier')); % needs to be convertible to a scalar string
            end
            tr.remove(stringArgument1, identifier);            
        else
            % We have a string array. This must be a nx2 array which
            % represents a list of class-identifier values
            if ((size(stringArgument1, 2) ~= 2) || any(ismissing(stringArgument1), 'all'))
                error(message('targetrepository:Command:NotConvertableTox2StringArray')); % needs to be convertible to an nx2 string array
            end
            tr.remove(stringArgument1(:, 1), stringArgument1(:,2));            
        end
    else
        tr.remove(targetObjectInstances);
    end
end

