% REMOVEVAL removes values from the input AO(s).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DESCRIPTION: REMOVEVAL removes user specified value(s) from the input AO(s),
%              such as NaNs, Infs, or 0s. Depending on the values set in the plist,
%              it will replace them with nothing or with an interpolated value
%
% CALL:        b = removeVal(a, pl)
%
% INPUTS:      a  - input array of AOs
%              pl - parameter list with the keys 'axis' and 'method'
%
% OUTPUTS:     b  - output array of AOs
%
% REMARKs:
%
% <a href="matlab:utils.helper.displayMethodInfo('ao', 'removeVal')">Parameters Description</a>
%
% VERSION:     $Id: removeVal.m,v 1.10 2011/05/27 10:30:43 mauro Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = removeVal(varargin)
  
  % Check if this is a call for parameters
  if utils.helper.isinfocall(varargin{:})
    varargout{1} = getInfo(varargin{3});
    return
  end
  
  import utils.const.*
  utils.helper.msg(msg.PROC3, 'running %s/%s', mfilename('class'), mfilename);
  
  % Collect input variable names
  in_names = cell(size(varargin));
  for ii = 1:nargin,in_names{ii} = inputname(ii);end
  
  % Collect all AOs and plists
  [as, ao_invars] = utils.helper.collect_objects(varargin(:), 'ao', in_names);
  pl              = utils.helper.collect_objects(varargin(:), 'plist', in_names);
  
  % Decide on a deep copy or a modify
  bs = copy(as, nargout);
  
  % Combine plists
  pl = parse(pl, getDefaultPlist);
  
  % Get parameters
  ax            = find(pl, 'axis');
  method        = find(pl, 'method');
  value         = find(pl, 'value');
  interp_method = find(pl, 'interpolation');
  
  %-----------------------
  % Loop over input AOs
  for jj = 1:numel(bs)
    % record input history
    hin = bs(jj).hist;
    
    switch ax
      case 'y'
        % Find the index position of the elements to remove
        validY = true(size(bs(jj).y));
        for kk = 1:numel(value)
          if isnumeric(value(kk))
            if isfinite(value(kk))
              validY = validY & bs(jj).y ~= value(kk);
            else
              if isnan(value(kk))
                validY = validY & ~isnan(bs(jj).y);
              end
              if isinf(value(kk))
                validY = validY & ~isinf(bs(jj).y);
              end
            end
          end
        end
        
        % Go ahead and act on the data
        switch method
          case 'remove'
            if ~isa(bs(jj).data, 'cdata')
              % for tsdata, fsdata and xydata objects
              % Set X,Y
              x = bs(jj).x;
              bs(jj).setXY(...
                x(validY), bs(jj).data.y(validY));
              % Set DY
              if ~isempty(bs(jj).dy) && numel(bs(jj).dy) > 1
                bs(jj).setDy(bs(jj).data.dy(validY));
              end
              clear x;
            else
              % for cdata objects
              % Set Y
              bs(jj).setY(...
                bs(jj).data.y(validY));
              % Set DY
              if ~isempty(bs(jj).dy) && numel(bs(jj).dy) > 1
                bs(jj).setDy(bs(jj).data.dy(validY));
              end
            end
            
            % Set ENBW
            if isprop(bs(jj).data, 'enbw')
              bs(jj).data.setEnbw(bs(jj).enbw(validY));
            end
            
            % Set FS
            if isprop(bs(jj).data, 'fs') && isa(bs(jj).data, 'tsdata')
              bs(jj).data.setFs(bs(jj).fs); % TODO: we should recalculate it ...
            end
            
          case 'interp'
            if ~isa(bs(jj).data, 'cdata')
              % for tsdata, fsdata and xydata objects
              % Set Y
              x = bs(jj).x;
              y = bs(jj).y;
              
              % We need at least two valid points to interpolate on
              if sum(validY) >= 2
                % Set Y
                bs(jj).setY(...
                  interp1(x(validY), y(validY), x, interp_method, 'extrap'));
                if ~isempty(bs(jj).dy) && numel(bs(jj).dy) > 1
                  % Set DY
                  bs(jj).setDy(interp1(x(validY), bs(jj).data.dy(validY), x, interp_method, 'extrap'));
                end
                if isprop(bs(jj).data, 'enbw')
                  % Set ENBW
                  if ~isempty(bs(jj).data.enbw) && numel(bs(jj).data.enbw) > 1
                    bs(jj).data.setEnbw(interp1(x(validY), bs(jj).enbw(validY), x, interp_method, 'extrap'));
                  end
                end
              else
                % If we have 0 or 1 valid points, just set them
                % Set Y
                bs(jj).setXY(...
                  x(validY), bs(jj).data.y(validY));
                % Set DY
                if ~isempty(bs(jj).dy) && numel(bs(jj).dy) > 1
                  bs(jj).setDy(bs(jj).data.dy(validY));
                end
                % Set ENBW
                if isprop(bs(jj).data, 'enbw')
                  bs(jj).data.setEnbw(bs(jj).enbw(validY));
                end
                % Set FS
                if isprop(bs(jj).data, 'fs') && isa(bs(jj).data, 'tsdata')
                  bs(jj).data.setFs(bs(jj).fs); % TODO: we should recalculate it ...
                end
              end
              clear x y;
            else
              % for cdata object
              % We need at least two valid points to interpolate on
              if sum(validY) >= 2
                % Set Y
                bs(jj).setY(interp1(bs(jj).data.y(validY), [1:lenght(bs(jj).y)], method, 'extrap'));
                if ~isempty(bs(jj).dy) && numel(bs(jj).dy) > 1
                  % Set DY
                  bs(jj).setDy(interp1(bs(jj).x(validY), bs(jj).data.dy(validY), [1:lenght(bs(jj).y)], interp_method, 'extrap'));
                end
              else
                % If we have 0 or 1 valid points, just set them
                % Set Y
                bs(jj).setY(...
                  bs(jj).data.y(validY));
                % Set DY
                if ~isempty(bs(jj).dy) && numel(bs(jj).dy) > 1
                  bs(jj).setDy(bs(jj).data.dy(validY));
                end
              end
            end
            
          otherwise
            error('### Unrecognised method %s', method);
        end
      case {'x', 'xy'}
        utils.helper.msg(msg.IMPORTANT, 'Option %s not avalable yet, sorry.', ax);
      otherwise
        utils.helper.msg(msg.IMPORTANT, 'Option %s not recognised, sorry.', ax);
    end
    
    % set name
    bs(jj).name = sprintf('%s(%s)', mfilename, ao_invars{jj});
    % Add history
    bs(jj).addHistory(getInfo('None'), pl, ao_invars, hin);
  end
  
  % Set output
  varargout = utils.helper.setoutputs(nargout, bs);
