% DSMEAN performs a simple downsampling by taking the mean of every N samples.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DESCRIPTION: DSMEAN performs a simple downsampling by taking the mean of
%              every N samples. The downsample factor (N) is taken as
%              round(fs/fsout). The original vector is then truncated to a
%              integer number of segments of length N. It is the reshaped
%              to N x length(y)/N. Then the mean is taken.
%
% CALL:        b = dsmean(a, pl)
%
% <a href="matlab:utils.helper.displayMethodInfo('ao', 'dsmean')">Parameters Description</a>
%
% VERSION:     $Id: dsmean.m,v 1.23 2011/05/11 08:42:19 mauro Exp $
%
% HISTORY:     20-04-08 M Hewitson
%                 Creation
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = dsmean(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
  [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);

  % Extract necessary parameters
  fsout = find(pl, 'fsout');

  % Loop over input AOs
  for jj = 1:numel(bs)
    if ~isa(bs(jj).data, 'tsdata')
      warning('!!! Can only downsample time-series (tsdata) objects. Skipping AO %s', ao_invars{j});
    else
      % downsample factor
      dsf = round(bs(jj).data.fs/fsout);
      if dsf < 1
        error('### I can''t downsample - the sample rate is already lower than the requested.');
      elseif dsf>1
        % Do Y data
        n = floor(length(bs(jj).data.y) / dsf);
        y = bs(jj).data.y(1:n*dsf);
        % reshape and take mean
        bs(jj).data.setY(mean(reshape(y, dsf, length(y)/dsf)));
        
        % If we have an x we should resample it
        if ~isempty(bs(jj).data.x)
          x = bs(jj).data.x(1:n*dsf);
          % reshape and take mean
          bs(jj).data.setX(mean(reshape(x, dsf, length(x)/dsf)));
        else
          % otherwise we need to adjust t0
          bs(jj).data.setT0(bs(jj).data.t0 + dsf/(2*bs(jj).data.fs));
        end
      end
      % Build output AO
      bs(jj).data.setFs(fsout);
      bs(jj).name = sprintf('dsmean(%s)', ao_invars{jj});
      % Add history
      bs(jj).addHistory(getInfo('None'), pl, ao_invars(jj), bs(jj).hist);
      % Clear the errors since they don't make sense anymore
      clearErrors(bs(jj));
    end
  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: dsmean.m,v 1.23 2011/05/11 08:42:19 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({'fsout', 'The output sample rate.'}, {1, {10}, paramValue.OPTIONAL});
end


