function bw2netcdf(filename, m, varargin)
%
%	Creates BeachWidth.nc file. 
%	'm' struct is called from BW2nc.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('BW_release%s', datestr(nowutc, 'yyyymmdd'))),...
    struct( 'Name', 'Metadata_Conventions', 'Value', 'Unidata Dataset Discovery v1.0'),...
    struct( 'Name', 'title', 'Value', 'beach width at mean high water and beach width at mean low water along the Dutch coast'),...
    struct( 'Name', 'summary', 'Value', 'beach width at mean high water and beach width at mean low water with respect to +3 m NAP along the Dutch coast since 1843'),...
    struct( 'Name', 'keywords', 'Value', 'Beach Width at mean high water, Beach Width at 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'), 'BW2nc.m')),...
    struct( 'Name', 'HEADurl', 'Value', 'https://svn.oss.deltares.nl/repos/openearthrawdata/trunk/rijkswaterstaat/strandbreedte/'),...
    struct( 'Name', 'comment', 'Value', 'Beach width with respect to +3 m NAP intersection with Jarkus profile'),...
    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: http://www.rijkswaterstaat.nl , Deltares storage: http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/strandbreedte, converted with script BW2nc.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

% beach_width_at_MHW
    s.Name      = 'beach_width_at_mean_high_water';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'long_name'                               									  , 'units'},...
                          'Value',{'distance between dune boundary at +3 m NAP and sea boundary at mean high water', 'm' });
    Variables = [Variables, s];
	
% beach_width_at_MLW
    s.Name      = 'beach_width_at_mean_low_water';
    s.Datatype    = 'double';
    s.Dimensions = [alongshore_dim, time_dim];
    s.Attributes = struct('Name' ,{'long_name'                               									  , 'units'},...
                          'Value',{'distance between dune boundary at +3 m NAP and sea boundary at mean low water', 'm' });
    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,'beach_width_at_mean_high_water', m.beach_width_at_mean_high_water);
    ncwrite(filename,'beach_width_at_mean_low_water' , m.beach_width_at_mean_low_water);
	
%% check
ncinfo(filename);

%%%%%%


end