% function [RR]=Processa_ECGs_Ratos_v7(filename)
% global escala Fam sfreq anot ECG IBB limiar picos_R m0 On Off Tp Te
% global mediaIntervalo desvioIntervalo tipo
% global Se Pr Der FN FP TP QRSver pproc
% global nrotFP nrotFPc1 nrotFPc2 nrotFPc3
% global MetricaTeste m1FPc1 m2FPc1 EscalaSel
% global Nbatmin Nbatmax FPlimiarEscala kernelx vetor_eg

signal = abfload(filename);
signal = signal';
sfreq = 10000;
Fam = sfreq;
%signal = signal(1:15*sfreq);
%figure;plot((1:length(signal))/sfreq,signal);
kernelx = [];
vetor_eg = [];
% [fp_QRS,EscalaSel] = Det_QRS_H(signal,2);
% hold on;
% plot(fp_QRS/sfreq,signal(fp_QRS),'ro');
% RR = fp_QRS(2:end) - fp_QRS(1:end-1);
% figure;plot(RR/sfreq);

MM = 999;
at = (MM-1)/2;
for i=1:length(signal)
    inicio = max(1,i-at);
    fim = min(length(signal),i+at);
    mmNN(i) = mean(signal(inicio:fim));
end


signalmm = signal-mmNN;
signal = signalmm;
keyboard;


exameft = signal;

Fam = sfreq;
M1_f = exameft;%(1,1:end);
%M1 = M1';

Mfilt_f = [];
MNfilt_f = [];
ref_RR1_f = [];hist_Dur_QRS_f = [];
%[Nder,Nsamp]=size(M1);
Nsamp = length(M1_f);
SampIni = 1;

Tbloco = 0.5*sfreq;

Hist_Medias_R_f = [];
Hist_Medias_On_f = [];
Hist_Medias_On2_f = [];
Hist_Medias_Off_f = [];
Hist_Medias_Off2_f = [];

Hist_MatrizTp_f = [];
Hist_MatrizTe_f = [];
Hist_MatrizTi_f = [];

Hist_MatrizPp_f = [];
Hist_MatrizPe_f = [];
Hist_MatrizPi_f = [];

Hist_Medias_Ppvs_f = [];
Hist_Medias_Pinivs_f = [];
Hist_Medias_Pendvs_f = [];

Hist_Best_SD1_P = [];
Hist_Best_Alfa_P = [];
Hist_Erro_Min_SD_P = [];

Hist_Best_SD1_QRS = [];
Hist_Best_SD2_QRS = [];
Hist_Perc_Corte1 = [];
Hist_Perc_Corte2 = [];
Hist_Erro_Matching = [];


        


vetor_RR_f = [];

ref_RR_f = [];

gapi = 0;
gapf = round(0.050*sfreq);
ultbatseg1 = 0;
ultbatseg2 = 0;
ultOndaP = 0;

Niter = 0;

tic
while SampIni+Tbloco-1 <= Nsamp %+ round(sfreq/2)
    
    
    fimbloco = min(SampIni+Tbloco+gapf-1,Nsamp);
    if SampIni+Tbloco+gapf-1 > Nsamp
        
        gapf = 0;
        Tbloco = Nsamp - SampIni + 1;
    end
    %M = M1(:,SampIni-gapi:fimbloco);
    M_f = M1_f(SampIni-gapi:fimbloco);
    if SampIni+2*Tbloco-1 > Nsamp + gapf
        UltBloco = 1;
    else UltBloco = 0;
    end
        
    %[MIntmm_f,MPicosR_f,RR_f,VetorOn,VetorOff,Best_SD1_QRS,Best_SD2_QRS,Perc_Corte1,Perc_Corte2,Erro_Matching] = WavHilbFilt_Detecta_QRS_Experimento01(M_f,SampIni,Fam,Tbloco,gapi,gapf,ultbatseg1-SampIni+gapi,UltBloco,Niter);
    [MIntmm_f,MPicosR_f,RR_f] = WavHilbFilt_Detecta_QRS_Experimento01_v2(M_f,SampIni,Fam,Tbloco,gapi,gapf,ultbatseg1-SampIni+gapi,UltBloco,Niter);
    
        gapi = round(0.050*sfreq);
