function [isfilter,filter,freq,applyto] = applyfilteropt(obj,opt,freq,nx,names)
% APPLYFILTEROPT  [Not a public function] Pre-process filter options in ACF.
%
% Backend IRIS function.
% No help provided.

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

%**************************************************************************

filter = opt.filter;
applyto = opt.applyto;

% Linear filter applied to some variables.
if isequal(applyto,':') || isequal(applyto,Inf)
    applyto = true(1,nx);
elseif iscellstr(applyto)
    applyto = applyto(:).';
    usrapplyto = applyto;
    applyto = regexprep(applyto,'log\((.*?)\)','$1');
    applyto = regexprep(applyto,'\{.*?\}','');
    applyto = strfun.findnames(names,applyto);
    pos = isnan(applyto);
    if any(pos)
        utils.error(class(obj),'#Name_not_exists',usrapplyto(pos));
    end
    applyto = false(1,nx);
    applyto(pos) = true;
elseif isnumeric(applyto)
    pos = applyto(:).';
    applyto = false(1,nx);
    applyto(pos) = true;
elseif islogical(applyto)
    applyto = applyto(:).';
    if length(applyto) > nx
        applyto = applyto(1:nx);
    elseif length(applyto) < nx
        applyto(end+1:nx) = false;
    end
end

if isfield(opt,'nfreq') && isempty(freq)
    width = pi/opt.nfreq;
    freq = width/2 : width : pi;
end

if ~isempty(filter) && any(applyto)
    isfilter = true;
    filter = xxfdfilter(filter,freq);
else
    isfilter = false;
    filter = [];
    freq = [];
end

end

% Subfunctions.

%**************************************************************************
function filter = xxfdfilter(fstring,freq)

nfreq = length(freq);
frq = freq; %#ok<NASGU>

% Vectorise *, /, \, ^ operators.
fstring = strfun.vectorise(fstring);

% Evaluate frequency response function of filter.
l = exp(-1i*freq); %#ok<NASGU>
per = 2*pi./freq; %#ok<NASGU>
filter = eval(lower(fstring));
if length(filter) == 1
    filter = ones(1,nfreq)*filter;
end

% Make sure the result is numeric.
filter = +filter;

end