function []=convert_aste2nctiles_singlefield(tilein,info);
%function []=convert_aste2nctiles_singlefield(tilein,info);
% Read ASTE binary file already in tile form and write nc output in ECCO form
% Inputs:
%  tilein: output from aste2tiles(a,[nx ncut1 ncut2 50],[90 90],diringrid,26);
%  info  : structure of additional information about tilein
%      .varName   : e.g., 'logdiffkr'
%      .longName  : e.g., 'log 10 of diffkr'
%      .units     : e.g., 'log10(m2/s)'
%      .nprec     : 4 or 8 (integer)
%      .outDir    : dir where file will be written
%      .fnameroot : root name of the nc output file
%      .gridDir   : dir of tile grid in binary, e.g.,
%                  '/scratch/atnguyen/aste_270x450x180/GRID_noblank_13p75/';
%      .loc_h     : 'C' or 'S' or 'W'
%      .loc_z     : 'M' or 'U' or 'L'
%      .nr        : 50 or 1, should = tilein.fsize(3)
%% these  name[1d,2d3d] are now outputs of set_grid, not needed
%%%      .name2d3d  : {'XC','YC','maskCtrlC','RAC'} for 'C' or
%%%                 : {'XG','YC','maskCtrlW','RAC'} for 'W'  or
%%%                 : {'XC','YG','maskCtrlS','RAC'} for 'S'
%%%      .name1d    : {'RC','DRF'} for 'M' or {'RF','DRC'} for 'L' / 'U'
%
%
% NC files have:
%	4 dimensions: 
%		0 itxt  30
%		1 i1  vertical levels
%		2 i2  y length
%		3 i3  x length
%
%	10 Variables (dims):
%		0 i1  		i1            (dep)
%		1 i2  		i2            (y)
%		2 i3  		i3            (x)
%		3 varName  	i3 i2 i1
%		4 lon  		i3 i2
%		5 lat  		i3 i2
%		6 dep  		i1
%		7 land  	i3 i2 i1
%		8 area  	i3 i2
%		9 thic  	i1
%		

%Directories, files		+---------------------------------------------------------- 

if(exist(info.outDir)==0);error('outDir missing, need to make');end;

%Get information about variable +---------------------------------------------------------- 
varName=info.varName;

%Set tile dimensions	+---------------------------------------------------------- 
dtilex = tilein.tsize(1);
dtiley = tilein.tsize(2);
nz =1 ; if(tilein.fsize(3)>2); nz = tilein.fsize(3);end;
if(info.nr~=nz);
  fprintf('info.nr= %i is not equal nz= %i, now set to nz\n',[info.nr,nz]);
end;

%Set domain dimensions	+---------------------------------------------------------- 
ntiles = tilein.wet;

%Set data Attributes for netcdf +---------------------------------------------------------- 
longName = info.longName;
units    = info.units;
coord='lon lat dep';
if(info.nprec==4); xtype ='NC_FLOAT';elseif(info.nprec==8);xtype ='NC_DOUBLE';end;  

%Set global attributes attributes       +---------------------------------------------------------- 
gatt_names = {'Description','Institution','References','Conventions','Software','netCDF Version','matlab Version','_FillValue','missing_value'};

gatt_value{1} = {'Arctic Subpolar Gyre sTate Estimate (ASTE) release 1'};
gatt_value{2} = {'Oden Institute for Computational Engineering and Science, UT-Austin'};
gatt_value{3} = {'  ',...
        '   Nguyen, A.T., H. Pillar, V. Ocaña, A. Bigdeli, T. A. Smith, P. Heimbach. 2021.',...
        '   The Arctic Subpolar Gyre sTate Estimate: Description and Assessment of a ',... 
        '   Data Constrained, Dynamically Consistent Ocean-Sea Ice Estimate for 2002-2017 ',...
        '   Journal of Advances in Modeling Earth Systems, 13, https://doi.org/10.1029/2020MS002398'};
gatt_value{4} = {'CF-1.6 (http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html)'};
gatt_value{5} = {'File created using convert_ASTE2nctiles_singlefield.m'};
gatt_value{6} = {netcdf.inqLibVers};
gatt_value{7} = {version};
gatt_value{8} = {NaN};
gatt_value{9} = {NaN};

