      
%% interpolace systoly a pak uvidime


function Final_SV_GUI(data,fvz)

% clear all;clc;
%% nacteni dat ze souboru, osetrit vyjimky, treba kdyz je spatnej format, nacitaji se soubory .txt
% [filename pathname] = uigetfile({'*.txt';'*.csv'},'File Selector');
% 
%            if(filename==0)
%               msgbox('There is no file to load');
%               return;
%           end
%            
%           % rewriting initialized data
%           fullpathname = strcat(pathname,filename);      
%           data = load(fullpathname);
%           % defaultne nastavene hodnoty pro data od pacientu, nastavim si
%           % okna aby se to mohlo zmenit
%           fvz = 1000;
          HR = 65;

scrsz = get(0,'ScreenSize');   

% vytvoreni noveho okna pro zobrazeni segmentu

w_pwv = figure('Units','characters',...
            'HandleVisibility','callback',...
            'Renderer','painters',...
            'MenuBar','none', ...
            'numbertitle','off', ...
            'name','Cardiac Output', ...
            'Units','pixels', ... 
            'Position',[70 80 scrsz(3)/1.1 scrsz(4)/1.2]);
        
    %%    
% Okno rozdelene do 2 panelu

L_Panel_sirka = scrsz(3)/5;
L_Panel_vyska = scrsz(4)/1.2-10;
L_Panel_odsazeni = 10;

L_Panel = uipanel('BorderType','etchedin',...
		'Units','characters',...
		'Parent',w_pwv, ...
        'Title','Parameters', ...
        'Units','pixels', ...
		'Position',[L_Panel_odsazeni L_Panel_odsazeni L_Panel_sirka L_Panel_vyska],...
        'TitlePosition','centertop');
   
Podrobnosti_odsazeni = 10;
Podrobnosti_sirka = 2.6*L_Panel_sirka;
Podrobnosti_vyska = L_Panel_vyska;
    
Podrobnosti = uipanel('BorderType','etchedin',...
            'Units','characters',...
            'Parent',w_pwv, ...
            'Title','Graf', ...
            'Units','pixels', ...
            'Position', ...
            [3*Podrobnosti_odsazeni+L_Panel_sirka Podrobnosti_odsazeni Podrobnosti_sirka*1.3 Podrobnosti_vyska],...
            'TitlePosition','centertop'); 
        
 %% vytvoreni popisku a zadani vzdalenosti
 %% 
 % vytvoreni labelu a tlacitek pro nastaveni poctu vln, pro ktere budu delat vypocet CO
 nadpis_pocet_marks = uicontrol(L_Panel,'Style','text','String','Number of Waves for counting CO',...
                     'Units','pixels', ...
                     'Position',[15 scrsz(4)/1.4 L_Panel_sirka-30 20]);   

 
 create_marks = uicontrol('Style','pushbutton','String','Create marks',...
                          'Parent',L_Panel,...
                          'Position',[15 scrsz(4)/1.6 L_Panel_sirka-30 30],...
                          'Callback',{@create_Callback}); 
                      
delete_marks_button = uicontrol('Style','pushbutton','String','Delete marks',...
                          'Parent',L_Panel,...
                          'Position',[15 scrsz(4)/1.6-40 L_Panel_sirka-30 30],...
                          'Callback',{@delete_Callback});  

                            
set_pocet_marks = uicontrol(L_Panel,'Style','edit','String','2','Units','pixels', ...
                     'BackgroundColor','white','Callback',{@Pocet_Callback}, ...
                     'Position',[15 scrsz(4)/1.4-20 L_Panel_sirka-30 20]); 
                     
