%DETILE   Splits and image in subimages
%  Revertes the function TILE.
%
% SYNOPSIS:
%  out = detile(in, array)
%
% PARAMETERS:
%  out:   dip_image_array of size array
%  array: 2D array. Number of subimages into which in is broken up per dimension.
%
% DEFAULTS:
%  array = 2;
%
% EXAMPLE:
%  a=readim;
%  g=gradient(a);
%  G=g*g';
%  G1=tile(G)
%  detile(G1,[4 2])
%
% SEE ALSO:
%   tile, arrangeslices

% (C) Copyright 1999-2007               Pattern Recognition Group
%     All rights reserved               Faculty of Applied Physics
%                                       Delft University of Technology
%                                       Lorentzweg 1
%                                       2628 CJ Delft
%                                       The Netherlands
%
% Bernd Rieger, June 2007

function out = detile(in, ts)
if nargin == 1
   if ischar(in) & strcmp(in,'DIP_GetParamList')
      out = struct('menu','none');
      return
   end
end
if nargin <2
   ts=2;
end
if ndims(in)>3 | ~isa(in,'dip_image')
   error('Input image must be a 2D or 3D dip_image.');
end
if length(ts)>2
   error('Array to detile the image must be 2D.');
end
if length(ts)==1
    ts = [ts ts];
end
sz=imsize(in);
if any(mod(sz(1:2),ts))
    error('The array must divide the image size.');
end
dd = sz(1:2)./[ts];

out = newimar(ts);
stx = 0;
for ii=1:ts(1)
    edx = stx+dd(1)-1;
    sty = 0;
    for jj=1:ts(2)
        edy = sty+dd(2)-1;
        %fprintf('%d:%d %d:%d\n',stx,edx,sty,edy);
        if ndims(in)==2
            out{ii,jj} = in(stx:edx, sty:edy);
        else
                out{ii,jj} = in(stx:edx, sty:edy,:);
        end
        sty = edy+1;
    end
    stx = edx+1;
end