%     [dt1 dt2] = size(MNfilt_f);
%     [dt3 dt4] = size(MIntmm_f);
    MNfilt_f = [MNfilt_f MIntmm_f];
    
    NovosRs_f = MPicosR_f+SampIni-1;
    if length(NovosRs_f) == 0
        keyboard;
    else ultbatseg1 = NovosRs_f(1,end);
    end
    
    
    if length(RR_f) > 0
        Hist_Medias_R_f = [Hist_Medias_R_f MPicosR_f+SampIni-1];
        vetor_RR_f = [vetor_RR_f RR_f];
               
        ref_RR_f = [ref_RR_f MPicosR_f(1,2:end)+SampIni-1];
        
        
    end
    
       
    SampIni = SampIni+Tbloco;
    
    Tbloco = round(0.5*sfreq);
    %Niter = Niter+1
    
end
toc


M1m_f = MNfilt_f;% (1,:);

vetorR1_f = Hist_Medias_R_f(1,:);

figure;plot((1:length(signal))/sfreq,signal);hold on; plot(vetorR1_f/sfreq,signal(vetorR1_f),'ro');

RR = (vetorR1_f(2:end) - vetorR1_f(1:end-1))/sfreq;
figure;plot(vetorR1_f(2:end)/sfreq,RR);

keyboard;
tic
[New_vetorR,vetorOn,vetorOff,Best_SD1_QRS,Best_SD2_QRS,Vetor_Perc_Corte1,Vetor_Perc_Corte2,Erro_Match_QRS] = Busca_Melhor_Chapeu_Mexicano_Plot_v5(vetorR1_f,signal,sfreq);
figure;plot(Erro_Match_QRS);title('Erro Match');
figure;plot(Best_SD1_QRS);title('Best SD1');
figure;plot(Best_SD2_QRS);title('Best SD2');
figure;plot(Vetor_Perc_Corte1);title('Corte 1');
figure;plot(Vetor_Perc_Corte2);title('Corte 2');

save('Best_SD1_QRS','Best_SD1_QRS');
save('Best_SD2_QRS','Best_SD2_QRS');
save('New_vetorR','New_vetorR');
save('vetorOn','vetorOn');
save('vetorOff','vetorOff');
save('Vetor_Perc_Corte1','Vetor_Perc_Corte1');
save('Vetor_Perc_Corte2','Vetor_Perc_Corte2');
save('Erro_Match_QRS','Erro_Match_QRS');
%[New_vetorR,vetorOn,vetorOff,Best_SD1_QRS,Best_SD2_QRS,Vetor_Perc_Corte1,Vetor_Perc_Corte2,Erro_Match_QRS] = Busca_Melhor_Chapeu_Mexicano_v3(vetorR1_f,signal,sfreq,[min([Best_SD1_QRS Best_SD2_QRS]) max([Best_SD1_QRS Best_SD2_QRS])],[min([Vetor_Perc_Corte1 Vetor_Perc_Corte2]) max([Vetor_Perc_Corte1 Vetor_Perc_Corte2])]);
toc

figure;plot((1:length(signal))/sfreq,signal);hold on; plot(New_vetorR/sfreq,signal(New_vetorR),'ro');
plot(vetorOn/sfreq,signal(vetorOn),'ok');
plot(vetorOff/sfreq,signal(vetorOff),'og');
keyboard;
close all;
vetorT = [];
testevarQRS = (vetorOff-vetorOn)/sfreq;
maxdurQRS = max(testevarQRS);
Escalas = [1 2 3 4 5];
signalECG = signal;

for beat = 1:length(vetorOff)-1 % Início do processo de segmentação para cada batimento
    
   
    iW = beat;
    sW=signal(vetorOff(iW):vetorOn(iW+1));
    Win = sW;
    Input = Win;
    
    %% DECOMPOSIÇÃO MULTINÍVEL
    x = sW;
    N=5;
