function [varData,omitVars,omitRecords] = handleReplacement(varData,varOpts,importErrorRule,missingRule,errorIDs,missingIDs)
%Handles Replacement Rules for a variable

% Copyright 2019 MathWorks, Inc.

% Used for handling replacement rules
[rows,cols] = size(errorIDs);
omitVars = false(1,cols);
omitRecords = false(rows,1);

    function processRules(ids,rule,errFcn)
        switch(rule)
            case 'error'
                rowK = find(any(ids,2),1);
                colK = find(ids(rowK,:),1);
                errFcn(varOpts{colK}.Type,rowK,colK);
            case 'fill'
                % Replace fill value
                fill = varOpts{1}.FillValue;
                [fill,varData] = matlab.io.internal.processRawFill(fill,varData);
                if any(ids,'all')
                    varData(ids) = fill;
                end
            case 'omitvar'
                % set the selected variable ID to zero so it can be filtered later.
                omitVars(:,any(ids,1)) = true;
            case 'omitrow'
                % Collect record numbers which need to be omitted
                omitRecords(any(ids,2),:) = true;
        end
    end

% Handle any error

if any(errorIDs,'all')
    processRules(errorIDs,importErrorRule,@(type,rowNum,colNum)errorRuleError(colNum,rowNum,type));
end

if any(missingIDs,'all')
    processRules(missingIDs,missingRule,@(~,rowNum,colNum)missingRuleError(colNum,rowNum));
end

% Remove omitted variables
if any(omitVars)
    varData(:,omitVars) = [];
end

% handle omit-records
if any(omitRecords)
    varData(omitRecords,:) = [];
end
end

function errorRuleError(i,rowNum,type)
error(message('MATLAB:spreadsheet:importoptions:ErrorRuleError',i,rowNum,type));
end

function missingRuleError(i,rowNum)
error(message('MATLAB:spreadsheet:importoptions:MissingRuleError',i,rowNum));
end