function varargout = ImMaths2(varargin)
% Opérations mathématiques entre 2 images de dimensions identiques
% Le résultat est de même nombre de bits que l'image1
% 
% INPUT:
% - image1 PxQ1
% - image2 PxQ2
% - valeur texte opération : '+' | '-' | '*' | '/' | '=' | 'moy' | 'min' | 'max'
%
% OUTPUT:
% - image PxQ1
%
% INFOS:
% - saturation des valeurs < 0 et > ValMax de image1
%
% Plugin for OpenIsaac
% version 1
% © 2011-2018 Alain Clément - Université d'Angers

%---------------------------------------------------------------------------------------------------

% Copyright 2007 - 2018 Université d'Angers - Author: Alain Clément
%
% 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 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, write to the Free
% Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

%---------------------------------------------------------------------------------------------------

% PLUGIN PARAMETERS
if (nargin == 1) && strcmp(varargin{1},'-f')
    % input
	varargout{1} = {'IMG','image1', ...
					'IMG','image2', ...
					'DATA','opération'};
    % output
	varargout{2} = {'IMG','image résultat'};
	return
end	

% INPUT
ObjIMG1 = varargin{1};
ObjIMG2 = varargin{2};
oper = IsaacDATA_get(varargin{3},'Val');

%---------------------------------------------------------------------------------------------------

if ~IsaacIMG_compare(ObjIMG1,ObjIMG2,'DimXYZ')
	error('images incompatibles')
end
% mat1 et mat2 en double avec des valeurs non nécessairement comprises entre 0 et 1 (pas des images)
mat1 = double(IsaacIMG_img2mat(ObjIMG1));
mat2 = double(IsaacIMG_img2mat(ObjIMG2));
clear ObjIMG2
switch oper
case '+'
	mat1 = mat1 + mat2;
case '-'
	mat1 = mat1 - mat2;
case '*'
	mat1 = mat1 .* mat2;
case '/'
	mat1 = mat1 ./ mat2;
case '='
	mat1 = mat2;
case 'moy'
	mat1 = (mat1 + mat2)/2;
case 'min'
	mat1 = min(mat1,mat2);
case 'max'
	mat1 = max(mat1,mat2);
otherwise
	error('opération invalide')
end
clear mat2
% gestion de la saturation
valmax = IsaacIMG_get(ObjIMG1,'ValMax');
mat1(mat1 < 0) = 0;
mat1(mat1 > valmax) = valmax;
% rétablissement du type Matlab
switch IsaacIMG_get(ObjIMG1,'BitClass');
case 1
	img = logical(mat1);
case 8
	img = uint8(mat1);
case 16
	img = uint16(mat1);
case 32
	img = single(mat1);
case 64
	img = double(mat1);
end
ObjIMG1 = IsaacIMG_mat2img(ObjIMG1,img);

%---------------------------------------------------------------------------------------------------

% OUTPUT
varargout{1} = ObjIMG1;
