%
% This is the name of the data file we will create.
FILE_NAME='sfc_pres_temp.nc';

%
% These are used to construct some example data.
sample_pressure = 900;
sample_temp = 9.0;

%
% Create some pretend data. If this wasn't an example program, we
% would have some real data to write, for example, model
% output.
lats = [25:0.5:27.5];
NLAT = length(lats);
lons = [-125:0.5:-119.5];
NLON = length(lons);

[Lon,Lat] = meshgrid([0:NLON-1],[0:NLAT-1]);

pres_out = sample_pressure + (Lon*NLAT+Lat);
temp_out = sample_temp + (Lon*NLON+Lat)/4;

%
% We'll create the file, variables, and dimensions using
% vanilla mexnc. The attributes and data writes will be done
% using SNCTOOLS. It's just easier that way.

%
% Create the file.
[ncid, status] = mexnc ( 'CREATE', FILE_NAME, nc_clobber_mode );
if status, error(mexnc('STRERROR',status)), end

%
% Define the dimensions. */
[lat_dimid, status] = mexnc ( 'DEF_DIM', ncid, 'latitude', NLAT );
if status, error(mexnc('STRERROR',status)), end

[lon_dimid, status] = mexnc ( 'DEF_DIM', ncid, 'longitude', NLON );
if status, error(mexnc('STRERROR',status)), end

%
% Define coordinate netCDF variables. They will hold the
% coordinate information, that is, the latitudes and longitudes. A
% varid is returned for each.
[lat_varid, status] = mexnc ( 'DEF_VAR', ncid, ...
'latitude', nc_float, 1, lat_dimid );
if status, error(mexnc('STRERROR',status)), end

[lon_varid, status] = mexnc ( 'DEF_VAR', ncid, ...
'longitude', nc_float, 1, lon_dimid );
if status, error(mexnc('STRERROR',status)), end

[pres_varid, status] = mexnc ( 'DEF_VAR', ncid, ...
'pressure', nc_float, 2, [lat_dimid lon_dimid] );
if status, error(mexnc('STRERROR',status)), end

[temp_varid, status] = mexnc ( 'DEF_VAR', ncid, ...
'temperature', nc_float, 2, [lat_dimid lon_dimid] );
if status, error(mexnc('STRERROR',status)), end

%
% Close the file.
status = mexnc ( 'CLOSE', ncid );
if status, error(mexnc('STRERROR',status)), end

%
% Now switch to SNCTOOLS to do the higher-level stuff.
%
% Define units attributes for coordinate vars.
nc_attput ( FILE_NAME, 'latitude', 'units', 'degrees_north' );
nc_attput ( FILE_NAME, 'longitude', 'units', 'degrees_east' );
nc_attput ( FILE_NAME, 'pressure', 'units', 'hPa' );
nc_attput ( FILE_NAME, 'temperature', 'units', 'celsius' );

%
% Write the coordinate variable data. This will put the latitudes
% and longitudes of our data grid into the netCDF file.
nc_varput ( FILE_NAME, 'latitude', lats );
nc_varput ( FILE_NAME, 'longitude', lons );
nc_varput ( FILE_NAME, 'pressure', pres_out );
nc_varput ( FILE_NAME, 'temperature', temp_out );

fprintf(1, '*** SUCCESS writing example file sfc_pres_temp.nc!\n');