function CHL_APEX = extract_bin_apex_chl(date, P, bindepths, Chl_b)
%
% finds all chl data from APEX data for a given month and depth and calculates median
% depths (bindepths) provided in plot_osd.m - can adjust
%
[yy,month,dd] = datevec(date); %converts date string to date vector
mmyy = [yy month P Chl_b]; %finds each year (once) in dataset and stores in array uyear
uyear = unique(yy); %finds each year (once) in dataset and stores in array uyear
CHL_APEX = []; %initializes array CHL_APEX
for ky = 1:length(uyear) %for each year in dataset
    umonth = unique(month(yy==uyear(ky))); %finds each month (once) in each year
    for km = 1:length(umonth) %for each month in each year in each dataset
        midx = yy==uyear(ky) & month==umonth(km); %where year AND month exist (create logical array)
        Chl_b_midx = Chl_b(midx); %create array chl_b_midx of chl data at midx = true
        P_midx = P(midx); %create array P_midx of depth data at midx = true
        %disp([uyear(ky) umonth(km)]);
        thisrow = [uyear(ky) umonth(km) nan(1,2*(length(bindepths)-1))]; %make array thisrow of yr, mo, NaNs for each bindepth to fill w/chl and st dev
        for kb = 1:(length(bindepths)-1) %for all bindepths
            found = P_midx>=bindepths(kb) & P_midx<bindepths(kb+1); %where dep falls within bindepth range (logical array created)
            thisrow(2+kb) = nanmedian(Chl_b_midx(found)); %skip yr, mo cols of array thisrow and add median chl for bindepth range to next cols of row kb
            thisrow(2+length(bindepths)-1+kb) = nanstd(Chl_b_midx(found)); %skip yr, mo, chl cols and add std to next cols of row kb
        end
        CHL_APEX = [CHL_APEX; thisrow]; %append new row to big array CHL_APEX (see plot.osd.m for CHL_APEX contents)
    end
end
return
