function [V, x1, x2] = jarkus_horizontalVolume(x, z, z1, z2)
% jarkus_absoluteVolume
%
%   Input:
%     x  = vector with specified distances
%     z  = vector with depths at locations x
%     z1 = upper boundary
%     z2 = lower boundary
%
%   Output:
%     V = volume in m2 relative to z2 level, with vertical limits defined
%     by the position of z1 and z2
%
%   NB: jarkus_distancetoZ returns the first crossing of specified depth
%
% See also: JARKUS, snctools, jarkus_distancetoZ

%% Copyright notice
%   --------------------------------------------------------------------
%   Copyright (C) 2010 Alterra
%       Tommer Vermaas
%       tommer.vermaas@wur.nl | 0317-481654
%
%       Postbus 47
%       6700 AA Wageningen
%
%   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/>.
%   --------------------------------------------------------------------

%% Get position of upper and lower boundaries
x1 = jarkus_distancetoZ(z1,z,x);
x2 = jarkus_distancetoZ(z2,z,x);

if isnan(x1) || isnan(x2) %check if profile covers asked depth zone
    V = NaN;
else
    b = find(x>=x1,1,'first');
    e = find(x<=x2,1,'last');
    X = [x1 x1 x(b:e)' x2]';
    Z = [z2 z1 z(b:e)' z2]';
    
    V=polyarea(X,Z);
end