function Lexp = fit_trailing_exponential(z,P,plotFlag)

% This finds constants for extending a production profile to infinite depth
% via a single exponential approximation.
%
% syntax: out = fit_trailing_exponential(z,P,plotFlag);
%
% z is a vector of depths
% P vector of corresponding production rates
%
% plotFlag 1 or 0; on by default
%
% Lexp is such that P(z) =
% P(z = max(z)).*exp(-z./out.Lexp)
%
% Greg Balco
% Berkeley Geochronology Center
% February, 2018

if nargin < 3;
    plotFlag = 1;
end;

Lexp = 1/(-(1/(z(end)-z(end-1))).*log(P(end)./P(end-1)));

if plotFlag == 1;
    figure;
    semilogy(z((end-5):end),P((end-5):end),'go');
    hold on; 

    px = (z(end):100:(z(end)+10000));
    py = P(end).*exp(-(px-z(end))./Lexp);
    plot(px,py,'g');
end;
