function varargout = fnv_transects2nc(varargin)
%FNV_TRANSECTS2NC  One line description goes here.
%
%   More detailed description goes here.
%
%   Syntax:
%   varargout = fnv_transects2nc(varargin)
%
%   Input: For <keyword,value> pairs call fnv_transects2nc() without arguments.
%   varargin  =
%
%   Output:
%   varargout =
%
%   Example
%   fnv_transects2nc
%
%   See also

%% Copyright notice
%   --------------------------------------------------------------------
%   Copyright (C) 2014 Deltares
%       Kees den Heijer
%
%       kees.denheijer@deltares.nl
%
%       P.O. Box 177
%       2600 MH Delft
%       The Netherlands
%
%   This library is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   This library is distributed 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.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this library.  If not, see <http://www.gnu.org/licenses/>.
%   --------------------------------------------------------------------

% This tool is part of <a href="http://www.OpenEarth.eu">OpenEarthTools</a>.
% OpenEarthTools is an online collaboration to share and manage data and
% programming tools in an open source, version controlled environment.
% Sign up to recieve regular updates of this function, and to contribute
% your own tools.

%% Version <http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html>
% Created: 17 Sep 2014
% Created with Matlab version: 8.2.0.701 (R2013b)

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

%%
OPT = struct(...
    'fname', '../data/wadsea_2012.xyz',...
    'jarkus_url', 'http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/jarkus/profiles/transect.nc',...
    'dataDir', '../../../../openearthrawdata/rijkswaterstaat/jarkus/',...
    'dateFcn', @(s) datenum( regexp(s,'(?<=_)\d{4}(?=\.xyz)','match'), 'yyyy'),...
    'year', [],...
    'id', [3000500 3000540] ...
    );
% return defaults (aka introspection)
% if nargin==0;
%     varargout = {OPT};
%     return
% end
% overwrite defaults with user arguments
OPT = setproperty(OPT, varargin);
%% code
% derive year from filename
dn = feval(OPT.dateFcn, OPT.fname);
if isempty(OPT.year)
    tr = jarkus_transects(...
        'url', OPT.jarkus_url,...
        'year', year(dn),...
        'output', {'time'});
    if ~isscalar(tr.time)
        jarkusyear = year(tr.time(end) + datenum(1970,1,1));
        dnj = datenum(num2str(jarkusyear),'yyyy');
    else
        jarkusyear = year(dn);
        dnj = datenum(num2str(jarkusyear),'yyyy');
    end
else
    jarkusyear = OPT.year;
    dnj = datenum(num2str(jarkusyear),'yyyy');
end
% get model and jarkus transects together in one structure
tr = fnv_xyz2transect(...
    'fname', OPT.fname,...
    'jarkus_url', OPT.jarkus_url,...
    'year', jarkusyear,...
    'id', OPT.id ...
    );

%% create transectstruct jarkus
transectStruct = jarkus_createtransectstruct();
transectStruct = repmat(transectStruct, 1, length(tr.time) * length(tr.id));

n = 1;
skipidx = [];
for jj = 1:size(tr.altitude,1) % time
    for kk = 1:size(tr.altitude,2) % alongshore
        nnid = ~isnan(tr.altitude(jj,kk,:));
        if any(nnid)
            transectStruct(n).areaCode = floor(tr.id(kk)/1e6);
            transectStruct(n).areaName = rws_kustvak(transectStruct(n).areaCode);
            transectStruct(n).time = tr.time(jj);
            transectStruct(n).alongshoreCoordinate = mod(tr.id(kk), 1e6);
            transectStruct(n).year = year(tr.time(jj)+datenum(1970,1,1));
            transectStruct(n).n = sum(nnid);
            transectStruct(n).origin = zeros(1, sum(nnid));
            transectStruct(n).crossShoreCoordinate = tr.cross_shore(nnid);
            transectStruct(n).altitude = tr.altitude(jj,kk,nnid);
            transectStruct(n).id = tr.id(kk);
            transectStruct(n).timeTopo = 107;
            transectStruct(n).monthTopo = 7;
            transectStruct(n).dayTopo = 1;
            transectStruct(n).timeBathy = 107;
            transectStruct(n).monthBathy = 7;
            transectStruct(n).dayBathy = 1;
            transectStruct(n).timelims = [datenum(transectStruct(n).year,1,1); datenum(transectStruct(n).year,12,31)] - datenum(1970,1,1);
            n = n +1;
        else
            skipidx = [skipidx kk];
        end       
    end
