function varargout = Res_DomTempo(varargin)
% RES_DOMTEMPO M-file for Res_DomTempo.fig
%      RES_DOMTEMPO, by itself, creates a new RES_DOMTEMPO or raises the existing
%      singleton*.
%
%      H = RES_DOMTEMPO returns the handle to a new RES_DOMTEMPO or the handle to
%      the existing singleton*.
%
%      RES_DOMTEMPO('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RES_DOMTEMPO.M with the given input arguments.
%
%      RES_DOMTEMPO('Property','Value',...) creates a new RES_DOMTEMPO or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Res_DomTempo_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Res_DomTempo_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Res_DomTempo

% Last Modified by GUIDE v2.5 26-Sep-2005 18:02:09

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Res_DomTempo_OpeningFcn, ...
                   'gui_OutputFcn',  @Res_DomTempo_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Res_DomTempo is made visible.
function Res_DomTempo_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Res_DomTempo (see VARARGIN)

% Choose default command line output for Res_DomTempo
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Res_DomTempo wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Res_DomTempo_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes during object creation, after setting all properties.
function SDNN_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SDNN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function SDNN_Callback(hObject, eventdata, handles)
% hObject    handle to SDNN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of SDNN as text
%        str2double(get(hObject,'String')) returns contents of SDNN as a double


% --- Executes during object creation, after setting all properties.
function mNN_CreateFcn(hObject, eventdata, handles)
% hObject    handle to mNN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function mNN_Callback(hObject, eventdata, handles)
% hObject    handle to mNN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of mNN as text
%        str2double(get(hObject,'String')) returns contents of mNN as a double


% --- Executes during object creation, after setting all properties.
function mHR_CreateFcn(hObject, eventdata, handles)
% hObject    handle to mHR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function mHR_Callback(hObject, eventdata, handles)
% hObject    handle to mHR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of mHR as text
%        str2double(get(hObject,'String')) returns contents of mHR as a double


% --- Executes during object creation, after setting all properties.
function sdHR_CreateFcn(hObject, eventdata, handles)
% hObject    handle to sdHR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function sdHR_Callback(hObject, eventdata, handles)
% hObject    handle to sdHR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of sdHR as text
%        str2double(get(hObject,'String')) returns contents of sdHR as a double


% --- Executes during object creation, after setting all properties.
function SDANN_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SDANN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function SDANN_Callback(hObject, eventdata, handles)
% hObject    handle to SDANN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of SDANN as text
%        str2double(get(hObject,'String')) returns contents of SDANN as a double


% --- Executes during object creation, after setting all properties.
function RMSSD_CreateFcn(hObject, eventdata, handles)
% hObject    handle to RMSSD (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function RMSSD_Callback(hObject, eventdata, handles)
% hObject    handle to RMSSD (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of RMSSD as text
%        str2double(get(hObject,'String')) returns contents of RMSSD as a double


% --- Executes during object creation, after setting all properties.
function SDNNind_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SDNNind (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function SDNNind_Callback(hObject, eventdata, handles)
% hObject    handle to SDNNind (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of SDNNind as text
%        str2double(get(hObject,'String')) returns contents of SDNNind as a double


% --- Executes during object creation, after setting all properties.
function SDSD_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SDSD (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function SDSD_Callback(hObject, eventdata, handles)
% hObject    handle to SDSD (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of SDSD as text
%        str2double(get(hObject,'String')) returns contents of SDSD as a double


% --- Executes during object creation, after setting all properties.
function NN50_CreateFcn(hObject, eventdata, handles)
% hObject    handle to NN50 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function NN50_Callback(hObject, eventdata, handles)
% hObject    handle to NN50 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of NN50 as text
%        str2double(get(hObject,'String')) returns contents of NN50 as a double


% --- Executes during object creation, after setting all properties.
function pNN50_CreateFcn(hObject, eventdata, handles)
% hObject    handle to pNN50 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function pNN50_Callback(hObject, eventdata, handles)
% hObject    handle to pNN50 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of pNN50 as text
%        str2double(get(hObject,'String')) returns contents of pNN50 as a double


% --- Executes during object creation, after setting all properties.
function HRVind_CreateFcn(hObject, eventdata, handles)
% hObject    handle to HRVind (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function HRVind_Callback(hObject, eventdata, handles)
% hObject    handle to HRVind (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of HRVind as text
%        str2double(get(hObject,'String')) returns contents of HRVind as a double


% --- Executes during object creation, after setting all properties.
function TINN_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TINN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function TINN_Callback(hObject, eventdata, handles)
% hObject    handle to TINN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of TINN as text
%        str2double(get(hObject,'String')) returns contents of TINN as a double


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%global cab exame Fam picosR RR NN NNi tNN Fitp opFFT opAR opDT iVLF fVLF iLF fLF iHF fHF cFFT inicioNN FimNN segNN
global tRR RR
%keyboard;
isRR=1;
indexsRR=1;
lsRR = min(500,length(RR));
fsRR=isRR+lsRR-1;

fileID = fopen('Result - HRV Metrics.txt','w');
keyboard;
ncount = 1;

media_mNN=0;
media_mHR = 0;
media_SDNN = 0;
media_sdHR=0;
media_SDANN=0;
media_SDNNindex=0;
media_RMSSD=0;
media_SDSD=0;
media_NN5=0;
media_pNN5=0;
media_HRVindex=0.
media_TINN=0;

while fsRR <= length(RR)
q=[];
D=[];
MRes=[];
vminl=[];
pminl=[];
segNN=RR(isRR:fsRR);
mNN = mean(segNN);
%set(handles.mNN,'String',num2str(mNN));
sHR = 60./segNN;
mHR = mean(sHR);
%set(handles.mHR,'String',num2str(mHR));
SDNN = std(segNN);
%set(handles.SDNN,'String',num2str(SDNN));
sdHR = std(sHR);
%set(handles.sdHR,'String',num2str(sdHR));
somaNN = 0;
mANN = 0;
cANN = 0;
iANN = 1;
devANN = 0;
for cNN = 1:length(segNN)
    somaNN = somaNN + segNN(cNN);
    if somaNN > 300
        cANN = cANN + 1;
        mANN(cANN) = mean(segNN(iANN:cNN));
        devANN(cANN) = std(segNN(iANN:cNN));
        somaNN = 0;
        iANN = cNN+1;
    end
end
if cANN >= 1
    SDANN = std(mANN);
    SDNNindex = mean(devANN);
else SDANN = 0;
     SDNNindex = 0;
end
%set(handles.SDANN,'String',num2str(SDANN));
%set(handles.SDNNind,'String',num2str(SDNNindex));
dNN = segNN(2:end)-segNN(1:end-1);
mqdNN = sum(dNN.*dNN)/length(dNN);
RMSSD = sqrt(mqdNN);
%set(handles.RMSSD,'String',RMSSD);
SDSD = std(dNN);
%set(handles.SDSD,'String',num2str(SDSD));
[n5 v5] = find(abs(dNN)>0.005);
NN5 = length(v5);
pNN5 = NN5/length(segNN);
%set(handles.NN50,'String',num2str(NN5));
%set(handles.pNN50,'String',num2str(pNN5*100));
%set(handles.nbat,'String',num2str(length(segNN)-1));
%bin = 1/128;
bin = 1/1000;
nbar = (max(segNN)-min(segNN))/bin;
[HNN,X] = hist(segNN,nbar);
HRVindex = length(segNN)/max(HNN);
%set(handles.HRVind,'String',num2str(HRVindex));
%% Obtençao da medida TINN %%
pXmax = find(HNN == max(HNN));
Xmax = X(pXmax(1));
Ymax = max(HNN);
%viq = linspace(0,Xmax-bin,100);
viq = (0.7)*min(X):bin:Xmax;
%vfq = linspace(Xmax+bin,2*max(X),100);
vfq = Xmax:bin:1.2*max(X);
iq = viq(1);
fq = vfq(1);

areta1 = Ymax/(Xmax-iq);
breta1 = -iq*areta1;
m1H = HNN(1:pXmax);
eixoX = (0.7)*min(X):bin:1.2*max(X);
for c1 = 1:length(eixoX)
    vD = find(abs(X-eixoX(c1)) == min( abs( (X-eixoX(c1)) )));
    if abs(eixoX(c1) - X(vD)) >bin
        D(c1) = 0;
        
    else D(c1) = HNN(vD);
         
    end
    
end

for c1 = 1:length(eixoX)
    if eixoX(c1) < iq | eixoX(c1) > fq
        q(c1) = 0;
    else if eixoX(c1) <= Xmax 
             q(c1) = ((Ymax)/(Xmax - iq))*eixoX(c1) - iq*((Ymax)/(Xmax - iq));
         else q(c1) = ((Ymax)/(Xmax - fq))*eixoX(c1) - fq*((Ymax)/(Xmax - fq));
         end
     end
 end
 
 MRes(1,1) = sum( ((D-q).^2)*bin );
 
 for c2 = 1:length(viq)
     for c3 = 1:length(vfq)
         iq = viq(c2);
         fq = vfq(c3);
         for c4 = 1:length(eixoX)
            if eixoX(c4) < iq | eixoX(c4) > fq
                q(c4) = 0;
            else if eixoX(c4) <= Xmax 
                    q(c4) = ((Ymax)/(Xmax - iq))*eixoX(c4) - iq*((Ymax)/(Xmax - iq));
                else q(c4) = ((Ymax)/(Xmax - fq))*eixoX(c4) - fq*((Ymax)/(Xmax - fq));
                end
            end
        end
 
        MRes(c2,c3) = sum( ((D-q).^2)*bin );
    end
    
      
end
c4=c2;
for c2 = 1:c4
    linha = MRes(c2,:);
    vminl(c2) = min(linha);
    pminl (c2) = find(linha == min(linha));
end

N = find(vminl == min(vminl));
M = pminl(N);
N = viq(N);
M = vfq(M);
TINN = M-N;
% axes(handles.axHNN);
% 
% hist(segNN,nbar);
% xlabel('Duraçao de intervalos NN');
% ylabel('Numero de NNs');
% hold on;


 for c4 = 1:length(eixoX)
            Np = find(vminl == min(vminl));
            iq = viq(Np);
            Mp = pminl(Np);
            fq = vfq(Mp);
            if eixoX(c4) < iq | eixoX(c4) > fq
                q(c4) = 0;
            else if eixoX(c4) <= Xmax 
                    q(c4) = ((Ymax)/(Xmax - iq))*eixoX(c4) - iq*((Ymax)/(Xmax - iq));
                else q(c4) = ((Ymax)/(Xmax - fq))*eixoX(c4) - fq*((Ymax)/(Xmax - fq));
                end
            end
 end
%         keyboard;
        MRes(c2,c3) = sum( ((D-q).^2)*bin );
%         figure;
        if length(eixoX) ~= length(q)
            keyboard;
        end
        plot(eixoX,q,'r');
%         pause;
 hold off;
%axis([N-0.050 M+0.050 0 1.5*max(HNN)]);
%set(handles.TINN,'String',num2str(TINN));
%axes(handles.axHHR);

% hist(sHR,nbar);
% xlabel('RC (bat/min)');
% ylabel('Numero de batimentos');

isRR = isRR+round(lsRR/2);
fsRR=isRR+lsRR-1;
indexsRR=indexsRR+1;
% disp('Avance para o proximo segmento!');
% disp(indexsRR);
%keyboard;

fprintf(fileID,['mNN: ' num2str(mNN) '\r\n']);
fprintf(fileID,['mHR: ' num2str(mHR) '\r\n']);
fprintf(fileID,['SDNN: ' num2str(SDNN),'\r\n']);
fprintf(fileID,['sdHR: ' num2str(sdHR),'\r\n']);
fprintf(fileID,['SDANN: ' num2str(SDANN),'\r\n']);
fprintf(fileID,['SDNNindex: ' num2str(SDNNindex),'\r\n']);
fprintf(fileID,['RMSSD: ' num2str(RMSSD),'\r\n']);
fprintf(fileID,['SDSD: ' num2str(SDSD),'\r\n']);
fprintf(fileID,['NN5: ' num2str(NN5),'\r\n']);
fprintf(fileID,['pNN5: ' num2str(pNN5*100),'\r\n']);
fprintf(fileID,['Num. intervalos: ' num2str(length(segNN)-1),'\r\n']);
fprintf(fileID,['HRVindex: ' num2str(HRVindex),'\r\n']);
fprintf(fileID,['TINN: ' num2str(TINN),'\r\n']);

ncount=ncount+1;

media_mNN=media_mNN+mNN;
media_mHR=media_mHR+mHR;
media_SDNN=media_SDNN+SDNN;
media_sdHR=media_sdHR+sdHR;
media_SDANN=media_SDANN+SDANN;
media_SDNNindex=media_SDNNindex+SDNNindex;
media_RMSSD=media_RMSSD+RMSSD;
media_SDSD=media_SDSD+SDSD;
media_NN5=media_NN5+NN5;
media_pNN5=media_pNN5+pNN5;
media_HRVindex=media_HRVindex+HRVindex;
media_TINN=media_TINN+TINN;




end

fprintf(fileID,['media mNN: ' num2str(media_mNN/(ncount-1)) '\r\n']);
fprintf(fileID,['media mHR: ' num2str(media_mHR/(ncount-1)) '\r\n']);
fprintf(fileID,['media SDNN: ' num2str(media_SDNN/(ncount-1)),'\r\n']);
fprintf(fileID,['media sdHR: ' num2str(media_sdHR/(ncount-1)),'\r\n']);
fprintf(fileID,['media SDANN: ' num2str(media_SDANN/(ncount-1)),'\r\n']);
fprintf(fileID,['media SDNNindex: ' num2str(media_SDNNindex/(ncount-1)),'\r\n']);
fprintf(fileID,['media RMSSD: ' num2str(media_RMSSD/(ncount-1)),'\r\n']);
fprintf(fileID,['media SDSD: ' num2str(media_SDSD/(ncount-1)),'\r\n']);
fprintf(fileID,['media NN5: ' num2str(media_NN5/(ncount-1)),'\r\n']);
fprintf(fileID,['media pNN5: ' num2str(media_pNN5*100/(ncount-1)),'\r\n']);
fprintf(fileID,['media HRVindex: ' num2str(media_HRVindex/(ncount-1)),'\r\n']);
fprintf(fileID,['media TINN: ' num2str(media_TINN/(ncount-1)),'\r\n']);

fclose(fileID);         
keyboard;         
         
         
         

 
             






        
    



% --- Executes during object creation, after setting all properties.
function nbat_CreateFcn(hObject, eventdata, handles)
% hObject    handle to nbat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end



function nbat_Callback(hObject, eventdata, handles)
% hObject    handle to nbat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of nbat as text
%        str2double(get(hObject,'String')) returns contents of nbat as a double


