function [d] = azim_av(d)
%azim_av: Decomposes spatially resolved PIV displacements into radial and
%azimuthal components, then azimuthally averages displacements to obtain
%displacement profiles
% Written 2012 G. K. German
% Modified X.Liu and G. K. German 08/2016

% Inputs 
% d - input grid positions and displacmets
% d.x - grid x-positions
% d.y - grid y-positions
% d.dx - x displacments
% d.dy - y-displacements
% Note, the center of the grid coicides with the center of the sample.

%Outputs
% d.r_inc - radial positions
% d.azi_d - azimuthally averaged azimuthal displacment
% d.azi_sd - azimuthally averaged azimuthal displacment standard deviation
% d.rad_d - azimuthally averaged radial displacment
% d.rad_sd - azimuthally averaged radial displacment standard deviation

% Code associated with journal article 'Measuring and modeling contractile
% drying in human stratum corneum' by X. Liu and G. K. German for the Journal
% of Visualized Experiments 
% August 15 2016

magd =(sqrt(d.dx.^2+d.dy.^2));
ori_disp = atan2(d.dy,d.dx);
ori_pos = atan2((d.y),(d.x));
ori_diff_d = (ori_pos)-(ori_disp);
rd= (magd.*cos(ori_diff_d));% rad displacement
ad = (magd.*sin(ori_diff_d)); % azi displacement
% Separation by radial position
r_pos_s = sqrt(d.x.^2 +d.y.^2);
num2=round(length(unique((r_pos_s)))/10);% number of radial positions
r_step = round(max(max(r_pos_s))/num2);
ii=1;
for r=r_step:r_step:max(max(r_pos_s));
    r_incval = (r_pos_s(r_pos_s >= (r-r_step) & r_pos_s <= (r + r_step)));     
    azi_dval = (ad(r_pos_s >= (r-r_step) & r_pos_s <= (r + r_step)));
    rad_dval = (rd(r_pos_s >= (r-r_step) & r_pos_s <= (r + r_step))); 
d.r_inc(ii,1) = mean(r_incval(~isnan(r_incval))); 
d.azi_d(ii,1) = mean(azi_dval(~isnan(azi_dval))); %azimuthally averaged azimuthal displacements
d.azi_sd(ii,1) = std(azi_dval(~isnan(azi_dval))); %azimuthally averaged azimuthal displacement standard deviations
d.rad_d(ii,1) = mean(rad_dval(~isnan(rad_dval))); %azimuthally averaged radial displacements
d.rad_sd(ii,1) = std(rad_dval(~isnan(rad_dval))); %azimuthally averaged radial displacement standard deviations
    ii=ii+1;
end

end
 