function get_domain_tile_GRID(domain_dims,tileSize,ix,iy,iz,dirgridin,dirgridout);
%------------
%function get_domain_tile_GRID(domain_dims,tileSize,ix,iy,iz,dirgridin,dirgridout);
%
%Read the full domain GRID, divide into tiles and produce binary files, one per tile

%Input:
%	domain_dims	[nx ny nz]
%	tileSize	[ntilex ntiley]
%       ix,iy,iz        indices, e.g., for the Arctic region within a larger domain
%	dirgridin	Directory (full path) where the model GRID lives 
%	dirgridout	Directory where tiled GRID will be written 
%                       (a directory, e.g., /.../GRID_90x90/'] will be created
%
%The tiled grid will be written to a directory named, e.g., GRID_90x90
%
% written by Victor Ocana 2019
% modified by An Nguyen Jul 2022
%------------

%Directories and dimensions
%=====================================================================
nx=domain_dims(1);
nz=1; if(length(domain_dims)==3); nz=domain_dims(3);end;
ny=domain_dims(2);
nfx=[nx nx];
nfy=[nx nx];

ntilex=tileSize(1);	
ntiley=tileSize(2);
ntile=nx*ny/ntilex/ntiley;

%Set output directory	%------------------------------------------------------------------
if(~exist(dirgridout));
   mkdir(dirgridout);
else;
   disp(['The directory ' dirgridout ...
         ' already exists. If Continue = Y or Return Key, it will be overwritten']);
   prompt = 'Continue? Y/N [Y]: ';
   str = input(prompt,'s');
   if isempty(str);
      str = 'Y';
   end;
   if(~strcmp(str,'Y')); error('Script interrupted');end;
end;

%Summary of the parameters for this routine
fprintf('Reading GRID from: %s\n',dirgridin);
fprintf('Writing GRID to  : %s\n',dirgridout);
fprintf('Tile size: %2d x %2d x %2d\n',ntilex,ntiley,nz);

%Get list of tiles with wet points
%=====================================================================
meta=read_meta('hFacC.meta',dirgridin);	
%%sometimes the meta is not storing the correct size, here we make correction:
nx0=domain_dims(1);ny0=meta.dimList(1)*meta.dimList(4)/nx0;
mskC=readbin([dirgridin 'hFacC.data'],[nx0 ny0],1,...
             ['real*' num2str(str2num(meta.dataprec(end-1:end))/8)]);
mskC=mskC(ix,iy);mskC(find(mskC(:)~=0))=1;
[tiles] = domain2tiles_v2([],domain_dims,tileSize,mskC);

ntile_wet = tiles.wet;
fprintf('Number of wet tiles: %2d\n',ntile_wet);
fprintf('\n');

fsave=[dirgridout 'list_tile.txt'];  
fid=fopen(fsave,'w');fprintf(fid,'%3.0f %3.0f\n',[tiles.list]');fclose(fid);

%Produce the wet tiles for the GRID
%first, determine the true size, as sometimes the meta is storing incorrect info:
meta=read_meta(['hFacC.meta'],dirgridin); 
nx0=domain_dims(1);
ny0=meta.dimList(1)*meta.dimList(4)/nx0;
nz0=meta.dimList(7);
%=====================================================================

vvar={'XC','YC','XG','YG','DXC','DYC','DXG','DYG','RAC','RAZ','RAS','RAW','AngleCS','AngleSN',...
     'Depth','hFacC','hFacW','hFacS','maskInC','maskInW','maskInS','maskCtrlC','maskCtrlS','maskCtrlW'};

for ivar=1:size(vvar,2);
  if(exist([dirgridin vvar{ivar} '.data']));
    meta=read_meta([vvar{ivar} '.meta'],dirgridin); 
    nprec = str2num(meta.dataprec(end-1:end))/8;
    precIn=['real*' num2str(nprec)]; 
    a=rdmds([dirgridin vvar{ivar}]);sz0=size(a);if(length(sz0)==2);sz0=[sz0 1];end;
    a=reshape(a,nx0,ny0,sz0(3));sz0=size(a);if(length(sz0)==2);sz0=[sz0 1];end;

%extract using indices
    a=a(ix,iy,:);if(sz0(3)>1);a=a(:,:,iz);end;
    if(sz0(3)>length(iz));sz0(3)=length(iz);end;
    [field_tiles] = field2tiles_v2(a,tiles.index,tileSize);
    for jtile=1:ntile_wet;
      fout=[dirgridout vvar{ivar} '.' sprintf('%4.4i',jtile) '.data'];
      writebin(fout,field_tiles{jtile},1,precIn);
    end;

    %Write .meta file
    metaFile=[dirgridout vvar{ivar} '_' num2str(ntilex) 'x' num2str(ntiley) '.meta'];
    write_meta(metaFile,[ntilex ntiley sz0(3)],precIn);
    fprintf(' %s ',vvar{ivar});
  else;
    fprintf('%s not exist, skip\n',[vvar{ivar} '.data']);
  end;
end;%ivar
fprintf('\n');

%%%Copy the 1D variables from the original GRID
%============================================
var1D={'RC','RF','DRC','DRF'};
fprintf('1D files from %s \n', dirgridin);
for ivar=1:size(var1D,2);
  if(exist([dirgridin var1D{ivar} '.data']));
   meta=read_meta([var1D{ivar} '.meta'],dirgridin);
   nprec = str2num(meta.dataprec(end-1:end))/8;
   precIn=['real*' num2str(nprec)]; 
   a=squeeze(rdmds([dirgridin var1D{ivar}]));
   metaFile=[dirgridout var1D{ivar} '.meta'];
   fout    =[dirgridout var1D{ivar} '.data'];
   if(meta.dimList(7)==nz0);
     a=a(iz(1):iz(end));
     write_meta(metaFile,[1 1 length(iz)],precIn);
   elseif(meta.dimList(7)==(nz0+1));;
     a=a(iz(1):iz(end)+1);
     write_meta(metaFile,[1 1 length(iz)+1],precIn);
   end;
   writebin(fout,a,1,precIn);
  else;
   fprintf('%s ',var1D{ivar});fprintf(' missing, skip\n');
  end;
  fprintf(' %s ',var1D{ivar});
end;    
fprintf('\n');

