function [field] = tiles2field(field_tiles,indices,fieldSize);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Given a set of 2D or 3D tiles and their indices from ASTE compact form, reconstruct
%a compact field with the tiles in their right place
%
%All tiles are assumed to be of the same size
%
%Input:
%       field_tiles     a set of 2D or 3D tiles as a cell structure (or vector if only one tile) with one cell per tile
%       indices         cell structure or (vector if only one tile) with the indices, from the compact format, for each tile
%			This can (should) be the output of script ASTE2tiles(field,aste_dims,tileSize,dirgridin,lat_cutoff);
%	fieldSize	Size of the ASTE compact field, e.g. [270 1350 50]
%
%Output:
%       field		A field with the dimensions fieldSize, in ASTE compact foprmat, with the data values of the locations
%			of the provided tiles and zeros elsewhere 	
%
% V.Ocana 14.Nov.2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

field=[];

%Dimensions
ndims=length(fieldSize);

dfieldx = fieldSize(1);
dfieldy = fieldSize(2);
dfieldz = 1;
if(ndims==3);
   if(iscell(field_tiles));
      dfieldz = size(field_tiles{1},3);
   elseif(isnumeric(field_tiles));
      dfieldz = size(field_tiles,3);
   end;
end;

%Check input
if(iscell(field_tiles));
   ntiles=length(field_tiles);
   nindex=length(indices);
   szt=size(field_tiles{1});
   szi=length(indices{1});
elseif(isnumeric(field_tiles));
   ntiles=1;
   nindex=1;
   szt=size(field_tiles);
   szi=length(indices);
end;

if(ntiles~=nindex);
   disp('tiles2field ERROR: There must be a set of indices for each tile ');
   return;
end;

if((szt(1)*szt(2))~=szi);
   disp(['field2tiles ERROR: Number of points in indices= ' num2str(szi) ' is different from tile size dtilex*dtiley=' num2str(szt(1)*szt(2))]);
   return;
end;

%Store tiles in field
field = zeros(dfieldx,dfieldy,dfieldz);

for ii=1:ntiles;
   if(iscell(indices)); tmp=indices{ii}; else; tmp=indices;end; 
   if(iscell(field_tiles)); tmpt=field_tiles{ii}; else; tmpt=field_tiles;end; 
   for iz=1:dfieldz;
      tmpf=field(:,:,iz);
      tmpt1=reshape(tmpt(:,:,iz),szi,1);
      tmpf(tmp) = tmpt1; 
      field(:,:,iz) = tmpf;
      clear tmpf tmp1;
   end;
   clear tmp;
end;