%%
% tady bude nastaveni srdecni frekvence anebo bude vypocet, kdyz to zrovna
% nebudu vedet

                 
    nadpis_time = uicontrol(L_Panel,'Style','text','String','Settings',...
                     'Units','pixels', ...
                     'Parent',L_Panel,...
                     'Position',[15 scrsz(4)/1.7-70 L_Panel_sirka-30 25]);
                 
    freq_set = uicontrol(L_Panel,'Style','edit','String','Sampling frequency',...
                     'Units','pixels', ...
                     'BackgroundColor','white',...
                     'Parent',L_Panel,...
                     'Enable', 'inactive',...
                     'Position',[15 scrsz(4)/1.7-100 L_Panel_sirka-30 25],...
                     'ButtonDownFcn', @clear);  
                 
    HR_set = uicontrol(L_Panel,'Style','edit','String','[beats/min]',...
                     'Units','pixels', ...
                     'BackgroundColor','white',...
                     'Parent',L_Panel,...
                     'Enable', 'inactive',...
                     'ButtonDownFcn', @clearHR,...
                     'Position',[15 scrsz(4)/1.7-130 L_Panel_sirka-30 25]);
                           
    set_button = uicontrol(L_Panel,'Style','pushbutton','String','SET',...
                          'Parent',L_Panel,...
                          'Position',[15 scrsz(4)/1.7-180 L_Panel_sirka-30 30],...
                          'Callback',{@set_Callback});       
                      
    checkbox_systole = uicontrol('Parent',L_Panel,'Style','checkbox','Value',1,'String','Systolic CO',...
                   'Units','pixels','Position',[15 scrsz(4)/1.7-220 L_Panel_sirka-30 20]);   
               
               
    checkbox_dicrotic = uicontrol('Parent',L_Panel,'Style','checkbox','Value',0,'String','Systole-Dicrotic CO',...
                   'Units','pixels','Position',[15 scrsz(4)/1.7-250 L_Panel_sirka-30 20]);                     
 %%
        
count_button = uicontrol('Style','pushbutton','String','Count CO',...
                          'Parent',L_Panel,...
                          'Position',[15 scrsz(4)/2-280 L_Panel_sirka-30 40],...
                          'Callback',{@count_Callback});   

nadpis_CO = uicontrol(L_Panel,'Style','text','String','CO [l/min]',...
                     'Units','pixels', ...
                     'Position',[15 scrsz(4)/2-325 L_Panel_sirka-30 20]);  
                      
set_CO = uicontrol(L_Panel,'Style','text','String','','Units','pixels', ...
                     'BackgroundColor','white', ...
                     'Position',[15 scrsz(4)/2-360 L_Panel_sirka-30 30]);                        
                 
                 
%% osa pro vykresleni nalezlych peaku

 axes_data = axes('Units','pixels','Position',[40 40 Podrobnosti_sirka*1.2,Podrobnosti_vyska-70], ...
                  'Parent',Podrobnosti);   
              
vlny = [];
systoles = [];

%%       

    %% funkce na zkouknuti inputu, jestli to jsou cisla
    
%     function myNumberCheck(ObjH, EventData)
%         S = get(, 'String');
%         % Exclude characters, which are accepted by sscanf:
%         S(ismember(S, '-+eEgG')) = ' ';
%         % Convert to one number and back to a string:
%         S2 = sprintf('%g', sscanf(S, '%g', 1));
%         set(ObjH, 'String', S2);
%         % Perhaps a small warning in WARNDLG or inside the GUI:
%         if ~all(ismember(S, '.1234567890'))
%     end
%      
%% vycisteni okno od popisku

    function clear(freq_set,~)

    set(freq_set, 'String', '', 'Enable', 'on');
    uicontrol(freq_set); % This activates the edit box and 
                   % places the cursor in the box,
                   % ready for user input.
    end
    

    function clearHR(HR_set,~)

    set(HR_set, 'String', '', 'Enable', 'on');
    uicontrol(HR_set); % This activates the edit box and 
                   % places the cursor in the box,
                   % ready for user input.
    end

%%

% nastaveni HR a frekvence vzorkovani
    function set_Callback(~,~)  
        
        %% kontrola cisel u HR
        S = get(HR_set, 'String');
        % Exclude characters, which are accepted by sscanf:
        S(ismember(S, '-+eEgG')) = '';
        % Convert to one number and back to a string:
        S2 = sprintf('%g', sscanf(S, '%g', 1));
        set(HR_set, 'String', S2);
        % Perhaps a small warning in WARNDLG or inside the GUI:
        if ~all(ismember(S, '.1234567890'))    
            msgbox('Insert a number, please');
            set(HR_set, 'String', '[beats/min]');
            set(HR_set,'Enable', 'inactive');
        else
            HR = str2double(get(HR_set,'String')); 
        end
        
        %% kontrola cisel u HR
        S = get(freq_set, 'String');
        % Exclude characters, which are accepted by sscanf:
        S(ismember(S, '-+eEgG')) = '';
        % Convert to one number and back to a string:
        S2 = sprintf('%g', sscanf(S, '%g', 1));
        set(freq_set, 'String', S2);
        % Perhaps a small warning in WARNDLG or inside the GUI:
        if ~all(ismember(S, '.1234567890'))    
             msgbox('Insert a number, please');
             set(freq_set, 'String', 'Sampling frequency');
             set(freq_set,'Enable', 'inactive');
        else
             fvz = str2double(get(freq_set,'String'));     
        end
                  
    end
    
