function mwl2netcdf(filename, m, varargin)
%
%	Creates MHW_MLW.nc file. 
%	'm' struct is called from MW2nc.m
%	Uses matlab nc functions
%
%	---------------------------------------
% 
%       Giorgio Santinelli
%
%       Giorgio.Santinelli@deltares.nl
%
%       Deltares
%       P.O. Box 177
%       2600 MH Delft
%       The Netherlands
%
%	---------------------------------------
%
% $Id$
% $Date$
% $Author$
% $Revision$
% $HeadURL$
 

OPT = struct(...
    'publisher_name', getenv('USERNAME'),...
    'publisher_email', 'info@deltares.nl',...
    'historyatt', '$HeadURL $ $Id $',...
    'processing_level', 'preliminary');

OPT = setproperty(OPT, varargin);

datefmt = 'yyyy-mm-ddTHH:MMZ'; % date format
STRINGSIZE = 100;

    Attributes = [...
    struct( 'Name', 'naming_authority', 'Value', 'deltares.nl' ),... 
    struct( 'Name', 'id', 'Value', sprintf('MHW_MLW_release%s', datestr(nowutc, 'yyyymmdd'))),...
    struct( 'Name', 'Metadata_Conventions', 'Value', 'Unidata Dataset Discovery v1.0'),...
    struct( 'Name', 'title', 'Value', 'mean high water and mean low water along the Dutch coast'),...
    struct( 'Name', 'summary', 'Value', 'mean high water and mean low water along the Dutch coast since 1843'),...
    struct( 'Name', 'keywords', 'Value', 'Mean high water, Mean low water, Dutch coast'),...
    struct( 'Name', 'keywords_vocabulary', 'Value', 'http://www.eionet.europa.eu/gemet'),...
    struct( 'Name', 'standard_name_vocabulary', 'Value', 'http://cf-convention.github.io/'),...
    struct( 'Name', 'history', 'Value', sprintf('Data received from Rijkswaterstaat\nNetCDF created on %s by %s on computer %s\\%s with script %s',datestr(now,31), getenv('USERNAME'), getenv('USERDOMAIN'), getenv('COMPUTERNAME'), 'MW2nc.m')),...
    struct( 'Name', 'HEADurl', 'Value', 'https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/kustlijnkaartenboek/'),...
    struct( 'Name', 'comment', 'Value', 'Most seaward point with descending Jarkus transect.nc profile is taken as intersection'),...
    struct( 'Name', 'Years covered', 'Value', ['1843-' num2str(m.jarkusyear(end)) ]),...
    struct( 'Name', 'institution', 'Value', 'Rijkswaterstaat'),...
    struct( 'Name', 'source'     , 'Value', 'on shore and off shore measurements intersection with https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/jarkus/raw/info/TIDEINFO.txt (Rijkswaterstaat)'),...
    struct( 'Name', 'references' , 'Value', 'Original source: Rijkswaterstaat (Morphan), Deltares storage: http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/ converted with script MW2nc.m'),...
    struct( 'Name', 'Conventions', 'Value', 'CF-1.6'),...
    ... % Creator Search attributes
    struct( 'Name', 'creator_name', 'Value', 'Rijkswaterstaat'),...
    struct( 'Name', 'creator_url', 'Value', 'http://www.rijkswaterstaat.nl'),...
    struct( 'Name', 'creator_email', 'Value', 'info@rijkswaterstaat.nl'),...
    struct( 'Name', 'date_created', 'Value', datestr(nowutc, datefmt)),...
    struct( 'Name', 'date_modified', 'Value', datestr(nowutc, datefmt)),...
    struct( 'Name', 'date_issued', 'Value', datestr(nowutc, datefmt)),...
    ... % Publisher Search attributes
    struct( 'Name', 'publisher_name', 'Value', OPT.publisher_name),...
    struct( 'Name', 'publisher_url', 'Value', 'http://www.deltares.nl'),...
    struct( 'Name', 'publisher_email', 'Value', OPT.publisher_email),...
    ... % Extent Search attributes
    ... % Other Extent Information attributes
    struct( 'Name', 'geospatial_vertical_units', 'Value', 'm'),...
    struct( 'Name', 'geospatial_vertical_positive', 'Value', 'up'),...
    ...% Other attributes
	struct( 'Name', 'processing_level', 'Value', OPT.processing_level),...
	struct( 'Name', 'license', 'Value', [sprintf('These data can be used freely for research purposes provided that the following source is acknowledged: %s. ', 'RIJKSWATERSTAAT')...
                'disclaimer: This data is made available in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.']),...
    struct( 'Name', 'time_coverage_start', 'Value', '1843'),...
    struct( 'Name', 'time_coverage_end', 'Value', num2str(m.jarkusyear(end))),...
    struct( 'Name', 'time_coverage_resolution', 'Value', 'year')...
    ];

