## Copyright (C) 2015 Carnë Draug <carandraug@octave.org>
##
## 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{quant}, @var{idx}] =} imquantize (@var{img}, @var{levels})
## @deftypefnx {Function File} {[@dots{}] =} imquantize (@var{img}, @var{levels}, @var{values})
## Quantize image.
##
## @seealso{gray2ind, ind2gray, ind2rgb, intlut, label2rgb, rgb2ind}
## @end deftypefn

function [quant, idx] = imquantize (img, levels, values)
  if (nargin < 2 || nargin > 3)
    print_usage ();
  elseif (! isimage (img))
    error ("imquantize: IMG must be an image - numeric array with real values");
  endif

  validateattributes (levels, {"numeric"}, {"nondecreasing", "vector"});
  idx = lookup ([-Inf vec(levels, 2) Inf], img, "r");

  if (nargin < 3)
    quant = idx;
  else
    validateattributes (values, {"numeric"}, {"vector", "numel", numel(levels)+1});
    quant = values(idx);
  endif

endfunction

%!test
%! img = [1:10; 11:20; 21:30; 31:40; 41:50; 51:60; 61:70];
%! [img2,img3] = imquantize(img,[5 15 25 30 40 60],[0 1 5 10 20 30 15]);
%! assert(img2(1,1) == 0)
%! assert(img2(1,6) == 1)
%! assert(img2(2,5) == 5)
%! assert(img2(6,10) == 15)
%! assert(img2(7,1) == 15)
%! assert(img3(1,1) == 1)
%! assert(img3(1,6) == 2)
%! assert(img3(2,5) == 3)
%! assert(img3(6,10) == 7)
%! assert(img3(7,1) == 7)

%!test
%! img = [-inf 0 10000000; -100000 -3 1/1000000; 5 5 10];
%! img2 = imquantize(img, 5);
%! assert(img2(1,1) == 1)
%! assert(img2(1,2) == 1)
%! assert(img2(1,3) == 2)
%! assert(img2(2,1) == 1)