%%
    function Pocet_Callback(~,~)  

    pocet = str2double(get(set_pocet_marks,'String')); 
    pocet_markru = pocet*3;
        
    end 
          

    m_wave = [];

% variables for marks
 pocet = 2;
 marks = [];
 marks_vypocty = [];
 i = 1;    
 time = (1/fvz:1/fvz:length(data)/fvz);
 pocet_markru = 6;
 PWV = 0;
 
 SV_rate_manz = 0;
 
 konst_posunu = fvz/25; %posun x vzorku od systoly pri systolickym CO, pri 1000 Hz jsem mel 30
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FUNCTIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% only plot the signals
% filtrace izolinie dle jine funkce, pouye linearni
%           for i=0:(pocet_systol-1)
%                 
%                     POM = data(round(marks(2*i+1)))-data(round(marks(2*i+3)));
%                     POM_ar = data_arter(round(marks_arter(2*i+1)))-data_arter(round(marks_arter(2*i+3)));
%                     POM2 = data(round(marks(2*i+3)))-data(round(marks(2*i+1)));
%                     POM2_ar = data_arter(round(marks_arter(2*i+3)))-data_arter(round(marks_arter(2*i+1)));
%                     
%                     if POM>0
%                         vector = fliplr((marks(2*i+1):marks(2*i+3)) - marks(2*i+1));
%                         vector_arter = fliplr((marks_arter(2*i+1):marks_arter(2*i+3)) - marks_arter(2*i+1));
%                         data((marks(2*i+1):marks(2*i+3))) = data(marks(2*i+1):marks(2*i+3))-vector'*(POM/length(vector));
%                         data_arter((marks_arter(2*i+1):marks_arter(2*i+3))) = data_arter(marks_arter(2*i+1):marks_arter(2*i+3))-vector_arter'*(POM_ar/length(vector_arter));
%                     else                    
%                         vector = (marks(2*i+1):marks(2*i+3)) - marks(2*i+1);
%                         data((marks(2*i+1):marks(2*i+3))) = data(marks(2*i+1):marks(2*i+3))-vector'*(POM2/length(vector));                        
%                         vector_arter = (marks_arter(2*i+1):marks_arter(2*i+3)) - marks_arter(2*i+1);
%                         data_arter((marks_arter(2*i+1):marks_arter(2*i+3))) = data_arter(marks_arter(2*i+1):marks_arter(2*i+3))-vector_arter'*(POM2_ar/length(vector_arter));
%                     end
% %                     length(data(marks(2*i+1):marks(2*i+3)));
% %                     data(marks(2*i+1):marks(2*i+3)) = data(marks(2*i+1):marks(2*i+3)) - f_y;
%             end

    function filtrace_izolinie()

             POM = data(1)-data(end);        
             vector = fliplr(1:length(data));
             data(1:end) = data(1:end)-vector'*(POM/length(vector));

    end

filtrace_izolinie;
zoom on;

plot_signals();

    function plot_signals()

            plot(axes_data,time,data);
            xlabel('t [s]');
            ylabel('amplituda [-]');
            zoom on;
            min_bound = 0;
            max_bound = length(data);

            %% showing the marks        
            if(~isempty(marks))
                          
                yLim = get(gca,'YLim');
                
                            for k=1:length(marks)
                                if(marks(k)>=min_bound && marks(k)<=max_bound)
                                    line([(marks(k)),(marks(k))],yLim,'Color','r');
                                end
                            end
                            
                            if(isempty(systoles)==0)
                                for k=1:length(systoles)
                                    systoles(k) 
                                    min_bound
                                    max_bound
                                    if(systoles(k)>=min_bound && systoles(k)<=max_bound)
                                        line([(systoles(k))/fvz,(systoles(k))/fvz],yLim,'Color','c');
                                    end
                                end
                            end
            end



    end

    

% then we have to do marks for every wave

