function [maxima_u,maxima_rms] = peakdetect(in_w,range)%,in_x,in_y,in_z,range)
% helper function:
        % function [maxima, bigwin_mean, bigwin_std] = maxfinder(data,...
        % ... range,bigwin,bigstep,smallwin,smallstep,min_level,threshold)

%----------------------------- Time domain, amplitude (u) processing ------
    
bigwin = 1000;    % size of window used for averaging in samples (5000,500 worked fine)
smallwin = 40;
bigstep = 500;   % offset in samples of subsequent windows
smallstep = 40;
threshold = 3;
min_peak = -30;   % min dB re max. to consider for peak detection

if nargin < 2                   
    siz = wavread(in_w,'size');  % set range to whole file if not specified
    range = [1,siz(1)];
end;

% Reading files
[W,fs,bit] = wavread(in_w,range); % currently all attributes _assumed_ to be the same
% X = wavread(in_x,range);
% Y = wavread(in_y,range);
% Z = wavread(in_z,range);

% find maxima in original signal
[maxima_u, bigwin_mean, bigwin_std] = maxfinder(W,range,bigwin,bigstep,smallwin,smallstep,min_peak,threshold);

%------------------------------ Time domain, RMS processing ---------------


% calculate RMS values over small window
rms = []; q = 1; 
rmswin = 20; 
rmsstep = 20;
for p=range(1) : rmsstep : range(2)-rmswin
    rms(q) = sqrt(mean(W(p : p+rmswin).^2));     
    q = q + 1;
end

% find maxima in RMS values
% bigwinr = 5000;   
% smallwinr = 50;
% bigstepr = 2500;  
% smallstepr = 7;
% thresholdr = 2.5;
% min_peakr = -26;
bigwinr = 5000;   
smallwinr = 5;
bigstepr = 2500;  
smallstepr = 2;
thresholdr = 3;
min_peakr = -26;
[maxima_rms, stdev_rms] = maxfinder(rms,[1,length(rms)],bigwinr,bigstepr,smallwinr,smallstepr,min_peakr,thresholdr);

plot(W); hold on;
xlim([3400,8000]);
plot(range(1) : rmsstep : range(2)-rmswin,rms,'r','LineWidth',2);

plot(range(1) : bigstep : range(2)-bigwin,bigwin_std,'k','LineWidth',2);

plot(maxima_u,W(maxima_u),'o','MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',6);
plot(maxima_rms.*rmsstep-rmswin ,rms(maxima_rms),'o','MarkerEdgeColor','k','MarkerFaceColor','r','MarkerSize',6);
%plot(1 : bigstepr : length(rms)-bigwinr,stdev_rms,'g','LineWidth',2);
hold off;

%peaks = maxima_u;
end