end
% remove unused elements
transectStruct(n:end) = [];

tr.id(skipidx) = [];
tr.x(skipidx,:) = [];
tr.y(skipidx,:) = [];
tr.altitude(:,skipidx,:) = [];
tr.z(skipidx,:) = [];

%% create transectstruct model
transectStructmodel = jarkus_createtransectstruct();
transectStructmodel = repmat(transectStructmodel, 1, size(tr.altitude,2));

n = 1;
skipidx = [];
for kk = 1:size(tr.z,1) % alongshore
    nnid = ~isnan(tr.z(kk,:));
    if any(nnid)
        transectStructmodel(n).areaCode = floor(tr.id(kk)/1e6);
        transectStructmodel(n).areaName = rws_kustvak(transectStructmodel(n).areaCode);
        transectStructmodel(n).time = datenum(year(dn),7,1) - datenum(1970,1,1);
        transectStructmodel(n).alongshoreCoordinate = mod(tr.id(kk), 1e6);
        transectStructmodel(n).year = year(dn);
        transectStructmodel(n).n = sum(nnid);
        transectStructmodel(n).origin = zeros(1, sum(nnid));
        transectStructmodel(n).crossShoreCoordinate = tr.cross_shore(nnid);
        transectStructmodel(n).altitude = tr.z(kk,nnid);
        transectStructmodel(n).id = tr.id(kk);
        transectStructmodel(n).timeTopo = 107;
        transectStructmodel(n).monthTopo = 7;
        transectStructmodel(n).dayTopo = 1;
        transectStructmodel(n).timeBathy = 107;
        transectStructmodel(n).monthBathy = 7;
        transectStructmodel(n).dayBathy = 1;
        transectStructmodel(n).timelims = [datenum(transectStructmodel(n).year,1,1); datenum(transectStructmodel(n).year,12,31)] - datenum(1970,1,1);
        n = n +1;
    else
        skipidx = [skipidx kk];
    end
end

%% define a grid based on the transectStruct

disp('converting transects to grid');
grid = jarkus_transect2grid([transectStruct transectStructmodel]);% renamed from transect2grid 2009 june 19th
grid = jarkus_updategrid(grid, fullfile(OPT.dataDir, 'raw', 'info', 'raaien.txt'  ), ...
                               fullfile(OPT.dataDir, 'raw', 'info', 'TIDEINFO.txt')); % this file contains extra information
idx = ismember([transectStructmodel.id], [grid.id]);
tr.id(~idx) = [];
tr.x(~idx,:) = [];
tr.y(~idx,:) = [];
tr.altitude(:,~idx,:) = [];
tr.z(~idx,:) = [];
                           
%% store grid and transects to a netcdf file
outputfile  = sprintf('transects_kzd_%i.nc',year(dn));

disp('Publish grid to NetCDF file');
jarkus_grid2netcdf(outputfile, grid);

%% extract a curvilinear grid definition from the transectStruct x grid H(time, transect, length) where
%  * time is the year, 
%  * transect is the transect and 
%  * lenght is the difference along the line starting from the measurement pole.
disp('Publish transects to a NetCDF file');
jarkus_transect2netcdf(outputfile, transectStruct);

%%
s.Name      = 'altitude_model';
s.Nctype    = nc_double;
s.Dimension = {'time', 'alongshore', 'cross_shore'};
s.Attribute = struct('Name', {'standard_name'   , 'units', 'actual_range', 'comment'                   , 'coordinates', 'grid_mapping', '_FillValue'}, ...
    'Value', {'surface_altitude', 'm'    , [NaN NaN],      sprintf('%i model altitude above geoid (NAP)', year(dn)), 'lat lon'    , 'epsg'        , -9999       });
nc_addvar(outputfile, s);
altitude_model = nan(length(grid.time), length(grid.id), length(grid.crossShoreCoordinate));
timeidx = year(grid.time+datenum(1970,1,1)) == year(dn);
altitude_model(timeidx,:,:) = tr.z;
nc_varput(outputfile, 'altitude_model', altitude_model);

%% return netcdf filename
varargout = {outputfile};