%% choosing a place for a mark

    function create_Callback(source,eventdata)
 
         for i=1:pocet_markru
               switch rem(i,3)
                   case 1
                     msg = msgbox('Start of a SYSTOLE');
                     pause(1);
                     delete(msg);
                     [x,y] = ginput(1);        
                     marks(i) = round((x*1000))/1000;
                     line([(marks(i)),(marks(i))],[min(data) max(data)],'Color','r');
                   case 2
                     msg = msgbox('Start of a reflected WAVE');
                     pause(1);
                     delete(msg);
                     [x,y] = ginput(1);        
                     marks(i) = round((x*1000))/1000;
                     line([(marks(i)),(marks(i))],[min(data) max(data)],'Color','g');
                   case 0
                     msg = msgbox('Dictotic notch');
                     pause(1);
                     delete(msg);
                     [x,y] = ginput(1);        
                     marks(i) = round((x*1000))/1000;
                     line([(marks(i)),(marks(i))],[min(data) max(data)],'Color','y');
               end
         end
         
         %% cyklus na nalezeni syzstol mezi jednotlivými markrama
         
         for i=0:pocet-1
             round(marks(i*3+1)*fvz)
             round(marks(i*3+2)*fvz)
             
             length(data);
             data(round(marks(i*3+1)*fvz):round(marks(i*3+2)*fvz))
             
             [a b] = max(data(round(marks(i*3+1)*fvz):round(marks(i*3+2)*fvz)));
             a
             b
             systoles(i+1) = b-1+marks(i*3+1)*fvz;
         end
         plot_signals();  
                
    end 
        

    function delete_Callback(source,eventdata)  

      marks = [];  
      plot_signals();
        
    end
   
    function count_Callback(~,~)  
    
      %% vypcitani CO
      
      
         %% forward wave
         % projedu pro jednotlivy vlny, zainterpoluju a spocitam
         % nahrazeni odrazene vlny hodnotami NaN, abz se to mohlo interpolovat
         
         valueSyst = get(checkbox_systole,'Value');
         valueDicr = get(checkbox_dicrotic,'Value');
         
         interp_data = data;
         
                  
         
         for j=0:pocet-1
       
         % nahrazeni NaN hodnotama pro interpolaci    
%          nan_values = data(marks(3*j+2)*fvz+1:marks(3*j+3)*fvz);
%          nan_values(:) = nan;
% 
         if(valueSyst==1)
             if(pocet==1)
             interp_data(round(marks(3*j+2)*fvz) + konst_posunu:end) = interp_data(round(marks(3*j+1)*fvz));  
             
             elseif(j==pocet-1 && pocet~=1)
             HR_vzdalenost = length(round(marks(3*(j-1)+1))*fvz:round(marks(3*j+1)*fvz))-length(round(marks(3*(j-1)+1)*fvz):round(marks(3*(j-1)+3)*fvz));
%              interp_data(marks(3*j+2)*fvz+konst_posunu:marks(3*j+3)*fvz+HR_vzdalenost) = interp_data(marks(3*j+1)*fvz);
                    if((marks(3*j+3)*fvz+HR_vzdalenost)>length(interp_data))
                    interp_data(round(marks(3*j+2)*fvz)+konst_posunu:round(marks(3*j+3)*fvz)+length(interp_data)-round(marks(3*j+3)*fvz)) = interp_data(round(marks(3*j+1)*fvz));
                    else
                    interp_data(round(marks(3*j+2)*fvz)+konst_posunu:round(marks(3*j+3)*fvz)+HR_vzdalenost) = interp_data(round(marks(3*j+1)*fvz));
                    end
                                       
             else
             interp_data(round(marks(3*j+2)*fvz)+konst_posunu:round(marks(3*(j+1)+1)*fvz)-1) = interp_data(round(marks(3*j+1)*fvz));
             
             end
             
             interp_data(round(marks(3*j+2)*fvz)+1:round(marks(3*j+2)*fvz) + konst_posunu) = nan;
                       

             
         end   

          if(valueDicr==1)
             if(pocet==1) 
             interp_data(round(marks(3*j+3)*fvz):end) = interp_data(round(marks(3*j+1)*fvz));
             elseif(j==pocet-1 && pocet~=1)
             HR_vzdalenost = length(round(marks(3*(j-1)+1)*fvz):round(marks(3*j+1)*fvz))-length(round(marks(3*(j-1)+1)*fvz):round(marks(3*(j-1)+3)*fvz));
%              interp_data(marks(3*j+3)*fvz:marks(3*j+3)*fvz+HR_vzdalenost) = interp_data(marks(3*j+1)*fvz);
                   if((round(marks(3*j+3)*fvz)+HR_vzdalenost)>length(interp_data))
                    interp_data(round(marks(3*j+3)*fvz):round(marks(3*j+3)*fvz)+length(interp_data)-round(marks(3*j+3)*fvz)) = interp_data(round(marks(3*j+1)*fvz));
                    else
                    interp_data(round(marks(3*j+3)*fvz):round(marks(3*j+3)*fvz)+HR_vzdalenost) = interp_data(round(marks(3*j+1)*fvz));
                    end
             else
             interp_data(round(marks(3*j+3)*fvz):round(marks(3*(j+1)+1)*fvz)-1) = interp_data(round(marks(3*j+1)*fvz));
             end
             
         interp_data(round(marks(3*j+2)*fvz)+1:round(marks(3*j+3)*fvz)) = nan;   
         
         end 
         % bez dobehu, rovnou to uriznu, jako dobry, ale potreboval bych to
         % s dobehem
