% PLUS implements addition operator for cdata objects.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DESCRIPTION: PLUS implements addition operator for two cdata objects.
%
% CALL:        a = d1+d2
%              a = plus(d1,d2);
%
% <a href="matlab:utils.helper.displayMethodInfo('cdata', 'plus')">Parameters Description</a>
%
% VERSION:     $Id: plus.m,v 1.3 2011/04/08 08:56:34 hewitson Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = plus(varargin)
  
  % get two data objects
  d1 = copy(varargin{1}, nargout);
  d2 = copy(varargin{2}, nargout);
  
  % check units
  d1.yunits.simplify();
  d2.yunits.simplify();
  
  if ~isempty(d1.yunits.strs) && ~isempty(d2.yunits.strs) && d1.yunits ~= d2.yunits
    error('### When adding two data objects, the yunits must be the same');
  end
  
  % add the data
  dout = applyoperator(d1,d2,'plus');
  
  % handle units: since both are the same, we take the first non-empty unit
  if isempty(d1.yunits.strs)
    dout.yunits = d2.yunits;
  else
    dout.yunits = d1.yunits;
  end
  
  % handle errors
  err = @(err1, err2) sqrt(err1 .^2 + err2.^2);
  if ~isempty(d1.dy) || ~isempty(d2.dy)    
    if isempty(d1.dy)
      d1.dy = zeros(size(d2.dy));
    end
    if isempty(d2.dy)
      d2.dy = zeros(size(d1.dy));
    end    
    dout.dy = err(d1.dy, d2.dy);
  else
    dout.dy = [];
  end

  
  % Single output
  varargout{1} = dout;
  
end

