%REBIN Rebinning of an image 
%
% SYNOPSIS:
%  out = rebin(in, binning)
%
% PARAMETERS:
%  in:  input image
%  binning: integer numbers (array) that divides the image without remainder  
%
% SEE ALSO:
%  resample, subsample

% (C) Copyright 1999-2007     Quantitative Imaging Group
%     All rights reserved     Department of Imaging Science and Technology
%                             Delft University of Technology
%                             Lorentzweg 1
%                             2628 CJ Delft
%                             The Netherlands
%
% Bernd Rieger, Feb 2007.

function out = rebin(varargin)
d = struct('menu','Manipulation',...
   'display','Rebinning',...
   'inparams',struct('name', {'in','bin'},...
         'description',{'Input image','Binning'},...
         'type',       {'image','array'},...
         'dim_check',  {0,1},...
         'range_check',{[],'N+'},...
         'required',   {1,0},...
         'default',    {'a',2}...
        ),...
   'outparams',struct('name',{'out'},...
                      'description',{'Output image'},...
                      'type',{'image'}...
                      )...
       );
if nargin == 1
   s = varargin{1};
   if ischar(s) & strcmp(s,'DIP_GetParamList')
      out = d;
      return
   end
end
try
   [in,bin] = getparams(d,varargin{:});
catch
   if ~isempty(paramerror)
      error(paramerror)
   else
      error(firsterr)
   end
end

N = ndims(in);
szI = size(in);
if any(rem(szI,bin))
   error('Binning must be divider of all image dimensions.');
end

%separable in x,y,.. loop over dimensions
s1 = 'out = tmp('; s2 = '0:bin(ii):end'; s3 = ');';
s4 = 'out = out + tmp('; s5 = 'jj:bin(ii):end'; s6 = ');';

tmp = in;
for ii=1:N
   %out = tmp(0:bin(ii):end,:); 
   s = make_evalstring(s1,s2,ii,N);
   eval(s);
   for jj=1:bin(ii)-1
      %out = out + tmp(jj:bin(ii):end,:); %add other pixel that dimension
      s = make_evalstring(s4,s5,ii,N);
      eval(s);
   end
   tmp = out;
end

%help function to extract one column with correct binning out of an image
function out = make_evalstring(s1,s2,ii,N)
out = s1;
for jj=1:N
   if jj==ii
      out = [out s2 ','];
   else
      out = [out ':,'];
   end
end
out(end)=[];
out = [out ');'];
