function [grid_tiles] = nctiles_grid(varName,dirGridnc,tile_list,tiles,flag_aste); 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Read specified netCDF tiles from disk, given selected levels and time steps, and return a compact format aste field
%This script requires the output of aste2tiles, a structure named tiles
%
%Input:
%	varName		Name of the grid variables, e.g. varName={'XC','YC','DXG,'DYG'} or varName={''} to load ALL the grid
%	dirGridnc	Directory where GRID*.nc tiles live (full path)
%	tile_list	Vector with a list of the tiles (tile number) being extracted, e.g. [8:16] selects the tiles that make up face 3 of ASTE
%	tiles		Structure with fields tiles.tot,tiles.wet,...,tiles.index 
%			This is the output of aste2tiles.m
%       flag_aste       0 = leave outputs as individual tiles, save memory if want to analyze only a few tiles
%                       1 = put into aste compact format [270 1350 [1 or nz]] , for use if analyze the entire ASTE domain
%
%Output:
%	grid_tiles	tile or compact format fields for individual tiles with dimensions dtilex x dtiley (x nz)
%                       if varName={'DXG','DYG','hFacC'} for example, the output will be
%                       grid_tiles.DXG   , size dtilex x dtiley
%                       grid_tiles.DYG   , size dtilex x dtiley
%                       grid_tiles.hFacC , size dtilex x dtiley x 50
%
% atn 01.nov.2020 copy from nctiles_single, output is for a individual tiles instead of put full aste compact size
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Get info from meta file
fList  = dir([dirGridnc 'GRID*.nc']);
nc_info=read_nc_info(fList(1).name,dirGridnc);

%nc_info = 
%          file: '/scratch2/atnguyen/aste_270x450x180/OFFICIAL_ASTE_R1_Sep2019/nctiles_grid/GRID.0001.nc'
%         ndims: 4
%       dimName: {'itxt'  'i1'  'i2'  'i3'}
%         dimID: [0 1 2 3]
%       dimSize: [30 50 90 90]
%         nvars: 23
%       varName: {1×23 cell}
%         varID: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22]
%       varSize: {1×23 cell}
%        ngatts: 10
%     gattsName: {1×10 cell}
%    unlimdimid: -1
%nc_info.varName 1×23 cell array
%    {'i1'}    {'i2'}    {'i3'}    {'hFacC'}    {'hFacW'}    {'hFacS'}    {'XC'}    {'YC'}    {'XG'}    {'YG'}    {'RAC'}    {'RAZ'}    {'DXC'}	%1--13
%    {'DYC'}    {'DXG'}    {'DYG'}    {'Depth'}    {'AngleCS'}    {'AngleSN'}    {'RC'}    {'RF'}    {'DRC'}    {'DRF'}				%14--23
%nc_info.varSize
%  1×23 cell array
%  Columns 1 through 10
%    {[50]} {[90]} {[90]} {1×3 double} {1×3 double} {1×3 double} {1×2 double} {1×2 double} {1×2 double} {1×2 double} {1×2 double} {1×2 double} {1×2 double}  %1--13
%    {1×2 double} {1×2 double} {1×2 double} {1×2 double} {1×2 double} {1×2 double} {[50]} {[50]} {[50]} {[50]}						    %14--23

%set default, if varName is empty, load all 23 fields of GRID in
if(~isempty(varName{1}));
  Lvar=size(varName,2);
else;
  Lvar=23;
end;

%Set dimensions
nx = tiles.fsize(1);
ny = tiles.fsize(2);
dtilex = tiles.tsize(1);
dtiley = tiles.tsize(2);
%fieldSize=[nx ny nz];

nz_max   = nc_info.dimSize(2); 
ntiles_max = length(fList);
ntiles  = length(tile_list); 

%loop through once to check size
for ivar=1:Lvar;
  varindex = find(ismember(nc_info.varName, varName{ivar}));
  varid = nc_info.varID(varindex);

%Check dimensions
%Check that tiles, nz requested are available
  if(length(nc_info.varSize{varindex})>=2);
    if(dtilex~=nc_info.varSize{varindex}(1) || dtiley~=nc_info.varSize{varindex}(2));
       fprintf('nctiles_grid ERROR: Dimensions from tiles.tsize %dx%d are different from nc_info.varSize %dx%d',...
                dtilex,dtiley,nc_info.varSize{varindex}(1),nc_info.varSize{varindex}(2));
       return;
    end;
  end;

  if(ntiles_max~=tiles.wet)
     disp(['nctiles_grid WARNING: number of tiles in directory ' num2str(ntiles_max) ' is different from number of tiles from ASTE2tiles = ' num2str(tiles.wet)]);
  end;
  if(length(tile_list)>tiles.wet);
     disp(['nctiles_grid ERROR: Number of wet tiles in dataDir is ' num2str(tiles.wet) ' but you are requesting ' num2str(length(tile_list)) ' tiles']); 
     return;
  end;
  if(max(tile_list)>tiles.wet);
     disp(['nctiles_grid ERROR: Number of wet tiles in dataDir is ' num2str(tiles.wet) ' but you are requesting a tile number' num2str(max(tile_list))]); 
     return;
  end;
end;	%done first loop through all variables 

%Extract the data from tiles 
field_tiles=[];
for itile = 1:ntiles;
   tmp=[];
   tile_num = tile_list(itile);
   indices{itile} = tiles.index{tile_num};
   fName = ['GRID.' sprintf('%04d',tile_num) '.nc'];
   ncid = netcdf.open([dirGridnc fName],'NC_NOWRITE');
   for ivar=1:Lvar;
      varindex = find(ismember(nc_info.varName, varName{ivar}));
      varid = nc_info.varID(varindex);
      
      count = nc_info.varSize{varindex};
      start = 0.*count;
      tmp.(varName{ivar}) = netcdf.getVar(ncid,varid,start,count);
   end;
   field_tiles{itile} = tmp;
   netcdf.close(ncid);
   clear tmp;
end;

%now check if need to put into ASTE compact size 
grid_tiles=[];

if(flag_aste);
  for ivar=1:Lvar
    clear tmp fieldSize nz varindex 

    varindex = find(ismember(nc_info.varName, varName{ivar}));

    if(length(nc_info.varSize{varindex})==1);
      grid_tiles.(varName{ivar})=field_tiles{1}.(varName{ivar});
    else;
          if(length(nc_info.varSize{varindex})==2);nz=1;
      elseif(length(nc_info.varSize{varindex})==3);nz=nc_info.varSize{varindex}(3);
      end;

      fieldSize=[tiles.fsize(1) tiles.fsize(2) nz];

      for itile=1:ntiles
        tmp{itile}=field_tiles{itile}.(varName{ivar});
      end;

      grid_tiles.(varName{ivar}) = tiles2field(tmp,indices,fieldSize);
    end;%length(nc_info.varSize{varindex)>1

  end;
else;
  grid_tiles=field_tiles;
end;
