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

function varargout = plus(varargin)
  
  % get two data objects
  d1 = copy(varargin{1}, nargout);
  d2 = copy(varargin{2}, nargout);
  
  % check units
  d1.zunits.simplify();
  d2.zunits.simplify();
  d1.yunits.simplify();
  d2.yunits.simplify();
  d1.xunits.simplify();
  d2.xunits.simplify();
  
  if ~isempty(d1.zunits.strs) && ~isempty(d2.zunits.strs) && d1.zunits ~= d2.zunits
    error('### When adding two data objects, the zunits must be the same');
  end
  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
  if ~isempty(d1.xunits.strs) && ~isempty(d2.xunits.strs) && d1.xunits ~= d2.xunits
    error('### When adding two data objects, the xunits 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.zunits.strs)
    dout.zunits = d2.zunits;
  else
    dout.zunits = d1.zunits;
  end
  if isempty(d1.yunits.strs)
    dout.yunits = d2.yunits;
  else
    dout.yunits = d1.yunits;
  end
  if isempty(d1.xunits.strs)
    dout.xunits = d2.xunits;
  else
    dout.xunits = d1.xunits;
  end
  
  % handle errors
  err = @(err1, err2) sqrt(err1 .^2 + err2.^2);
  if ~isempty(d1.dz) || ~isempty(d2.dz)    
    if isempty(d1.dz)
      d1.dz = zeros(size(d2.dz));
    end
    if isempty(d2.dz)
      d2.dz = zeros(size(d1.dz));
    end    
    dout.dz = err(d1.dz, d2.dz);
  else
    dout.dz = [];
  end
  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
  if ~isempty(d1.dx) || ~isempty(d2.dx)    
    if isempty(d1.dx)
      d1.dx = zeros(size(d2.dx));
    end
    if isempty(d2.dx)
      d2.dx = zeros(size(d1.dx));
    end    
    dout.dx = err(d1.dx, d2.dx);
  else
    dout.dx = [];
  end

  
  % Single output
  varargout{1} = dout;
  
end