%% Define and create dimensions
% %  unlimited "time" dimension in Matlab seems to give variable "time" a 
% %  size equal to the the maximum dimension among all variables [2268]. 
% %  This leads to storing a useless amount of data. 
%    time_dim = struct('Name', 'time', 'Length', 0, 'Unlimited', true);
    time_dim = struct('Name', 'time', 'Length', length(m.time), 'Unlimited', false);
    bounds2_dim = struct('Name', 'bounds2', 'Length', 2, 'Unlimited', false);
    alongshore_dim = struct('Name', 'alongshore', 'Length', length(m.id), 'Unlimited', false);
    cross_shore_dim = struct('Name', 'cross_shore', 'Length', length(m.cross), 'Unlimited', false);
    stringsize_dim = struct('Name', 'stringsize', 'Length', STRINGSIZE, 'Unlimited', false);
    Dimensions = [time_dim, bounds2_dim, alongshore_dim, cross_shore_dim, stringsize_dim];
    
%% add epsg
    % smaller variables first
    epsg        = 28992;
    [~,~,OPT]=convertCoordinates(0,0,'CS1.code',epsg,'CS2.code',4326);
    %[CoordinateSystems, Operations , CoordSysCart ,CoordSysGeo] = GetCoordinateSystems();
    s.Name      = 'epsg';
    s.Datatype    = 'int32';
    s.Dimensions = [];
    s.Attributes = struct('Name', ...
       {'grid_mapping_name', ...
        'semi_major_axis', ...
        'semi_minor_axis', ...
        'inverse_flattening', ...
        'latitude_of_projection_origin', ...
        'longitude_of_projection_origin', ...
        'false_easting', ...
        'false_northing', ...
        'scale_factor_at_projection_origin',...
        'comment'}, ...
        'Value', ...
        {OPT.proj_conv1.method.name,    ...
        OPT.CS1.ellips.semi_major_axis, ...
        OPT.CS1.ellips.semi_minor_axis, ...
        OPT.CS1.ellips.inv_flattening,  ...
        OPT.proj_conv1.param.value(strcmp(OPT.proj_conv1.param.name,'Latitude of natural origin'    )), ...
        OPT.proj_conv1.param.value(strcmp(OPT.proj_conv1.param.name,'Longitude of natural origin'   )),...
        OPT.proj_conv1.param.value(strcmp(OPT.proj_conv1.param.name,'False easting'                 )),...
        OPT.proj_conv1.param.value(strcmp(OPT.proj_conv1.param.name,'False northing'                )),...
        OPT.proj_conv1.param.value(strcmp(OPT.proj_conv1.param.name,'Scale factor at natural origin')),...
        'value is equal to EPSG code'});
    Variables = s;

