function [s R_peaks Q_peaks S_peaks] = Calc_slopes(signal,I,status)
% [s R_peaks Q_peaks S_peaks] = Calc_slopes(signal,I,status)
%
% Input Variables
%   signal - The signal
%   I - The position of the Peaks
%   status - min or max
% Output Variables
%   s - the set of all slopes
%   R_peaks - The set of R peaks
%   Q_peaks - The set of Q peaks
%   S_peaks - The set of S peaks
%
% Description
%   Determines the Slopes and QRS peaks in a signal.
% Created
%   8/23/2006, Mohamed A Mneimneh, Marquette University
%
% This software is released under the terms of the GNU General
% Public License (http://www.gnu.org/copyleft/gpl.html).
% Modified

count = 1;

visited = ones(size(I));
for i = 1:length(I)-1
    s(i) = (signal(I(i+1)) - signal(I(i)))/(I(i+1)-I(i));
end
for i = 2:length(I)-2
     if ( abs(s(i)) > max(abs(s(3:end-2)))*0.3 )
        if ( count > 1 && R_peaks(count-1) == I(i-1) )
            if ((abs(s(i)) >abs(s(i-1)) || abs(s(i)) >abs(s(i-2)) || ~visited(count-1) || abs(s(i))>abs(s(i-1))*0.51 ))
                Q_peaks(count-1) = I(i-1);
                R_peaks (count-1) =I(i);
                S_peaks(count -1) = I(i+1);
                pb_status(count-1) = status(i);
                visited(count-1) = 1;
            end
        elseif (abs(s(i))  > max( s(find(sign(s(2:end-2)) == sign(s(i)))) )*0.471 )
            if i > 1
                Q_peaks(count) = I(i-1);
            else
                Q_peaks(count) = -1;
            end
            visited(count) = 0;
            R_peaks (count) =I(i);
            S_peaks(count ) = I(i+1);
            pb_status(count) = status(i);
            count = count + 1;

        end
    end
end

if (length(pb_status) > 0 )
    [pb_0 pb_1] = Calc_Pb(pb_status);


    %
    for i = 1:length(R_peaks)-1

        if (pb_0 > pb_1)
            if pb_status(i) ~= 0 && pb_status(i+1) == 0
                Q_peaks(i) = Q_peaks(i+1);
                R_peaks (i) =R_peaks(i+1);
                S_peaks(i) = S_peaks(i+1);
            end
        else
            if pb_status(i) ~= 1 && pb_status(i+1) == 1
                Q_peaks(i) = Q_peaks(i+1);
                R_peaks (i) =R_peaks(i+1);
                S_peaks(i) = S_peaks(i+1);
            end
        end

    end

    if (pb_0 > pb_1)

        if pb_status(length(R_peaks)) ~= 0
            Q_peaks = Q_peaks(1:length(Q_peaks)-1);
            R_peaks  =R_peaks(1:length(R_peaks)-1);
            S_peaks = S_peaks(1:length(S_peaks)-1);
        end
    else
        if pb_status(length(R_peaks)) ~= 1
            Q_peaks = Q_peaks(1:length(Q_peaks)-1);
            R_peaks  =R_peaks(1:length(R_peaks)-1);
            S_peaks = S_peaks(1:length(S_peaks)-1);
        end
    end
end