function [maxima_u] = peakdetect(in_data,threshold,min_peak,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 = 2000;    % size of window used for averaging in samples (5000,500 worked fine)
smallwin = 50;   %500
bigstep = 2000;   % offset in samples of subsequent windows
smallstep = 50;  %500
%threshold = 4.5;
%min_peak = -70;   % min dB re max. to consider for peak detection

if nargin < 4                   
    %siz = wavread(in_w,'size');  % set range to whole file if not specified
    range = [1,length(in_data)];
    if nargin < 3
        min_peak = -70;
        if nargin < 2
            threshold = 4.5;
        end
    end
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] = maxfinder2(in_data,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 = 2.5;
% % min_peakr = -30;
% bigwinr = 4000;   
% smallwinr = 50;
% bigstepr = 4000;  
% smallstepr = 30;
% thresholdr = 1;
% min_peakr = -40; %!!!!! was -40
% 
% [maxima_rms, stdev_rms] = maxfinder(rms,[1,length(rms)],bigwinr,bigstepr,smallwinr,smallstepr,min_peakr,thresholdr);

%------------------------------ Plotting----------------------------------
% plot(linspace(0,length(in_data)/fs,length(in_data)),in_data); hold on;
plot(in_data); hold on;

%plot((range(1) : rmsstep : range(2)-rmswin)/fs,rms,'r','LineWidth',2);

% plot(range(1) : bigstep : range(2)-bigwin,bigwin_std,'k','LineWidth',2);
% plot(range(1) : bigstep : range(2)-bigwin,bigwin_mean,'r','LineWidth',2);
plot(bigwin_mean+threshold*bigwin_std,'k','LineWidth',2);
%plot(bigwin_mean,'r','LineWidth',2);


plot(maxima_u,in_data(maxima_u),'o','MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',6);
%plot((maxima_rms.*rmsstep-rmswin)/fs ,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;
%xlim([0,0.5]);
ylim([0,2e-4]);
xlabel('minta');
ylabel('Rel. ampl.');
end