function [cut_signal] = get_Beat(filename,start,stop,channel)
% [cut_signal] = get_Beat(filename,start,stop,channel)
%
% Input Variables
%   filename - Record Name
%   start - starting point
%   stop - End point
%   channel - 
% 
% Output Variables
%   cut_signal- The One beat
%
% Description
%   Takes one Beat from the ECG 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).
%

cmd2 = ['ecgpuwave -r ' filename ' -a atr' ];
system(cmd2);

cmd2 = ['rdann -r ' filename ' -a atr' ];
[status, rrString]  = system(cmd2);



if status == 0
    count = 1;
    for i = 1:43:length(rrString)
        j = i+ 42;
        blabla(count,:) = rrString(i+13:j);
        count = count +1;
    end
    cmd = ['rdsamp -r ' filename ];
    cmd = [cmd sprintf(' -s %u -f %12.3f -t %12.3f', channel-1 , start, stop)];
    [status, rrString] = system(cmd);

    if status == 0
        signal(:,1) = sscanf(rrString, '%*d %d', inf);
    else
        error('Couldn''t extract signal.');
    end %if
    t = 1:length(signal);
    t=t.*1e-3;

    count = 0;
    count1 = 1;
    Q_on_al = 0;
    T_off_al = 0;
    for i = 1:length(blabla)-3
        %check for the first QRS
        if ( blabla(i,14) == '(' )
            switch (  blabla(i+1,14) )
                case 'N'
                    %check if there is a  wave detected in the same
                    %cycle
                    if i > 3 && str2num(blabla(i,1:8)) < stop*1e3-51 && count >= 0 && i+4 < length(blabla) && blabla(i+4,14) == 't' &&  blabla(i-2,14) == 'p'
                        count =1;
                        %if a T-wave is detected select the current
                        %signal
                        P_on_al = str2num(blabla(i-3,1:8));
                        P_peaks_al = str2num(blabla(i-2,1:8));
                        P_off_al = str2num(blabla(i-1,1:8));

                        Q_on_al = str2num(blabla(i,1:8));
                        R_peaks_al = str2num(blabla(i+1,1:8));
                        Q_off_al = str2num(blabla(i+2,1:8));

                        T_on_al = str2num(blabla(i+3,1:8));
                        T_peaks_al = str2num(blabla(i+4,1:8));
                        T_off_al = str2num(blabla(i+5,1:8));
                        
                        X_on = P_on_al-50;
                        X_off = T_off_al+50;

                        Y_on =  signal(X_on,1);
                        Y_off = signal(X_off,1) ;

                        slope(count1) = (Y_off - Y_on)/(X_off-X_on);

                        if (abs(slope(count1)) < 0.1)
                            V_on  = X_on;
                            V_off = X_off;
                            break;
                        end
                        count1 = count1 + 1;
                    end
            end
            i = i +2;
        end
    end
end
cut_signal = signal(X_on:X_off);