end

%--------------------------------------------------------------------------
% Get Info Object
%--------------------------------------------------------------------------
function ii = getInfo(varargin)
  if nargin == 1 && strcmpi(varargin{1}, 'None')
    sets = {};
    pl   = [];
  else
    sets = {'Default'};
    pl   = getDefaultPlist();
  end
  % Build info object
  ii = minfo(mfilename, 'ao', 'ltpda', utils.const.categories.sigproc, '$Id: removeVal.m,v 1.10 2011/05/27 10:30:43 mauro Exp $', sets, pl);
end

%--------------------------------------------------------------------------
% Get Default Plist
%--------------------------------------------------------------------------
function plout = getDefaultPlist()
  persistent pl;
  if ~exist('pl', 'var') || isempty(pl)
    pl = buildplist();
  end
  plout = pl;
end

function pl = buildplist()
  
  pl = plist();
  
  % Value
  p = param({'value', ['The value(s) to remove. Multiple values can be input in a vector.<br>' ...
    'Accepted values are:<ul>' ...
    '<li>NaN</li>' ...
    '<li>Inf</li>' ...
    '<li>Numbers</li></ul>']}, paramValue.EMPTY_DOUBLE);
  pl.append(p);
  
  % Vertices
  p = param({'axis', 'The axis to check on.'}, ...
    {2, {'x', 'y'}, paramValue.SINGLE});
  pl.append(p);
  
  % Method
  p = param({'method', 'The operation to perform on the values curresponding to NaN.'}, ...
    {1, {'remove', 'interp'}, paramValue.SINGLE});
  pl.append(p);
  
  % Interpolation
  pli = ao.getInfo('interp').plists;
  p = setKey(pli.params(pli.getIndexForKey('method')), 'interpolation');
  pl.append(p);
end
