%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                   Developed by Matin Rahnamay Naeini                    %
%                         Email: rahnamam@uci.edu                         %
%                    University of California, Irvine                     %
%                              August 2019                                %
%            Teaching Computation in the Sciences Using MATLAB            %                 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [runoff,storage] = BucketModel(precip,Smax,K)
% First get the size of the data
n = length(precip);
% Assign memory for the variables
storage = nan(n,1);
spill = nan(n,1);  
leak = nan(n,1);  
runoff = nan(n,1);
% Calculate the storage and runoff for the first day
storage(1) = 0;
avail_water = precip(1);
if(avail_water <= Smax)
    % There is no spill
    spill  = 0;
    leak  = K * avail_water;
else
    % There is spill
    spill = avail_water - Smax;
    leak = K* Smax;
end
% Calculate the total runoff for time step t
runoff(1)  = spill + leak;
% Calculate the total storage for time step t
storage(1) = avail_water - runoff(1);
% Calculate the runoff from the bucket model for each day
for t = 2:n    
    % Calculate the total available water
    avail_water = storage(t-1) + precip(t);
    % Control if there is spill
    if(avail_water <= Smax)
        % There is no spill
        spill = 0;
        leak = K * avail_water;
    else
        % There is spill
        spill = avail_water - Smax;
        leak = K* Smax;
    end
    % Calculate the total runoff for time step t
    runoff(t)  = spill + leak;
    % Calculate the total storage for time step t
    storage(t) = avail_water - runoff(t);
end