function varargout = calc_profilefluct(varargin)
%CALC_PROFILEFLUCT  Calculate profile volume in active DURUS+ erosion profile part
%
%   This function calculates the DUROS+ erosion profile under normative
%   storm conditions and provides the (initial) profile volume under active
%   profile part. The lower boundary of the volume is NAP-55m, since no
%   JarKus measurements are found below this level.
%
%   Syntax:
%   varargout = calc_profilefluct(varargin)
%
%   Input: For <keyword,value> pairs call calc_profilefluct() without arguments.
%   varargin  =
%
%   Output:
%   varargout =
%
%   Example
%   calc_profilefluct
%
%   See also

%% Copyright notice
%   --------------------------------------------------------------------
%   Copyright (C) 2014 Deltares
%       Kees den Heijer
%
%       Kees.denHeijer@deltares.nl
%
%       Deltares
%       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: 06 Mar 2014
% Created with Matlab version: 8.1.0.604 (R2013a)

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

%%
OPT = struct(...
    'id', 7004325,...
    'url', 'http://dtvirt5.deltares.nl:8080/thredds/dodsC/opendap/rijkswaterstaat/jarkus/profiles/transect_r2013_filled.nc',...
    'yearid', [],...
    'bndslimit', [],...
    'plot', false);
OPT = setproperty(OPT, varargin);

%%
t = datevec(nc_cf_time(OPT.url, 'time'));
if isempty(OPT.yearid)
    OPT.yearid = true(size(t(:,1)));
end
yyyy = t(OPT.yearid,1);

tr = jarkus_transects(...
    'year', yyyy,...
    'url', OPT.url,...
    'id', OPT.id);

bc = get_hr_boundaryconditions(...
    'id', OPT.id,...
    'datadir', '.');

%disp(bc)

[V, Vc, d, dc] = deal(nan(size(OPT.yearid')));
bnds = nan(length(OPT.yearid), 2);

nnid = ~isnan(tr.altitude);
aidx = 1;
yid = cumsum(OPT.yearid);
DuneErosionSettings('set', 'AdditionalErosion', false, 'BoundaryProfile', false);
for iy = find(ismember(t(:,1), yyyy)')
    riy = yid(iy);
    crid = squeeze(nnid(riy,aidx,:));
    z = squeeze(tr.altitude(riy,aidx,crid));
    x = tr.cross_shore(crid);
    result = DUROS(x(:),z(:),'D50', bc.D50, 'WL_t', bc.Rp, 'Tp_t', bc.Tp, 'Hsig_t', bc.Hs);
    bnds(iy,:) = minmax(result(1).xActive(:)');
    if bnds(iy,1)> OPT.bndslimit(riy,2) || bnds(iy,2) < OPT.bndslimit(riy,1)
        % the erosion profile is totally outside the zone of actual
        % measured point in the year of concern (all points are based on
        % interpolation and/or extrapolation. Skip this year
        continue
    end
    V(iy) = getVolume(x,z,...
        'LandwardBoundary', bnds(iy,1),...
        'SeawardBoundary', bnds(iy,2),...
        'LowerBoundary', -55);
    d(iy) = interp1(x, z, bnds(iy,2));
end
extrbnds = minmax(bnds(:)');
[lon, lat] = jarkus_rsp2lonlat(extrbnds, OPT.id*ones(size(extrbnds)), 'url', OPT.url);
actidx = tr.cross_shore >= min(extrbnds) & tr.cross_shore <= max(extrbnds);
zb = squeeze(tr.altitude(~isnan(d(OPT.yearid)),aidx,actidx));
dmax = nanmax(zb(:));
dmin = nanmin(zb(:));
dlimits = [dmin dmax];

%% calculate volumes for the outermost bounds
for iy = find(~isnan(V))
    riy = yid(iy);
    crid = squeeze(nnid(riy,aidx,:));
    z = squeeze(tr.altitude(riy,aidx,crid));
    x = tr.cross_shore(crid);
    % volume
    Vc(iy) = getVolume(x,z,...
        'LandwardBoundary', extrbnds(1),...
        'SeawardBoundary', extrbnds(2),...
        'LowerBoundary', -55);
    % depth contour
    dc(iy) = interp1(x, z, extrbnds(2));
end

varargout = {V, Vc, d, dc, bnds, extrbnds, lon, lat, dlimits};

%%
if OPT.plot
    subplot(2,2,1)
    ph = plot(yyyy, V, yyyy, Vc);
    c = get(ph, 'Color');
    
    subplot(2,2,2)
    plot(yyyy, d, yyyy, dc)
    
    ax3 = subplot(2,2,3);
    hist(V)
    h = findobj(ax3,'Type','patch');
    set(h,'FaceColor', c{1},'EdgeColor','w')
    
    ax4 = subplot(2,2,4);
    hist(Vc)
    h = findobj(ax4,'Type','patch');
    set(h,'FaceColor', c{2},'EdgeColor','w')
end