function [var_mean,var_std] = find_mean_CTD_data(depth_ranges, bin_width, meas_depths, var)

% Take a set of CTD casts, where rows represent measurment depths, and
% columns represent casts at a single station, and average with depth to
% produce evenly spaced depth bins. Returns both mean and standard
% deviation at each desired depth. Assumes meas_depths is positive.
%
% Inputs:
% depth_ranges: vector indicating spacing for averages.
% bin_width: size of bin to average over (e.g. .5 for 1/2 m bins)
% meas_depth: depths where measurements were made
% var: variable values at each meas_depth point
%
% Outputs:
% var_mean: mean value (calculated using nanmean) of variable supplied at
%           each depth in depth_ranges (averaged over bin_width)
% var_std: standard deviation (calculated using stdev) of variable supplied at
%           each depth in depth_ranges (calculated over bin_width)

% Convert the input matrices into vectors, do not need to preserve casts
var=var(:); meas_depths=meas_depths(:);

% For each desired depth, get the average and standard deviation
var_mean=zeros(1,length(depth_ranges))*NaN; var_std=var_mean;
for n=1:length(depth_ranges)
    var_mean(n)=nanmean(var(meas_depths<depth_ranges(n)+bin_width/2 & meas_depths>depth_ranges(n)-bin_width/2));
    var_std(n)=nanstd(var(meas_depths<depth_ranges(n)+bin_width/2 & meas_depths>depth_ranges(n)-bin_width/2));
end