function y = stormcheck (x, gap)
%
% Accepts a 2-column array x with columns for time and precipitation
% and a parameter 'gap' indicating how many time steps without precipitation
% represents a transition from one storm event to another.
%
% Returns a 4-column array y, repeating the columns in x and adding
% a third column that indicates whether the time step is part of a storm event
% as defined when the function eventinfo.m is called, as well as a fourth column indicating
% how many time steps the storm lasts for.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INITIALIZATION OF VARIABLES                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
datapts = size (x,1); % Check to see how many data points are in the series
storms = ones(datapts,3); % Set up a 3-column array for finding storm events
startcheck = 0; % Initialize variable to deal with initial time steps
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% COPY ARGUMENT ARRAY INTO FIRST TWO COLUMNS OF NEW ARRAY %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for i = 1:datapts
%     storms(i,1) = x(i,1);
%     storms(i,2) = x(i,2);
% end;
storms(:,1)=x(:,1); storms(:,2)=x(:,2);
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% GO FORWARD THROUGH ARGUMENT ARRAY AND LOOK FOR GAPS    %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:(datapts-(gap-1))     % beware of too short a file, index may go to zero!!! (gap>1 also!)
    if startcheck == 0 & x(i,2) == 0
        storms (i,3) = 0; % no event indicated
    else
        ; % do nothing to alter ones array
    end;
    check = 0; % Initialize variable looking for non-zero values
    for j = 0:(gap-1)   % look for non-zero rain in gap
        if x(i+j,2)==0
            ;   % no rain in time step
        else
            check = 1; % Indicate that non-zero values are in gap
            startcheck = 1; % End initial series of zeros indicating no event (3rd column in storms)
        end;
    end;
    if check == 0 % If all values in gap were zero, this is true
        for j = 0:(gap-1)   
            storms(i+j,3)=0; % Loop assigns zero values indicating no event 
        end;
        i = i + gap; % Gap found, so check moves to datapoint beyond gap
    else
        ; % If a gap was not found, nothing is done to alter the ones array
    end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% GO BACKWARDS THROUGH ARRAY AND FILL IN FINAL VALUES    %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
check = 0; 
for i = 0:(gap-2)
    j = datapts - i;
    if (check == 0) & (x(j,2) == 0)
        storms(j,3) = 0;
    else
        check = 1;
        storms(j,3)=1;
    end;
end;
infocheck = eventinfo(storms);
events = size(infocheck,1);
for i = 1:events
    for j=1:datapts
        if infocheck(i,2)==j
            storms(j,4)=infocheck(i,4);
        end;
    end;
end;
y=storms;