%          interp_data(marks(3*j+2)*fvz+1:marks(3*j+3)*fvz) = nan;
         % vysledkem je pak vlna od systoly az po dikroticky zarez a tu
         % bych pak nahral do tech statych dat a vykreslil
%          fw = [data(1:marks((3*j)+1)*fvz-1) data(marks((3*j)+1)*fvz:marks((3*j)+2)*fvz)' nan_values' data(marks((3*j)+1)*fvz)];
%          fw
         
         %%
         interp_data = inpaint_nans(interp_data);
%          figure(15);
%          plot(pokus)
%          
%          %%
%          pozice = 1:length(fw);
%          p = pchip(pozice,fw);
%          % interval do kteryho to interooluju, az teda do tretiho markru
%          xq = 1:marks(3*j+3);
%          pp = ppval(p,xq);
%          
%          %% upravy udelane pro vypocet integralu. vykresleni pak muzu udelat jinde
         
         % vypocet, pokud to je do marks(2), tak beru jen systolu 
         posunute_pp = interp_data - min(interp_data);
%          posunute_pp = interp_data;
%          figure(10);
%          plot(posunute_pp,'r')
         
         %% vse v poradku, ted jen z toho udelat jeden signal a vybarvit a bude to parad
         
         % dle 
         % vysledny signal upraveny
%          posunute_pp = [data(1:marks((3*j)+1)*fvz) posunute_pp zeros(1,length(data)-length(posunute_pp))];


         if(valueSyst==1)
         vypocet_pp = posunute_pp(round(marks((3*j)+1)*fvz):round(marks((3*j)+2)*fvz)+konst_posunu)-min(posunute_pp(round(marks((3*j)+1)*fvz):round(marks((3*j)+2)*fvz)+konst_posunu));      
         else
         vypocet_pp = posunute_pp(round(marks((3*j)+1)*fvz):round(marks((3*j)+3)*fvz))-min(posunute_pp(round(marks((3*j)+1)*fvz):round(marks((3*j)+3)*fvz))); 
         end    
         
%          figure(j+30);
%          time_vec = 0:1/fvz:length(vypocet_pp)/fvz-1/fvz;
%          plot(time_vec,vypocet_pp);
%          xlabel('t [s]');
%          ylabel('Amplitude [-]');
            
         length(time)
         length(posunute_pp)
         length(data-min(interp_data))
%          plot(time,posunute_pp,'r');
% %      
         
         figure(5);
         zoom on;
         plot(time,data-min(interp_data));
         hold on;
    

         SV_vol(j+1) = trapz(vypocet_pp);
         SV_vol
         sysVal_m(j+1) = data(round(systoles(j+1)))-min(interp_data);
         sysVal_m
         SV_rate_manz(j+1) = (((SV_vol)/sysVal_m)*HR)/fvz;
         SV_rate_manz
         
        %% upravim vypocet pro obdelnik, co nam zustal pod jednotlivzmi posunutymi vlnami
      
        %% vybarveni pole
%         figure(20);
%         plot(vypocet_pp);
        

        %         posunute_pp(marks(3*j+3)*fvz) =  posunute_pp(marks(3*j+1)*fvz);

        if(valueSyst==1)
        fillY = posunute_pp(round(marks(3*j+1)*fvz):round(marks(3*j+2)*fvz)+konst_posunu+5)'; 
        fillX = marks(3*j+1):1/fvz:marks(3*j+2)+konst_posunu+5/fvz;     
        else
        fillY = posunute_pp(round(marks(3*j+1)*fvz):round(marks(3*j+3)*fvz))'; 
        fillX = marks(3*j+1):1/fvz:marks(3*j+1)+length(fillY)/fvz-1/fvz; 
        end
        
        if(length(fillY)>length(fillX))
            fillY = fillY(1:length(fillX));
        elseif (length(fillY)<length(fillX))
            fillX = fillX(1:length(fillY));
        else
            'vse OKEY'
        end
            
        length(fillY)
        length(fillX)
        fill(fillX,fillY,'r');
        xlabel('t [s]');
        ylabel('amplituda [-]');
         
         
         end
       
      
        %% vypsani do labelu
        
      set(set_CO,'String',mean(SV_rate_manz));
 
    end
        


end