%M_COASTS2NC  rewrites m_map world landboundary into NetCDF file
%
%See also: m_map, SNCTOOLS, LANDBOUNDARY, POLYSPLIT, POLYJOIN, POLY_FUN

% $Id$
% $Date$
% $Author$
% $Revision$
% $HeadURL$
% $Keywords: $

%% Initialize

   OPT.fillvalue         = nan; % NaNs do work in netcdf API
   OPT.dump              = 0;
   
   OPT.pause             = 0;
   
   OPT.refdatenum        = datenum(0000,0,0); % matlab datenumber convention: A serial date number of 1 corresponds to Jan-1-0000. Gives wring date sin ncbrowse due to different calenders. Must use doubles here.
   OPT.refdatenum        = datenum(1970,1,1); % lunix  datenumber convention
   
   OPT.directory_raw     = '../raw/gshhs_1.10/';
   OPT.directory_nc      = '../processed/';
   OPT.ext               = ''; % to add to output file name before *.nc

%% Set (1)

   OPT.file.landboundary = 'm_coasts.mat';
   OPT.file.nc           = 'm_coasts';
   OPT.title             = 'Crude vector coastline of the world';

   D = load(OPT.file.landboundary)
   
   D.lon     = D.ncst(:,1);
   D.lat     = D.ncst(:,2);
   D.version = 'm_map mapping toolbox version 1.4';
   
%% 0 Create file
   
   outputfile    = fullfile(OPT.directory_nc,[OPT.file.nc,'.nc']);
   
   nc_create_empty (outputfile)
   
%% 1 Add global meta-info to file
% Add overall meta info:
% http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.4/cf-conventions.html#description-of-file-contents
   
   nc_attput(outputfile, nc_global, 'title'           , OPT.title);
   nc_attput(outputfile, nc_global, 'institution'     , 'NOAA');
   nc_attput(outputfile, nc_global, 'source'          , 'NOAA');
   nc_attput(outputfile, nc_global, 'history'         , ['Original filename: ',OPT.file.landboundary,...
                                  ', version:' ,D.version,...
                                  ', tranformation to NetCDF: $HeadURL$']);
   nc_attput(outputfile, nc_global, 'references'      , '<http://www.ngdc.noaa.gov/mgg/shorelines/data/gshhs/>,<http://www.eos.ubc.ca/~rich/map.html>');
   nc_attput(outputfile, nc_global, 'email'           , '');
   
   nc_attput(outputfile, nc_global, 'comment'         , 'The lowres coastline was obtained as part of the m_map toolbox, which got it from the Global Self-consistant Hierarchical High-resolution Shorelines, Distributed under the GNU Public License.');
   nc_attput(outputfile, nc_global, 'version'         , D.version);
   
   nc_attput(outputfile, nc_global, 'Conventions'     , 'CF-1.4');
   nc_attput(outputfile, nc_global, 'CF:featureType'  , '');  % https://cf-pcmdi.llnl.gov/trac/wiki/PointObservationConventions
   
   nc_attput(outputfile, nc_global, 'terms_for_use'   , 'These data can be used freely for research purposes provided that the following source is acknowledged: NOAA & m_map.');
   nc_attput(outputfile, nc_global, '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.');
   
%% Add discovery information (test):

   %  http://www.unidata.ucar.edu/projects/THREDDS/tech/catalog/InvCatalogSpec.html
  
   nc_attput(outputfile, nc_global, 'geospatial_lat_min'         , min(D.lat));
   nc_attput(outputfile, nc_global, 'geospatial_lat_max'         , max(D.lat));
   nc_attput(outputfile, nc_global, 'geospatial_lon_min'         , min(D.lon));
   nc_attput(outputfile, nc_global, 'geospatial_lon_max'         , max(D.lon));
  %nc_attput(outputfile, nc_global, 'time_coverage_start'        , '');
  %nc_attput(outputfile, nc_global, 'time_coverage_end'          , '');
   nc_attput(outputfile, nc_global, 'geospatial_lat_units'       , 'degrees_north');
   nc_attput(outputfile, nc_global, 'geospatial_lon_units'       , 'degrees_east' );

