function [field_tiles] = field2tiles_v2(field,indices,tileSize);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%function [field_tiles] = field2tiles_v2(field,indices,tileSize);
%
%Given a 2D or 3D field, extract the points from it specified in indices and 
%reshape to a field with dimensions given in tileSize
%
%Input:
%       field           a 2D or 3D  data field  
%       tileSize        [dtilex dtiley] (number of grid points in each tile side)
%       indices         cell structure or vector with the indices, form the compact format, for each tile
%			This can (should) be the output of script ASTE2tiles(field,aste_dims,tileSize,dirgridin,lat_cutoff);
%Output:
%       field_tiles	cell structure with data in tiles, field_tiles{tilenumber} has dimensions [dtilex dtiley]
%
% Written by Victor Ocana 2019
% Modified by An Nguyen Jul 2022
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

field_tiles =[];

%Dimensions
dtilex = tileSize(1);
dtiley = tileSize(2);
sz = size(field); if(length(sz)==2);sz(3)=1;end;
st = dtilex*dtiley;

%Check input
if(iscell(indices));
   ntiles=length(indices);
   nindx = size(indices{1});
elseif(isnumeric(indices));
   ntiles=1;
   nindx = size(indices);
else;
   str1=['field2tiles_v2 ERROR: Indices must be a vector of indices '];
   str2=['or a cell structure with indices for each tile'];
   disp([str1 str2]);
   return;
end; 

if(nindx~=st);
   str1=['field2tiles_v2 ERROR: Number of points in indices= ' num2str(nindx)];
   str2=[' is different from tile size dtilex*dtiley=' num2str(st)];
   disp([str1 str2]);
   return;
end;

%Store field in tiles cell structure
for ii=1:ntiles;
   if(iscell(indices)); tmp=indices{ii}; else; tmp=indices;end; 
   if(~isempty(field));
      for iz=1:sz(3);
         ftmp = field(:,:,iz);
         ftmp1= ftmp(tmp); ftmp1=reshape(ftmp1,dtilex,dtiley);
         ftmp2(:,:,iz) = ftmp1;
      end;
      field_tiles{ii} = ftmp2;
      clear ftmp ftmp1 ftmp2;
   end;
   clear tmp;
end;


return