%% Define and create variables
    s.Name       = 'id';
    s.Datatype   = 'int32';
    s.Dimensions = alongshore_dim;
    s.Attributes = struct('Name' ,{'long_name' , 'comment'},...
                         'Value',{'identifier' , 'sum of area code (*1e6) and alongshore coordinate'});
    Variables = [Variables, s];
    
    flag_values = 1:17;%unique(m.areaCode);
    flag_meanings = rws_kustvak(flag_values);
    flag_meanings = str2line(flag_meanings,'s',', ');
    
    s.Name       = 'areacode';
    s.Datatype   = 'int32';
    s.Dimensions = alongshore_dim;
    s.Attributes = struct('Name' ,{'long_name','flag_values','flag_meanings','flag_comment'       ,'comment'},...
                          'Value',{'area code', flag_values , flag_meanings ,'points to: areaname','codes for the 17 coastal areas (kustvakken) as defined by Rijkswaterstaat'});
    Variables = [Variables, s];

    s.Name      = 'areaname';
    s.Datatype  = 'char';
    s.Dimensions = [stringsize_dim, alongshore_dim];
    s.Attributes = struct('Name',{'long_name','flag_comment'        ,'comment'},...
                         'Value',{'area name','indexed in: areacode','names for the 17 coastal areas (kustvakken) as defined by Rijkswaterstaat'});
    Variables = [Variables, s];

    s.Name       = 'alongshore';
    s.Datatype   = 'double';
    s.Dimensions = alongshore_dim;
    s.Attributes = struct('Name' ,{'long_name'             , 'units', 'comment'},...
                         'Value',{'alongshore coordinate', 'm'     , 'alongshore coordinate within the 17 coastal areas (kustvakken) as defined by Rijkswaterstaat'});
    Variables = [Variables, s];

    s.Name       = 'cross_shore';
    s.Datatype   = 'double';
    s.Dimensions = cross_shore_dim;
    s.Attributes = struct('Name' ,{'long_name'             , 'units', 'comment'},...
                         'Value',{'cross-shore coordinate', 'm'    , 'cross-shore coordinate relative to the rsp (rijks strand paal)'});
    Variables = [Variables, s];

    s.Name       = 'time';
    s.Datatype   = 'double';
    s.Dimensions = time_dim;
    s.Attributes = struct('Name' ,{'standard_name'          ,'axis' ,'units'                 ,'cell_methods','bounds'     ,'comment'         },...
                         'Value',{'time'                   ,'T'    ,'days since 1970-01-01' ,'mean'        ,'time_bounds','measurement year (date is artificially set to July, 1st); see time_MKL'});
    Variables = [Variables, s];

    s.Name      = 'time_bounds';
    s.Datatype    = 'double';
    s.Dimensions = [bounds2_dim, time_dim];
    s.Attributes = struct('Name' ,{'standard_name'          ,'units'                },...
                         'Value',{'time'                   ,'days since 1970-01-01'});
    Variables = [Variables, s];

    % ! important: time has to be the last! 
    % http://stackoverflow.com/questions/16938779/matlab-nc-unlimited-in-the-wrong-index-when-writing-unlimited-time-dimension-i

% mean_high_water
    s.Name      = 'mean_high_water';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim];
    s.Attributes = struct('Name' ,{'long_name'      , 'units', 'source'																													 , 'comment'},...
                          'Value',{'mean high water', 'm'    , 'https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/jarkus/raw/info/TIDEINFO.txt (Rijkswaterstaat)' , 'mean high water in 1990, relative to NAP'});
    Variables = [Variables, s];

% mean_high_water_cross
    s.Name      = 'mean_high_water_cross';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'long_name'                               , 'units', 'comment'},...
                          'Value',{'mean high water cross-shore intersection', 'm'    , 'mean high water intersection with transect profile altitude. Most seaward point with descending profile is taken'});
    Variables = [Variables, s];

% mean_high_water_lat
    s.Name         = 'mean_high_water_lat';
    s.Datatype     = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'standard_name'         , 'long_name',             'units',        'axis', 'comment'},...
                         'Value',{'latitude'               , 'MHW latitude position', 'degree_north', 'X',    'mean high water latitude position as defined by Rijkswaterstaat'});
    Variables = [Variables, s];

% mean_high_water_lon
    s.Name         = 'mean_high_water_lon';
    s.Datatype     = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'standard_name', 'long_name',              'units',        'axis', 'comment'},...
                          'Value',{'longitude'    , 'MHW longitude position', 'degrees_east', 'Y',    'mean high water longitude position as defined by Rijkswaterstaat'});
        Variables = [Variables, s];

% mean_high_water_x
    s.Name      = 'mean_high_water_x';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'standard_name'          , 'long_name',      'units', 'axis', 'comment'},...
                          'Value',{'projection_x_coordinate', 'MHW x position', 'm',     'X',    'mean high water x position as defined by Rijkswaterstaat'});
    Variables = [Variables, s];
    
% mean_high_water_y
    s.Name      = 'mean_high_water_y';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'standard_name'          , 'long_name',      'units', 'axis', 'comment'},...
                          'Value',{'projection_y_coordinate', 'MHW y position', 'm',     'Y',    'mean high water y position as defined by Rijkswaterstaat'});
    Variables = [Variables, s];
    