Signal=x;
DB='db10';
for i=1:N
    [A,D] = DECOMP(Signal,DB);
    Signal=A;
    cA{i,:}=A;
    cD{i,:}=D;
    SignalA=A;
    SignalD=D;

    for k=1:i
         Ar=RECON_A(SignalA,DB);
         Dr=RECON_D(SignalD,DB);
         SignalA=Ar;
         SignalD=Dr;
    end
    cAr{i,:}=Ar;
    cDr{i,:}=Dr;
    
end
%% AJUSTANTO TAMANHO DAS COMPONENTES DE APROXIMAÇÃO
for i=1:N
if length(cAr{i,:}) > length(x)
   Ajust=cAr{i,:};
   Ajust1{i,:}=Ajust(1:length(x));

else
 Ajust=cAr{i,:}; 
 Ajust1{i,:}=Ajust;
end 
end
cAr=Ajust1;

%% AJUSTANTO TAMANHO DAS COMPONENTES DE DETALHE
for i=1:N
if length(cDr{i,:}) > length(x)
   Ajust=cDr{i,:};
   Ajust1{i,:}=Ajust(1:length(x));

else
 Ajust=cDr{i,:}; 
 Ajust1{i,:}=Ajust;
end 
end
cDr=Ajust1;

%% PLOTANDO OS RESULTADOS DO PROCEDIMENTO DE RECUPERAÇÃO
% stA = sym('COMPONENTE_cAr', [1 N]);
% stD = sym('COMPONENTE_cDr', [1 N]);
% for i=1:N
%  strA{1,i}=char(stA(1,i));
%  strD{1,i}=char(stD(1,i));
% end

%figure;
xteste = cAr{4};
limt = 0.5*max(xteste);
ii = length(xteste)-1;
jj = ii;
pcrt = [];
while (ii > 1)
    if (xteste(ii) > xteste(ii-1)) && (xteste(ii) > xteste(ii+1))
        pcrt = [pcrt ii];
    end
    ii =ii-1;
end

refamp = -inf;
locpico = 0;
achei = 0;

while (achei == 0)
    for ii=1:length(pcrt)
        if xteste(pcrt(ii)) > refamp
            refamp = xteste(pcrt(ii));
            locpico = pcrt(ii);
        end
    end
    
    if refamp == -inf
        locpico = pcrt(round(length(pcrt)/2));
        Ppeak(beat) = locpico;
        ii=locpico;
        jj=locpico;
        achei=1;
        break;
    end
    
    if (locpico > round(0.030*sfreq)) && (locpico < length(xteste) - round(0.010*sfreq))
        Ppeak(beat) = locpico;
        ii=locpico;
        jj=locpico;
        achei=1;
        break;
    else xteste(locpico) = -inf;
        refamp = -inf;
    end
end
        


% while (ii > 1)
%     if (xteste(ii)) > limt
%         jj = ii;
%         while ((xteste(ii)) > limt)
%             ii = ii-1;
%         end
%         break;
%     end
%     ii = ii-1;
% end
% 
% Ppeak(beat) = find(xteste(ii:jj) == max(xteste(ii:jj)))+ii-1;

while (xteste(ii) > xteste(ii-1) || xteste(ii) > xteste(ii+1)) || xteste(ii) > 0.2*xteste(Ppeak(beat))
    ii = ii-1;
    if (ii == 1)
        break;
    end
end
if (ii==1)
    ii = locpico-10;
end
jj_ant=jj;
while (xteste(jj) > xteste(jj-1) || xteste(jj) > xteste(jj+1)) || xteste(jj) > 0.2*xteste(Ppeak(beat))
    jj = jj+1;
    if jj == length(xteste)
        break;
    end
end

if jj == length(xteste)
 jj=jj_ant;
 while (xteste(jj) > xteste(jj-1) || xteste(jj) > xteste(jj+1)) 
    jj = jj+1;
    if jj == length(xteste)
        break;
    end
 end
end
    

Pon(beat) = ii;
Poff(beat) = jj;

