
%% Converts ASCII files (sealevel_startdate_enddate.txt) into netCDF format. 
% Data description: colomn 1: Date of measurement, format YYYYMMDD.HHMMSS;
%                   colomn 2: Sea level [m].
%                                      
%% ---------
clear all

%% Fill in the path to the raw data
aa = input('Input the path and the name to raw data file');
data = load(aa); clear(aa);

%% Store data in transect series
t = data(:,1);
SLevelDate = datenum(num2str(t,'%15.6f'), 'yyyymmdd.HHMMSS');
slevel = data(:,2);

sealevel = struct('SeaLevel', slevel, 'Time', SLevelDate);

%% Enter netCDF file name according to the name of the input raw data file or else...

%----- Create NetCDF file. 
ncid = netcdf.create('sealevel_20100307_20100312.nc','nc_write');  

%% Define global attributes
netcdf.putAtt(ncid, netcdf.getConstant('NC_GLOBAL'), 'title',                    'Sea level');
netcdf.putAtt(ncid, netcdf.getConstant('NC_GLOBAL'), 'institution',              'Institute of Oceanology - BAS');
netcdf.putAtt(ncid, netcdf.getConstant('NC_GLOBAL'), 'source',                   'Measurements are taken by sea level radar Vegapuls 61 (4 … 20 mA/HART two-wire) installed on the pier at Shkorpilovtsi study site - Bulgaria');
netcdf.putAtt(ncid, netcdf.getConstant('NC_GLOBAL'), 'sea_level_radar_location', '42.958038263N, 27.899852161E , WGS84, format DD.DDDDDDDDD');
netcdf.putAtt(ncid, netcdf.getConstant('NC_GLOBAL'), 'project_name',             'MICORE');
netcdf.putAtt(ncid, netcdf.getConstant('NC_GLOBAL'), 'project_url',              'www.micore.eu');
netcdf.putAtt(ncid, netcdf.getConstant('NC_GLOBAL'), 'e-mail',                   'n.andreeva@io-bas.bg');
netcdf.putAtt(ncid, netcdf.getConstant('NC_GLOBAL'), 'conventions',              'CF-1.4');
 
%% Define dimensions
timedim = netcdf.defDim(ncid,'Time', length(t));

%% Create variables and their attributes
timevar = netcdf.defvar(ncid,'Time','double',timedim);
netcdf.putAtt(ncid,timevar,'long_name','time');
netcdf.putAtt(ncid,timevar,'units','hours');

slvar = netcdf.defvar(ncid,'SeaLevel','double', timedim);
netcdf.putAtt(ncid,slvar,'long_name','Sea level fluctuations');
%netcdf.putAtt(ncid,wdminvar,'missing_value','-999');
netcdf.putAtt(ncid,slvar,'units','metres');

%% Exit define mode
netcdf.endDef(ncid);

%% Add data to the created variables
netcdf.putVar(ncid,slvar,sealevel.SeaLevel);
netcdf.putVar(ncid,timevar,sealevel.Time);

%% Close netcdf file
netcdf.close(ncid);