%% 2 Create dimensions
   
   nc_add_dimension(outputfile, 'npoints'           , length(D.lon)) ; % incl nan-segment_separators
   nc_add_dimension(outputfile, 'closed_segments'   , length(D.Area)); % incl nan-segment_separators
   nc_add_dimension(outputfile, 'segment_separators', length(D.k))   ; % incl nan-segment_separators
   
%% 3 Create variables
   
   clear nc
   ifld = 0;
   
   % Longitude:
   % http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.4/cf-conventions.html#longitude-coordinate
   
   ifld = ifld + 1;
   nc(ifld).Name         = 'lon';
   nc(ifld).Nctype       = 'float'; % no double needed
   nc(ifld).Dimension    = {'npoints'};
   nc(ifld).Attribute(1) = struct('Name', 'long_name'      ,'Value', 'longitude');
   nc(ifld).Attribute(2) = struct('Name', 'units'          ,'Value', 'degrees_east');
   nc(ifld).Attribute(3) = struct('Name', 'standard_name'  ,'Value', 'longitude');
   nc(ifld).Attribute(4) = struct('Name', 'comment'        ,'Value', 'all segments are closed contours, separated by NaN');
   
   % Latitude:
   % http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.4/cf-conventions.html#latitude-coordinate
   
   ifld = ifld + 1;
   nc(ifld).Name         = 'lat';
   nc(ifld).Nctype       = 'float'; % no double needed
   nc(ifld).Dimension    = {'npoints'};
   nc(ifld).Attribute(1) = struct('Name', 'long_name'      ,'Value', 'latitude');
   nc(ifld).Attribute(2) = struct('Name', 'units'          ,'Value', 'degrees_north');
   nc(ifld).Attribute(3) = struct('Name', 'standard_name'  ,'Value', 'latitude');
   nc(ifld).Attribute(4) = struct('Name', 'comment'        ,'Value', 'all segments are closed contours, separated by NaN');
   
   % Parameters with standard names:
   % * http://cf-pcmdi.llnl.gov/documents/cf-standard-names/standard-name-table/current/standard-name-table/
   
   % Other parameters

   ifld = ifld + 1;
   nc(ifld).Name         = 'k';
   nc(ifld).Nctype       = 'float'; % no double needed
   nc(ifld).Dimension    = {'segment_separators'};
   nc(ifld).Attribute(1) = struct('Name', 'long_name'      ,'Value', 'segment separator indices');
   nc(ifld).Attribute(2) = struct('Name', 'units'          ,'Value', '#');
   nc(ifld).Attribute(3) = struct('Name', 'comment'        ,'Value', 'k=find(isnan(lon(:,1)))');

   ifld = ifld + 1;
   nc(ifld).Name         = 'area';
   nc(ifld).Nctype       = 'float'; % no double needed
   nc(ifld).Dimension    = {'closed_segments'};
   nc(ifld).Attribute(1) = struct('Name', 'long_name'      ,'Value', 'segment patch areas (>0 for land, <0 for lakes and inland seas)');
   nc(ifld).Attribute(2) = struct('Name', 'units'          ,'Value', 'degrees_north*degrees_east');
   nc(ifld).Attribute(3) = struct('Name', 'comment'        ,'Value', 'Area=zeros(length(k)-1,1);for i=1:length(k)-1,x=lon([k(i)+1:(k(i+1)-1) k(i)+1]);y=lat([k(i)+1:(k(i+1)-1) k(i)+1]);nl=length(x);Area(i)=sum(diff(x).*(y(1:nl-1)+y(2:nl))/2 );end;');


%% 4 Create variables with attibutes
% When variable definitons are created before actually writing the
% data in the next cell, netCDF can nicely fit all data into the
% file without the need to relocate any info.
   
   for ifld=1:length(nc)
       nc_addvar(outputfile, nc(ifld));
   end
   
%% 5 Fill variables
   
   nc_varput(outputfile, 'lon'                  , D.lon);
   nc_varput(outputfile, 'lat'                  , D.lat);
   nc_varput(outputfile, 'k'                    , D.k);
   nc_varput(outputfile, 'area'                 , D.Area);
   
%% 6 Check
   
   if OPT.dump
       nc_dump(outputfile);
   end
   
%% EOF