function bi = calc_startdate_threshold(record_yr,date_yr,thres)
%calc_startdate_threshold Function 1 of 5 to calculate bloom start date.
%   This function uses a long-term threshold value equal to the long-term
%   median chlorophyll concentration (of whole time series, not just one
%   year) plus 5% of that long-term median. Input to the function is the
%   one-year time series and the long-term threshold. Output will be the
%   start date (in matlab datenum format) of the phyto growing season for
%   that one year.
% Example:
%   record_yr = chl_pixel(time_ind);
%   date_yr = date_mat(time_ind);
%   thres  = nanmedian(chl_pixel) + (0.05 .* nanmedian(chl_pixel));
%   bi = calc_startdate_threshold(record_yr,date_yr,thres);'

 % bi = the first time chl>threshold for N  days
    above = find(record_yr > thres);
    N = 5; % Required number of consecutive numbers following a first one
    x = diff(above)==1;
    f = find([false,x']~=[x',false]);
    % f=x;
    g = find(f(2:2:end)-f(1:2:end-1)>=N,1,'first');
    first_t = above(f(2*g-1)); % First t followed by >=N consecutive numbers
    if isempty(first_t) % if there IS no bi according to this def, make that location nan
        bi = nan;
    else
        bi = date_yr(first_t);
    end
end