% mean_low_water
    s.Name      = 'mean_low_water';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim];
    s.Attributes = struct('Name' ,{'long_name'      , 'units', 'source'																													 , 'comment'},...
                          'Value',{'mean low water', 'm'    , 'https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/jarkus/raw/info/TIDEINFO.txt (Rijkswaterstaat)' , 'mean low water in 1990, relative to NAP'});
    Variables = [Variables, s];

% mean_low_water_cross
    s.Name      = 'mean_low_water_cross';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'long_name'                               , 'units', 'comment'},...
                          'Value',{'mean low water cross-shore intersection', 'm'    , 'mean low water intersection with transect profile altitude. Most seaward point with descending profile is taken'});
    Variables = [Variables, s];

% mean_low_water_lat
    s.Name         = 'mean_low_water_lat';
    s.Datatype     = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'standard_name'         , 'long_name',             'units',        'axis', 'comment'},...
                         'Value',{'latitude'               , 'MLW latitude position', 'degree_north', 'X',    'mean low water latitude position as defined by Rijkswaterstaat'});
    Variables = [Variables, s];

% mean_low_water_lon
    s.Name         = 'mean_low_water_lon';
    s.Datatype     = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'standard_name', 'long_name',              'units',        'axis', 'comment'},...
                          'Value',{'longitude'    , 'MLW longitude position', 'degrees_east', 'Y',    'mean low water longitude position as defined by Rijkswaterstaat'});
        Variables = [Variables, s];

% mean_low_water_x
    s.Name      = 'mean_low_water_x';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'standard_name'          , 'long_name',      'units', 'axis', 'comment'},...
                          'Value',{'projection_x_coordinate', 'MLW x position', 'm',     'X',    'mean low water x position as defined by Rijkswaterstaat'});
    Variables = [Variables, s];
    
% mean_low_water_y
    s.Name      = 'mean_low_water_y';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'standard_name'          , 'long_name',      'units', 'axis', 'comment'},...
                          'Value',{'projection_y_coordinate', 'MLW y position', 'm',     'Y',    'mean low water y position as defined by Rijkswaterstaat'});
    Variables = [Variables, s];
    
%% write schema to file        

ncSchema = struct(...
        'Name', '/',...
        'Dimensions', Dimensions,...
        'Variables', Variables,...
        'Attributes', Attributes,...
        'Groups', [],...
        'Format', 'classic');

    ncwriteschema(filename, ncSchema)

%% Store index variables
    ncwrite(filename, 'time'        , m.time    );
    ncwrite(filename, 'time_bounds' , m.time_bounds);

    ncwrite(filename, 'id'          , m.id);
    ncwrite(filename, 'areacode'    , m.areacode);
    areanames = m.areaname;
    areanames(:, size(areanames,2)+1:STRINGSIZE) = ' ';
    ncwrite(filename, 'areaname', areanames);

    ncwrite(filename, 'alongshore', m.along);
    ncwrite(filename, 'cross_shore', m.cross);
    
    ncwrite(filename,'mean_high_water'       , m.mean_high_water);
    ncwrite(filename,'mean_high_water_cross' , m.mean_high_water_cross);    
	ncwrite(filename,'mean_high_water_x'     , m.mean_high_water_x);
    ncwrite(filename,'mean_high_water_y'     , m.mean_high_water_y);
    ncwrite(filename,'mean_high_water_lat'   , m.mean_high_water_lat);
    ncwrite(filename,'mean_high_water_lon'   , m.mean_high_water_lon);

    ncwrite(filename,'mean_low_water'       , m.mean_low_water);
    ncwrite(filename,'mean_low_water_cross' , m.mean_low_water_cross);
    ncwrite(filename,'mean_low_water_x'     , m.mean_low_water_x);	
    ncwrite(filename,'mean_low_water_y'     , m.mean_low_water_y);	
    ncwrite(filename,'mean_low_water_lat'   , m.mean_low_water_lat);	
    ncwrite(filename,'mean_low_water_lon'   , m.mean_low_water_lon);
	
%% check
ncinfo(filename);

%%%%%%


end