if(~(size(gatt_value)==size(gatt_names))); disp('Number of global attribute names and values MUST be the same');end;

%---------------------------------------------------------------------------------------------------------------------
%Loop over tiles 		+-------------------------------------------------------------------------------------
   fprintf('%s %5d %5d %5d \n',varName,dtilex,dtiley,nz);
   fprintf('Processing tile ');
for itile = 1:ntiles;
%for itile = 1;
   fprintf(' %d',itile);
   tileName=sprintf('%4.4i',itile);
   fileTile = [info.outDir info.fnameroot '.' tileName '.nc']; 

   data=tilein.field{itile};
   dims    = size(data);			
   data    = reshape(data,fliplr(dims));           %!!!!!!!!!!!!  	TO COMPLY WITH netCDF conventions CF-1.6 REVERSE ORDER OF DIMENSIONS WRT MITgcm  !!!!!!!!!!!!!!!!!!!!!
   nDim    = length(size(data));			%Number of dimensions
   dimsize = size(data);				%Size of each dimension
   
   %Create netcdf file		+---------------------------------------------------------- 
   %(by default usic basic netcdf, unless data file is very large) 
   if prod(dimsize)*4/1e9<1.5;	
       cmode='clobber';	%Overwrite any existing file with the same name.
   else;		
       cmode='NETCDF4';	%To allow for large file: create a NetCDF-4/HDF5 file
   end;
   ncid = netcdf.create(fileTile,cmode); 	%ncid=nccreate(fileTile,mode);

   %Global Attributes	+------------------------------------------------------------------
   nc_global=netcdf.getConstant('NC_GLOBAL');
   
   for in=1:size(gatt_names,2);
      for iv=1:size(gatt_value{in},2);
         tmp=gatt_names{in}; 
         if (size(gatt_value{in},2)>1 & iv>1); tmp=sprintf('%2.2i',(iv-1));end;
         netcdf.putAtt(ncid,nc_global,tmp,gatt_value{in}{iv});
      end;
   end;
    
   %Dimensions (and dims as variables) +---------------------------------------------------
   %Create the dimension-variables, their names and their values
   for iDim=1:nDim;		
      if dimsize(iDim)~=1;
         dimlist{iDim}=['i' num2str(iDim)];
         dimName{iDim}=['array index ' num2str(iDim)];
         eval(['dimvec.i' num2str(iDim) '=[1:dimsize(iDim)];']);
      end;
   end;
   
   %Define dims
   netcdf.defDim(ncid,'itxt',30);   
   dimid=[];
   for dd=1:length(dimlist); 
      dimid(dd)= netcdf.defDim(ncid,dimlist{dd},dimsize(dd)); 
   end;

   %Define dimensions as variables and their attributes
   for dd=1:length(dimlist); 	
      varid = netcdf.defVar(ncid,dimlist{dd},'NC_DOUBLE',dimid(dd));
      netcdf.putAtt(ncid,varid,'long_name',dimName{dd});
      netcdf.putAtt(ncid,varid,'units','1');
   end;
   netcdf.endDef(ncid);

   %Fill the values of the dimension variables
   for dd=1:length(dimlist);	
     ncputvar(ncid,dimlist{dd},getfield(dimvec,dimlist{dd}));
   end;

   %Variables  +------------------------------------------------------------------------------

   %Data       +------------------------------------------------------------------------------
   %Define diagnostic variable and its attributes
   netcdf.reDef(ncid);
   varid = netcdf.defVar(ncid,varName,xtype,flipdim(dimid,2));    %Notice the order of the dimensions !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   if ~isempty(longName); netcdf.putAtt(ncid,varid,'long_name',longName); end;
   if ~isempty(units); netcdf.putAtt(ncid,varid,'units',units); end;
   if ~isempty(coord); netcdf.putAtt(ncid,varid,'coordinates',coord); end;

   %Write data
   netcdf.endDef(ncid);
   netcdf.putVar(ncid,varid,data); 
   %ncputvar(ncid,varName,data); 

   %GRID	+------------------------------------------------------------------------------
   gxtype ='NC_DOUBLE';   
%keyboard
   %[grid_diag]=set_grid_diag(avail_diag,tileName,gridDir);
%below  is lifted from set_grid_diag, likely should be its own function called set_grid
   grid_diag=[];
   grid_diag=set_grid(info,tileName,info.gridDir);
