function [dmp, pksh] = peakAlignAv(piks, spa, hw)
%
% OUTPUT:
%
% dmp - data matrix of aligned peak intensities (dim = peaks x samples)
% pksh - matrix of applied peak position shifts (dim = peaks x samples);
%
% INPUT:
% peaks - peak positions from the average spectrum;
% spa - array of columns of resampled spectra (time x samples);
% hw - peak half-width (window for alignment) -- constant for resampled data;
%
% USAGE:
% [dmp, pksh] = peakAlignAv(piks, spa, hw);
% Dependency: none
%
%
lpik = length(piks);
sz = size(spa);
dmp = zeros(lpik, sz(2));
pksh = dmp;
for i=1:lpik
for j=1:sz(2) % samples
w=spa((piks(i)-hw):(piks(i)+hw), j);
[mw, imw]=max(w);
x = diff(w); % first difference
xl = x(1:end-1); % left side
xr = x(2:end); % right side
neartop = (xl > 0 & xr <= 0) | (xl == 0 & xr < 0);
xx = 1:length(x);
nt = xx(neartop)+1; % tentative maximum
if length(nt)>0
if length(nt)>1
[y,iy]=max(w(nt));
dmp(i,j)=y;
pksh(i,j)=nt(iy)-hw-1;
else
dmp(i,j)=w(nt);
pksh(i,j)=nt-hw-1;
end;
else
if abs(imw-hw-1) < hw
dmp(i,j) = mw;
pksh(i,j)=imw-hw-1;
else
dmp(i,j)=spa(piks(i),j);
pksh(i,j)=0;
end;
end;
end;
end;
return;