% um_ancil_netcdf
% Creating netcdf file that can be converted to a um ancillary file
% file_nc = 'ice2007022812.nc';

filen_nc = 'ostia_sst_clean.nc';
mode = bitor ( nc_clobber_mode, nc_64bit_offset_mode );
nc_create_empty ( filen_nc, mode )

nc_add_dimension ( filen_nc, 'x', length(x) )
nc_add_dimension ( filen_nc, 'y', length(y) )
nc_add_dimension ( filen_nc, 'surface', 1 )
nc_add_dimension ( filen_nc, 't', 0 )

varstruct.Name = 'temp';
varstruct.Nctype = nc_float;
varstruct.Dimension = { 't', 'surface','y','x' };
nc_addvar ( filen_nc, varstruct )

lon_varstruct.Name = 'x';
lon_varstruct.Dimension = { 'x' };
lat_varstruct.Name = 'y';
lat_varstruct.Dimension = { 'y' };
time_varstruct.Name = 't';
time_varstruct.Dimension = { 't' };
surf_varstruct.Name = 'surface';
surf_varstruct.Nctype = nc_float;
surf_varstruct.Dimension = { 'surface' };
nc_addvar ( filen_nc, lon_varstruct )
nc_addvar ( filen_nc, lat_varstruct )
nc_addvar ( filen_nc, time_varstruct )
nc_addvar ( filen_nc, surf_varstruct )

% now nc_varput of data to variables:
nc_varput ( filen_nc, 'x', x(:) );
nc_varput ( filen_nc, 'y', y(:) );
t_step = 1;
nc_varput ( filen_nc, 'surface', 0 );

temp = zeros(1,1,220,220);
temp(1,1,:,:) = sst(:,:);
start = [0 0 0 0];
count = [1 1 220 220];
nc_varput ( filen_nc, 'temp', temp, start, count );

nc_attput ( filen_nc, 'x', 'units','degrees_east' );
nc_attput ( filen_nc, 'x', 'point_spacing', 'even');
nc_attput ( filen_nc, 'y', 'units','degrees_north' );
nc_attput ( filen_nc, 'y', 'point_spacing', 'even');
nc_attput ( filen_nc, 'surface', 'units','level' );
nc_attput ( filen_nc, 'surface', 'positive', 'up');
nc_attput ( filen_nc, 't', 'units','days since 2007-02-21 00:00:00' );
nc_attput ( filen_nc, 't', 'time_origin','21-FEB-2007:00:00:00' );

nc_attput ( filen_nc, 'temp', 'name', 'temp');
nc_attput ( filen_nc, 'temp', 'title', 'temp');
nc_attput ( filen_nc, 'temp', 'date', '21/02/07');
nc_attput ( filen_nc, 'temp', 'time', '00:00');
nc_attput ( filen_nc, 'temp', 'long_name', 'SURFACE TEMPERATURE AFTER TIMESTEP');
nc_attput ( filen_nc, 'temp', 'units', 'm');
nc_attput ( filen_nc, 'temp', 'grid_mapping', 'rotated_pole');
nc_attput ( filen_nc, 'temp', 'north_pole', [145.0, 25.0]); 
nc_attput ( filen_nc, 'temp', 'missing_value', 2.e+20);
nc_attput ( filen_nc, 'temp', '_FillValue', 2.e+20);
nc_attput ( filen_nc, 'temp', 'valid_min', min(sst(:)));
nc_attput ( filen_nc, 'temp', 'valid_max', max(sst(:)));

nc_attput ( filen_nc, nc_global, 'title', 'SST ancillary file for GreenNearly domain' );
nc_addhist ( filen_nc, 'Edited by Stephen Outten');
nc_addhist ( filen_nc, 'OSTIA SST data');

nc_dump ( filen_nc )
