% FIND particular samples that satisfy the input query and return a new AO.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DESCRIPTION: FIND particular samples that satisfy the input query and return a new AO.
%
% CALL:        b = find(a, 'x > 10 & x < 100')
%              b = find(a, plist)
%
% PROCINFO:    The selected indexes are stored in the procinfo of the
%              output AO. You can get this indexes with:
%              b.procinfo.find('index')
%
% <a href="matlab:utils.helper.displayMethodInfo('ao', 'find')">Parameters Description</a>
%
% VERSION:     $Id: find.m,v 1.47 2011/10/05 12:04:25 ingo Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = find(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, pl_invars, rest] = 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());

  % initialise queries
  queries = '';
  % extract any from inputs
  for j=1:numel(rest)
    if ischar(rest{j})
      queries = [queries ' & ' rest{j}];
    end
  end

  % Get sample selection from plist
  queries = [queries ' & ' find(pl, 'query')];

  % We may have pre or trailing '&' now
  queries = strtrim(queries);
  if queries(1) == '&'
    queries = queries(2:end);
  end
  if queries(end) == '&'
    queries = queries(1:end-1);
  end
  
  % store for history
  queries = strtrim(queries);
  pl.pset('query', queries);

  % Loop over input AOs
  for j=1:numel(bs)
    
    % The user uses the variables x and y so we need
    % to put them in the workspace.
    clear x
    if ~isa(bs(j).data, 'cdata')
      x = bs(j).data.getX;
    end
    y = bs(j).data.getY;

    idx = [];
    cmd = sprintf('idx = find(%s);', queries);
    try
      eval(cmd);
    catch ME
      error('%s\n\n### please use x or y for the queries.',ME.message);
    end

    % set data
    if ~isa(bs(j).data, 'cdata')
      %%% tsdata, fsdata, xydata
      bs(j).data.setXY(x(idx), y(idx));
      
      % Set 'dx' and 'dy' and 'enbw'
      if numel(bs(j).data.dx) > 1
        bs(j).data.setDx(bs(j).data.dx(idx));
      end
      if numel(bs(j).data.dy) > 1
        bs(j).data.setDy(bs(j).data.dy(idx));
      end
      if isprop(bs(j).data, 'enbw')
        if numel(bs(j).data.enbw) > 1
          bs(j).data.setEnbw(bs(j).data.enbw(idx));
        end
      end
      
    else
      %%% cdata
      bs(j).data.setY(y(idx));
      if numel(bs(j).data.dy) > 1
        bs(j).data.setY(bs(j).data.dy(idx));
      end
    end

    %%% Set special properties for 'tsdata' objects
    if isa(bs(j).data, 'tsdata')
      % Set the toffset to zero because the x-vector includes the toffset
      bs(j).data.setToffset(0);
      
      % Check fs and see if is x evenly sampled
      [fs,t0,fitted] = tsdata.fitfs(x(idx));
      if fitted
        bs(j).data.setFs(fs);
        bs(j).data.fixNsecs();
      else
        % drop x
        bs(j).data.collapseX;
      end
    end
    
    % set name
    bs(j).name = sprintf('find(%s)', ao_invars{j});
    % add history
    bs(j).addHistory(getInfo('None'), pl, ao_invars(j), bs(j).hist);
    bs(j).procinfo = plist('index', idx);
  end

  % Set output
  if nargout == numel(bs)
    % List of outputs
    for ii = 1:numel(bs)
      varargout{ii} = bs(ii);
    end
  else
    % Single output
    varargout{1} = bs;
  end
end

%--------------------------------------------------------------------------
% Get Info Object
%--------------------------------------------------------------------------
function ii = getInfo(varargin)
  if nargin == 1 && strcmpi(varargin{1}, 'None')
    sets = {};
    pls  = [];
  else
    sets = {'Default'};
    pls  = getDefaultPlist;
  end
  % Build info object
  ii = minfo(mfilename, 'ao', 'ltpda', utils.const.categories.helper, '$Id: find.m,v 1.47 2011/10/05 12:04:25 ingo Exp $', sets, pls);
end

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

function pl = buildplist()
  pl = plist({'query', 'A search string specifying a query on ''x'' or ''y'' (or ''vals'' for cdata). <br>For example, <tt>''x>3 & x<5''</tt>'},  paramValue.EMPTY_STRING);
end


