function SAL_APEX = extract_bin_apex_sal(date, P, bindepths, S)
%
% finds all salinity 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
uyear = unique(yy); %finds each year (once) in dataset and stores in array uyear
SAL_APEX = []; %initializes array SAL_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)
        S_midx = S(midx); %create array S_midx of sal data at midx = true
        P_midx = P(midx); %create array dep_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/sal 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(S_midx(found)); %skip yr, mo cols of array thisrow and add median sal for bindepth range to next cols of row kb
            thisrow(2+length(bindepths)-1+kb) = nanstd(S_midx(found)); %skip yr, mo, sal cols and add std to next cols of row kb
        end
        SAL_APEX = [SAL_APEX; thisrow]; %append new row to big array SAL_APEX (see plot.osd.m for SAL_APEX contents)
    end
end
return