%   names = {'lon','lat','msk','RAC'};
%   for ii=1:length(names);
%      fileN = [info.gridDir info.name2d3d{ii} '.' tileName '.data'];
%      temp = dir([info.gridDir info.name2d3d{ii} '*.meta']);   
%      temp1 = read_meta(temp.name,info.gridDir);
%      nprec=str2num(temp1.dataprec(end-1:end))/8; prec=['real*' num2str(nprec)];
%      dims=[];
%      for idim=1:temp1.nDims; 
%         dims(idim)=temp1.dimList(1+3*(idim-1));
%      end;
%      if (temp1.nDims==3);
%         dims(temp1.nDims) = tilein.fsize(3);
%      end;
%      grid_diag.(names{ii})=readbin(fileN,dims,1,prec);
%      clear temp temp1 nprec prec dims;
%   end;
%   names={'dep','dz'};
%   for ii=1:length(names);
%      fileN = [info.gridDir info.name1d{ii}  '.data'];
%      temp = dir([info.gridDir info.name1d{ii} '*.meta']);   
%      temp1 = read_meta(temp.name,info.gridDir);
%      nprec=str2num(temp1.dataprec(end-1:end))/8; prec=['real*' num2str(nprec)];
%      dims = temp1.dimList(7);
%      grid_diag.(names{ii})=readbin(fileN,dims,1,prec);
%      clear temp temp1 nprec prec dims
%   end;
%   if strcmp(info.loc_z,'M');
%       grid_diag.dep=abs(grid_diag.dep);
%       grid_diag.dz=grid_diag.dz;
%   elseif strcmp(info.loc_z,'L');
%       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=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 tilein.fsize(3)]);
%   grid_diag.dz  = reshape(grid_diag.dz,[1 1 tilein.fsize(3)]);
%keyboard   
   %gvar = fieldnames(grid_diag)';      %gvar = {grid_diag.lon grid_diag.lat grid_diag.dep tim timstep grid_diag.msk grid_diag.RAC grid_diag.dz};
   if (tilein.fsize(3)==1); %2D diags
      gvar      = {grid_diag.lon grid_diag.lat grid_diag.msk grid_diag.RAC};
      gname     = {'lon','lat','land','area'}; 
      glongName = {'longitude','latitude','land mask','grid cell area'};
      gstdName  = {'longitude','latitude','land_binary_mask','cell_area'};
      gunits    = {'degrees_east','degrees_north','1','m^2'};
      gdimid    = {dimid(2:3) dimid(2:3) dimid(2:3) dimid(2:3)};
   elseif(tilein.fsize(3)>1);  %3D diags
      gvar      = {grid_diag.lon grid_diag.lat grid_diag.dep grid_diag.msk grid_diag.RAC grid_diag.dz};
      gname     = {'lon','lat','dep','land','area','thic'}; 
      glongName = {'longitude','latitude','depth','land mask','grid cell area','grid cell thickness'};
      gstdName  = {'longitude','latitude','depth','land_binary_mask','cell_area','cell_thickness'};
      gunits    = {'degrees_east','degrees_north','m','1','m^2','m'};
      gdimid    = {dimid(2:3) dimid(2:3) dimid(1) dimid(1:3) dimid(2:3) dimid(1)};
   end;

   netcdf.reDef(ncid);

   gvarid=[];
   for igrid=1:length(gname);
      gvarid(igrid) = netcdf.defVar(ncid,gname{igrid},gxtype,flipdim(gdimid{igrid},2)); %Notice the order of the dimensions !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      netcdf.putAtt(ncid,gvarid(igrid),'long_name',glongName{igrid});
      netcdf.putAtt(ncid,gvarid(igrid),'standard_name',gstdName{igrid});
      netcdf.putAtt(ncid,gvarid(igrid),'units',gunits{igrid});
   end;
   netcdf.endDef(ncid);

   %Write GRID 
   for igrid=1:length(gname);
      tmp  = gvar{igrid};
      tmpd = size(tmp); tmp = reshape(tmp,fliplr(tmpd));
      netcdf.putVar(ncid,gvarid(igrid),tmp);
      clear tmp tmpd; 
   end;
   
   %CLOSE nc file	+------------------------------------------------------------------------------
   netcdf.close(ncid); 

end;
fprintf('\n');


