##  Copyright (C) 2014  Daniel Kraft <d@domob.eu>
##  GNU Octave level-set package.
##
##  This program is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 3 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program.  If not, see <http://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn  {Function File} {@var{phi} =} ls_setxor (@var{phi1}, @var{phi2})
## 
## Calculate a level-set function for the set ``xor'' of the
## two domains given via @var{phi1} and @var{phi2}.  In other words,
## returned is a domain that contains all points that are in precisely
## @emph{one} of the sets but not in both.
##
## @seealso{ls_complement, ls_union, ls_intersect, ls_setdiff, setxor}
## @end deftypefn

function phi = ls_setxor (phi1, phi2)
  if (nargin () ~= 2)
    print_usage ();
  endif

  if (~all (size (phi1) == size (phi2)))
    error ("PHI1 and PHI2 must be of the same size");
  endif

  total = ls_union (phi1, phi2);
  both = ls_intersect (phi1, phi2);
  phi = ls_setdiff (total, both);
endfunction

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Tests.

% Test for error conditions.
%!error <Invalid call to>
%!  ls_setxor (1)
%!error <Invalid call to>
%!  ls_setxor (1, 2, 3)
%!error <PHI1 and PHI2 must be of the same size>
%!  ls_setxor (1, [1, 2])

% Basic test.
%!test
%!  assert (ls_equal (ls_setxor ([-1, -1, Inf], [1, -1, -Inf]), [-1, 1, -1]));

% 2D test with circles.
%!  n = 50;
%!  x = linspace (-10, 10, n);
%!  h = x(2) - x(1);
%!  [XX, YY] = meshgrid (x, x);
%!
%!  phi1 = XX.^2 + YY.^2 - 8^2;
%!  phi2 = XX.^2 + YY.^2 - 5^2;
%!
%!  assert (ls_equal (ls_setdiff (phi1, phi2), ls_setxor (phi1, phi2)));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Demo.

%!demo
%!  n = 100;
%!  x = linspace (-7, 7, n);
%!  [XX, YY] = meshgrid (x, x);
%!
%!  phi1 = (XX - 2).^2 + YY.^2 - 3^2;
%!  phi2 = (XX + 2).^2 + YY.^2 - 3^2;
%!  phi = ls_setxor (phi1, phi2);
%!
%!  figure ();
%!  subplot (1, 2, 1);
%!  hold ("on");
%!  contour (XX, YY, phi1, [0, 0], "k");
%!  contour (XX, YY, phi2, [0, 0], "k");
%!  hold ("off");
%!  axis ("equal");
%!
%!  subplot (1, 2, 2);
%!  hold ("on");
%!  imagesc (x, x, phi);
%!  set (gca (), "ydir", "normal");
%!  ls_sign_colourmap ();
%!  contour (XX, YY, phi, [0, 0], "k");
%!  hold ("off");
%!  axis ("equal");
