function time_domain_rand_feat = pattern_time_feat(ecg,Fs)

% 
% Copyright (C) 2017 
% Shreyasi Datta
% Chetanya Puri
% Ayan Mukherjee
% Rohan Banerjee
% Anirban Dutta Choudhury
% Arijit Ukil
% Soma Bandyopadhyay
% Rituraj Singh
% Arpan Pal
% Sundeep Khandelwal
% 
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

ecg = zscore(ecg);
[~,locs_max] = findpeaks(ecg);
[~,locs_min] = findpeaks(-ecg);
locs = [locs_max(:);locs_min(:)];
if (min(locs_max)<min(locs_min)) % maxima detected first
    new_locs_min=[];
    for ji=1:length(locs_max)
        new_locs_min = [new_locs_min;locs_min(find(locs_min>locs_max(ji),1,'first'))];
    end
    if (length(new_locs_min) < length(locs_max))
        duo = [locs_max(1:length(new_locs_min)) new_locs_min ];
    else
        duo = [ locs_max new_locs_min(1:length(locs_max))];
    end
else
    new_locs_max=[];
    for ji=1:length(locs_min)
        new_locs_max = [new_locs_max;locs_max(find(locs_max>locs_min(ji),1,'first'))];
    end
    if (length(locs_min)<length(new_locs_max))
        duo = [locs_min new_locs_max(1:length(locs_min))];
    else
        duo = [locs_min(1:length(new_locs_max)) new_locs_max];
    end
end
 a=duo(:,2)-duo(:,1);
% a=diff(locs_max);
xvalues = unique(a);%[0:2:50 inf];
[x,y]=hist(a,xvalues);
xa=x./sum(x);
t1=find(y<11/300*Fs,1,'first');
t2=find(y>=11/300*Fs,1,'first');
%  bar(sort(a));
% [length(ecg)/Fs*5]
%     time_domain_rand_feat(iter,2) = sum(xa(t1:t2));
time_domain_rand_feat1 = sum(xa(1:t1));
time_domain_rand_feat2 = sum(xa(t2:end));
time_domain_rand_feat = [time_domain_rand_feat1 time_domain_rand_feat2];