kpk = Ppeak(beat);
maxder = 0;
lim_inc = 0;
while kpk > ii
    if abs(xteste(kpk)-xteste(kpk-1)) > lim_inc
        lim_inc = abs(xteste(kpk)-xteste(kpk-1));
        maxder = kpk;
    end
    kpk=kpk-1;
end

kpk=maxder;
while kpk > ii
    if abs(xteste(kpk)-xteste(kpk-1)) < 0.20*lim_inc && xteste(kpk) < 0.2*xteste(Ppeak(beat))
        
        minder = kpk;
        break;
    end
    kpk=kpk-1;
end
Pon(beat) = minder;


kpk = Ppeak(beat);
maxder = 0;
lim_inc = 0;
while kpk < jj
    if abs(xteste(kpk)-xteste(kpk+1)) > lim_inc
        lim_inc = abs(xteste(kpk)-xteste(kpk+1));
        maxder = kpk;
    end
    kpk=kpk+1;
end

kpk=maxder;
while kpk < jj
    if abs(xteste(kpk)-xteste(kpk+1)) < 0.20*lim_inc && xteste(kpk) < 0.2*xteste(Ppeak(beat))
        
        minder = kpk;
        break;
    end
    kpk=kpk+1;
end
Poff(beat) = minder;

    

            

% for i=1:2*N
%     
% switch  rem(i,2)==0
%     case 0
% subplot(N,2,i);
% plot(cAr{((i+1)/2)});
% hold on;
% stt = cAr{((i+1)/2)};
% plot(Ppeak(beat),stt(Ppeak(beat)),'ro');
% plot(Pon(beat),stt(Pon(beat)),'ok');
% plot(Poff(beat),stt(Poff(beat)),'og');
% %title(strA{1,((i+1)/2)})
%     case 1
% subplot(N,2,i)
% plot(cDr{(i/2)})
% %title(strD{1,(i/2)})
% end    
% end

Ppeak(beat) = Ppeak(beat)+vetorOff(iW)-1;
Pon(beat) = Pon(beat)+vetorOff(iW)-1;
Poff(beat) = Poff(beat)+vetorOff(iW)-1;

%% PLOTANDO OS RESULTADOS DO PROCEDIMENTO DE DECOMPOSIÇÃO
% stA = sym('COMPONENTE_cA', [1 N]);
% stD = sym('COMPONENTE_cD', [1 N]);
% for i=1:N
%  strA{1,i}=char(stA(1,i));
%  strD{1,i}=char(stD(1,i));
% end

% figure;
% 
% for i=1:2*N
%     
% switch  rem(i,2)==0
%     case 0
% subplot(N,2,i);
% plot(cA{((i+1)/2)});
% %title(strA{1,((i+1)/2)})
%     case 1
% subplot(N,2,i)
% plot(cD{(i/2)});
% %title(strD{1,(i/2)})
% end    
% end
%keyboard;    


end

save('Ppeak','Ppeak');
save('Pon','Pon');
save('Poff','Poff');


 segPR = vetorOn(2:end)-Poff;
 intPR = vetorOn(2:end)-Pon;
 
 figure;plot(vetorOn(2:end)/sfreq,segPR/sfreq);
 figure;plot(vetorOn(2:end)/sfreq,intPR/sfreq);
 
figure;plot((1:length(signalECG))/sfreq,signalECG);hold on; plot(New_vetorR/sfreq,signalECG(New_vetorR),'ro');
plot(vetorOn/sfreq,signalECG(vetorOn),'ok');
plot(vetorOff/sfreq,signalECG(vetorOff),'ok');
plot(Ppeak/sfreq,signalECG(Ppeak),'ro');
plot(Pon/sfreq,signalECG(Pon),'ok');
plot(Poff/sfreq,signalECG(Poff),'ok');
keyboard;

%[New_R,On,Off,Best_SD1_QRS,Best_SD2_QRS,Perc_Corte1,Perc_Corte2,Erro_Matching,pmedio] = Busca_Melhor_Rayleigh1_Plot(PicoMapeado,sinal_ref,Fam);