function [grid_diag]=set_grid(info,tileName,gridDir);
%This routine is copied/adapted from gcmfaces_IO/process2nctiles.m
%
%Extract GRID information to be written in diag output nc files
%
%Input:
%       info            a matlab structure with some information on
%                       the field with which we need grid for
%       tileName        The tile being processed
%       gridDir         Directory with ASTE grid in binary tile form
%
%Output:
%       grid_diag       structure with the relevant grid variables needed for nc output
%                       will be different for 2D and 3D field
%e.g.:
%>> grid_diag
%grid_diag = 
%  struct with fields:
%
%    lon: [90×90 double]
%    lat: [90×90 double]
%    msk: [90×90×50 double]
%    RAC: [90×90 double]
%    dep: [1×1×50 double]
%     dz: [1×1×50 double]

names = {'lon','lat','msk','RAC'};
%switch for non-tracer point values
if strcmp(info.loc_h,'C');
    namesg ={'XC','YC','maskCtrlC','RAC'};
elseif strcmp(info.loc_h,'W');
    namesg ={'XG','YC','maskCtrlW','RAC'};
elseif strcmp(info.loc_h,'S');
    namesg ={'XC','YG','maskCtrlS','RAC'};
end;

for ii=1:length(names);
   fileN = [gridDir namesg{ii} '.' tileName '.data'];
   temp = dir([gridDir namesg{ii} '*.meta']);   
   temp1 = read_meta(temp.name,gridDir);
   nprec=str2num(temp1.dataprec(end-1:end))/8; prec=['real*' num2str(nprec)];
   for idim=1:temp1.nDims; 
      dims(idim)=temp1.dimList(1+3*(idim-1));
   end;
   if (temp1.nDims==3 && info.nr==1); 
      dims(temp1.nDims) = info.nr;
   end;
   grid_diag.(names{ii})=readbin(fileN,dims,1,prec);
   clear temp temp1 nprec prec dims;
end;

%vertical grid (for 3D diags)
clear names namesg;
if info.nr~=1;
   names = {'dep','dz'};
   if strcmp(info.loc_z,'M');
      namesg= {'RC','DRF'};
   elseif strcmp(info.loc_z,'L');
      namesg= {'RF','DRC'};
   elseif strcmp(info.loc_z,'U');
      namesg= {'RF','DRC'};
   end;
   for ii=1:length(names);
      fileN = [gridDir namesg{ii}  '.data'];
      temp = dir([gridDir namesg{ii} '*.meta']);   
      temp1 = read_meta(temp.name,gridDir);
      nprec=str2num(temp1.dataprec(end-1:end))/8; prec=['real*' num2str(nprec)];
      dims = temp1.dimList(7);
      eval(['grid_diag.' names{ii} '=readbin(fileN,dims,1,prec);']);
      clear temp temp1 nprec prec;
   end;
   if strcmp(info.loc_z,'M');
       %grid_diag.dep=-grid_diag.dep;
       grid_diag.dep=abs(grid_diag.dep);
       grid_diag.dz=grid_diag.dz;
   elseif strcmp(info.loc_z,'L');
       %grid_diag.dep=-grid_diag.dep(2:end);
       grid_diag.dep=abs(grid_diag.dep(2:end));
       grid_diag.dz=grid_diag.dz(2:end);
   elseif strcmp(info.loc_z,'U');
       %grid_diag.dep=-grid_diag.dep(1:end-1);
       grid_diag.dep=abs(grid_diag.dep(1:end-1));
       grid_diag.dz=grid_diag.dz(1:end-1);
   else;
       error('unknown vertical grid');
   end;
   grid_diag.dep = reshape(grid_diag.dep,[1 1 info.nr]);
   grid_diag.dz  = reshape(grid_diag.dz,[1 1 info.nr]);
end;



