function ErosionVolume = tb_calc_ErosionVolume(xini,zini,xend,zend,wl,varargin)
%UNTITLED  Calculate the erosion volume above storm surge level
%
%   The erosion volume is calculated by integrating the surface area
%   between the initial bottom profile and the end profile using the
%   trapeziodal integration technic. Begin and end coordinates are trimmed
%   to ensure both profiles start and end at the same position.
%
%   Syntax:
%   varargout = Untitled(varargin)
%
%   Input:
%   xini = Vector with x-coordinates of z-points of initial profile
%   zini = Vector with z-coordinates of initial profile
%   xend = Vector with x-coordinates of z-points of the final profile
%   zini = Vector with z-coordinates of the final profile
%   wl = Waterlevel elevation
%   mode = Source of input data.
%
%   Output:
%   ErosionVolume = Erosion volume above storm surge level
%
%
%% Copyright notice
%   --------------------------------------------------------------------
%   Copyright (C) 2011 <COMPANY>
%       Bram de Vries
%
%       <EMAIL>	
%
%       <ADDRESS>
%
%   This library is free software: you can redistribute it and/or
%   modify it under the terms of the GNU Lesser General Public
%   License as published by the Free Software Foundation, either
%   version 2.1 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
%   Lesser General Public License for more details.
%
%   You should have received a copy of the GNU Lesser General Public
%   License along with this library. If not, see <http://www.gnu.org/licenses/>.
%   --------------------------------------------------------------------

% This tool is part of <a href="http://OpenEarth.nl">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: 23 Mar 2011
% Created with Matlab version: 7.9.1.705 (R2009b) Service Pack 1

% $Id: AH2124
% $Date: 23-03-2011
% $Author: Bram de Vries
% $Revision$
% $HeadURL$
% $Keywords: Mean current velocity

%% Sort data
[xini sid] = sort(xini);
zini = zini(sid);
[xend sid] = sort(xend);
zend = zend(sid);


%% Calculate x-coordinate water level intersection(s)
[xcr zcr xini zini] = findCrossings(xini,zini,[min(xini) max(xini)],[wl wl]);
for icr = 1:length(xcr)
    zini(xini==xcr(icr)) = wl;
end
zini(zini < wl) = wl;

[xcr zcr xend zero] = findCrossings(xend,zend,[min(xend) max(xend)],[wl wl]);
for icr = 1:length(xcr)
    zero(xend==xcr(icr)) = wl;
end
zero(zero < wl) = wl;


%% Calculate sedimentation/erosion volumes
ErosionVolume = trapz(xini,zini) - trapz(xend,zero);