function perfusni_analyza_v2()


%% inicialization
    close all
    global handles data var;    % declaring of global variables

    handles.FigureA.main_figure = figure('Name','Perfusni analyza','Resize','off','units','pixels','Toolbar','figure','Menubar','none','Position',[650 250 900 650],'Color',[0.8 0.8 0.8]);   % definition of main figure
    set(handles.FigureA.main_figure,'CloseRequestFcn',@main_close);     % adding of user-defined Close request Function

    %% panels and children
    handles.FigureA.panel_middle=uibuttongroup('Parent',handles.FigureA.main_figure,'Title','Kroky analýzy','TitlePosition','centertop','BorderType','beveledin','HighlightColor','black','ShadowColor','black','ForegroundColor','black','FontSize',10,'FontWeight','bold','Position',[0.02 0.23 0.2 0.65]);
    handles.FigureA.panel_conversion=uipanel('Parent',handles.FigureA.main_figure,'Title','Konverze','TitlePosition','centertop','BorderType','beveledin','HighlightColor','black','ShadowColor','black','ForegroundColor','black','FontSize',10,'FontWeight','bold','Position',[0.78 0.23 0.2 0.65],'Visible','off');
    handles.FigureA.panel_registration=uipanel('Parent',handles.FigureA.main_figure,'Title','Registrace','TitlePosition','centertop','BorderType','beveledin','HighlightColor','black','ShadowColor','black','ForegroundColor','black','FontSize',10,'FontWeight','bold','Position',[0.78 0.23 0.2 0.65],'Visible','off');
    handles.FigureA.panel_aif_selection=uipanel('Parent',handles.FigureA.main_figure,'Title','Vyber AIF','TitlePosition','centertop','BorderType','beveledin','HighlightColor','black','ShadowColor','black','ForegroundColor','black','FontSize',10,'FontWeight','bold','Position',[0.78 0.23 0.2 0.65],'Visible','off');
    handles.FigureA.panel_roi_selection=uipanel('Parent',handles.FigureA.main_figure,'Title','Vyber ROI','TitlePosition','centertop','BorderType','beveledin','HighlightColor','black','ShadowColor','black','ForegroundColor','black','FontSize',10,'FontWeight','bold','Position',[0.78 0.23 0.2 0.65],'Visible','off');
    handles.FigureA.panel_perf_an=uibuttongroup('Parent',handles.FigureA.main_figure,'Title','Perfusni analyza','TitlePosition','centertop','BorderType','beveledin','HighlightColor','black','ShadowColor','black','ForegroundColor','black','FontSize',10,'FontWeight','bold','Position',[0.78 0.23 0.2 0.65],'Visible','off');
    handles.FigureA.panel_visualization=uipanel('Parent',handles.FigureA.main_figure,'Title','Vizualizace','TitlePosition','centertop','BorderType','beveledin','HighlightColor','black','ShadowColor','black','ForegroundColor','black','FontSize',10,'FontWeight','bold','Position',[0.78 0.23 0.2 0.65],'Visible','off');
 
    


    
    %% BUTTONs
    handles.FigureA.radio_button_conversion=uicontrol('Style','Radio','String','Konverze','pos',[40 320 100 30],'parent',handles.FigureA.panel_middle,'HandleVisibility','on');
    handles.FigureA.radio_button_manual_registration=uicontrol('Style','Radio','String','Registrace','pos',[40 280 100 30],'parent',handles.FigureA.panel_middle,'HandleVisibility','on');
    handles.FigureA.radio_button_aif_selection=uicontrol('Style','Radio','String','Vyber AIF','pos',[40 240 100 30],'parent',handles.FigureA.panel_middle,'HandleVisibility','on');
    handles.FigureA.radio_button_roi_selection=uicontrol('Style','Radio','String','Vyber ROI','pos',[40 200 100 30],'parent',handles.FigureA.panel_middle,'HandleVisibility','on');
    handles.FigureA.radio_button_perf_an=uicontrol('Style','Radio','String','Perfusni analyza','pos',[40 160 100 30],'parent',handles.FigureA.panel_middle,'HandleVisibility','on');
    handles.FigureA.radio_button_visualization=uicontrol('Style','Radio','String','Vizualizace','pos',[40 120 100 30],'parent',handles.FigureA.panel_middle,'HandleVisibility','on');
    set(handles.FigureA.panel_middle,'SelectionChangeFcn',@selection_method);
    handles.FigureA.button_load=uicontrol('Parent',handles.FigureA.main_figure,'Position',[60 590 100 40],'Enable','on','String','NACTI','Callback',@loading);
    handles.FigureA.button_backward=uicontrol('Parent',handles.FigureA.main_figure,'Position',[320 80 40 40],'Enable','on','String','<','Visible','off','Callback',@previous_image);
    handles.FigureA.button_forward=uicontrol('Parent',handles.FigureA.main_figure,'Position',[570 80 40 40],'Enable','on','String','>','Visible','off','Callback',@next_image);
    handles.FigureA.button_conversion_test=uicontrol('Parent',handles.FigureA.panel_conversion,'Position',[42 240 100 20],'Enable','on','String','Otestuj na ROI','Callback',@roi_test);
    handles.FigureA.button_conversion_precontrast=uicontrol('Parent',handles.FigureA.panel_conversion,'Position',[20 340 150 20],'Enable','on','String','Pocet prekontrastnich snimku','Callback',@conversion_precontrast);
    handles.FigureA.button_conversion_whole=uicontrol('Parent',handles.FigureA.panel_conversion,'Position',[42 200 100 20],'Enable','on','String','Konvertuj','Callback',@whole_conversion);
    handles.FigureA.button_visualize=uicontrol('Parent',handles.FigureA.panel_visualization,'Position',[42 200 100 20],'Enable','on','String','Vizualizuj','Callback',@do_visualization);
    handles.FigureA.radio_button_perfanKety=uicontrol('Style','Radio','String',' model Kety','pos',[10 330 100 30],'parent',handles.FigureA.panel_perf_an,'HandleVisibility','off');
    handles.FigureA.radio_button_perfanKetyvasc=uicontrol('Style','Radio','String',' model Kety vascular phase','pos',[10 300 160 30],'parent',handles.FigureA.panel_perf_an,'HandleVisibility','off');
    handles.FigureA.button_perfan=uicontrol('Parent',handles.FigureA.panel_perf_an,'Position',[42 200 100 20],'Enable','on','String','Start analyzy','Callback',@do_perfan);
    % M
    handles.FigureA.button_setroi=uicontrol('Parent',handles.FigureA.panel_roi_selection,'Position',[40 200 100 20],'Enable','on','String','Vyber oblast','Callback',@vyber_mROI);
    handles.FigureA.button_setaif=uicontrol('Parent',handles.FigureA.panel_aif_selection,'Position',[40 200 100 20],'Enable','on','String','Vyber oblast','Callback',@aif_selection);
    handles.FigureA.button_man_reg=uicontrol('Parent',handles.FigureA.panel_registration,'Position',[40 200 100 20],'Enable','on','String','Registrovat','Callback',@man_reg);
    %% Axes
    handles.FigureA.axes = axes('units','pixels','Position',[260 152 400 400],'Color',[0.8 0.8 0.8],'Visible','off');   % definition of main figure
    
    %% Edits
    handles.edit_precontrastframes=uicontrol(handles.FigureA.panel_conversion,'Position',[80 320 30 20],'Style','edit');
    set(handles.edit_precontrastframes,'String',0);
    %% Texts
    handles.text_aktual_frame=uicontrol('Parent',handles.FigureA.main_figure,'Position',[450 90 75 20],'Style','text','String','-/-','HorizontalAlignment','left','FontSize',8,'BackgroundColor',[0.8 0.8 0.8],'Visible','off');
 
    %% Panel Children
    handles.deti_conversion=get(handles.FigureA.panel_conversion,'Children');
    handles.deti_registration=get(handles.FigureA.panel_registration,'Children');
    handles.deti_aif_selection=get(handles.FigureA.panel_aif_selection,'Children');
    handles.deti_roi_selection=get(handles.FigureA.panel_roi_selection,'Children');
    handles.deti_perf_an=get(handles.FigureA.panel_perf_an,'Children');
    handles.deti_visualization=get(handles.FigureA.panel_visualization,'Children');
    set(handles.deti_conversion,'Visible','off' );
    set(handles.deti_registration,'Visible','off' );
    set(handles.deti_aif_selection,'Visible','off' );
    set(handles.deti_roi_selection,'Visible','off' );
    set(handles.deti_visualization,'Visible','off' );
    set(handles.deti_perf_an,'Visible','off' );
    %% FUNCTIONS
    handles.priznak_nacteni=0;
    handles.priznak_perfanalyza_skoncena=0;
    handles.priznak_vyber=0;
    handles.priznak_aif=0;
    %% function LOADING
    function loading(hObject,eventdata)
        data=cell(1);
        spustenaokna=get(0,'Children');
        close(spustenaokna(2:end));
        [filename_p, pathname] = uigetfile( ...
            {'*.mat', 'Mat files';}, ...
            'Pick a file');
        if filename_p==0
            guidata(hObject, handles);
            
            helpdlg('Nebyl vybran zadny soubor.','Info');
            handles.priznak_nacteni=0;
            set(handles.FigureA.panel_visualization,'Visible','off');
            set(handles.FigureA.panel_conversion,'Visible','off');
            set(handles.FigureA.panel_aif_selection,'Visible','off');
            set(handles.FigureA.panel_roi_selection,'Visible','off');
            set(handles.FigureA.panel_perf_an,'Visible','off');
            set(handles.FigureA.panel_registration,'Visible','off');
            cla(handles.FigureA.axes);
            set(handles.FigureA.axes,'Visible','off');
            set(handles.FigureA.button_forward,'Visible','off');
            set(handles.FigureA.button_backward,'Visible','off');
            set(handles.text_aktual_frame,'Visible','off');
        else
            
            load([pathname filename_p],'data1','data2','info');
            try correctfile=info.codewords;catch end;
            if (exist ('correctfile'))
                for ii=1:length(info.codewords) has_par=strcmp('par',info.codewords(ii)); if has_par==1 break; end;end;
            end;
            if (exist ('correctfile')) & has_par==1
                guidata(hObject, handles);
                helpdlg('Nebyl vybran zadny soubor.','Info');
                handles.priznak_nacteni=0;
                set(handles.FigureA.panel_visualization,'Visible','off');
                set(handles.FigureA.panel_conversion,'Visible','off');
                set(handles.FigureA.panel_aif_selection,'Visible','off');
                set(handles.FigureA.panel_roi_selection,'Visible','off');
                set(handles.FigureA.panel_perf_an,'Visible','off');
                set(handles.FigureA.panel_registration,'Visible','off');
                cla(handles.FigureA.axes);
                set(handles.FigureA.axes,'Visible','off');
                set(handles.FigureA.button_forward,'Visible','off');
                set(handles.FigureA.button_backward,'Visible','off');
                set(handles.text_aktual_frame,'Visible','off');
            end;
            data{1}.info=info;
            data{2}.info=info;
            data{2}.info.conversion_done=0;
            data{1}.data1=data1;
            data{1}.data2=data2;
            helpdlg('Načteno');
            handles.priznak_nacteni=1;
            var.delka_sekvence=length(data{1}.data2);
            prepare_to_conversion=get(handles.FigureA.radio_button_conversion, 'Value');
            var.aktual_frame=1;
            text_aktual=[num2str(var.aktual_frame) '/' num2str(var.delka_sekvence)];
            set(handles.text_aktual_frame,'String',text_aktual);
            intensity_vector=data{1}.data2{1,round(var.delka_sekvence/2)}(:); %get intensity values of middle slice in the series
            var.maxcontrast1=set_contrast1(intensity_vector);
            if prepare_to_conversion==1 || get(handles.FigureA.radio_button_manual_registration,'Value')
                
                if get(handles.FigureA.radio_button_manual_registration,'Value')
                set(handles.FigureA.panel_registration,'Visible','on');
                set(handles.deti_registration,'Visible','on' )
                else
                set(handles.FigureA.panel_conversion,'Visible','on');
                set(handles.deti_conversion,'Visible','on' )
                end;
                set(handles.FigureA.axes, 'Visible','on');
                set(handles.FigureA.button_backward, 'Visible','on');
                set(handles.FigureA.button_forward, 'Visible','on');
                set(handles.text_aktual_frame, 'Visible','on');                
                imshow(data{1}.data2{var.aktual_frame},[var.maxcontrast1],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                handles.priznak_vyber=0;
                handles.priznak_aif=0;
            else
                helpdlg('Nastavte přepínač na konverzi nebo registraci!');
            end;
            
        end;
    end
    
    %% Function Conversion_precontrast
    
    function conversion_precontrast(hObject,eventdata)
        [BW,x_vect,y_vect]=roipoly();
        maska=double(BW);
        summask=sum(sum(maska));
        for ind=1:length(data{1}.data2)
            tmp=double(data{1}.data2{ind}).*maska;
            roi_0(ind)=sum(sum(tmp))/summask;
        end       
        figure(1111);plot(roi_0);
        axes(handles.FigureA.axes);hold on;
        line(x_vect,y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;
        line(x_vect,y_vect,'LineWidth',2,'Color',[0 1 0]);       
        handles.priznak_vyber=0;
        handles.priznak_aif=0;
    end

    %% Function Manual Registration
    
    function man_reg(hOBject,eventdata)
        ref_frame=var.aktual_frame;
        answ=questdlg(['Jako referencni snimek bude nastaven snimek ', num2str(ref_frame), '. Chcete pokracovat?'],'Warning','Ano','Ne','Ne');
        switch answ
            case 'Ano'
                set(handles.FigureA.button_backward,'Enable','off');
                set(handles.FigureA.button_forward,'Enable','off');
                set(handles.FigureA.button_man_reg,'Enable','off');
                vertic_only=1; 
                magni=3;
                frames=var.delka_sekvence;
                data_temp=data{1};
                [size_x,size_y]=size(data_temp.data2{1,1});
                handle_text=text(10,10,'REF','FontSize',16,'FontWeight','bold','Color',[1 1 1]);
                var.text_title=['Data2: REF'];
                title('Parent',handles.FigureA.axes, var.text_title);
                msgbox('Vyberte referencni bod.');uiwait;
                [ref_col,ref_row]=ginput_mod(1);
                ref_col=round(ref_col);
                ref_row=round(ref_row);
                clear ('handle_text'); 
                var.ref_col=ref_col;
                var.ref_row=ref_row;
                data1_seq=size(data_temp.data1,2);
                % nejprve data1
                for ind=1:data1_seq
                    data1_inner=size(data_temp.data1{ind},2);
                    for ind2=1:data1_inner
                        imshow(data{1}.data1{ind}{ind2},'InitialMagnification',magni*100,'DisplayRange',[]); 
                        colormap(gray);
                        var.text_title=['Data1: ' num2str(ind) '-' num2str(ind2)];
                        title('Parent',handles.FigureA.axes,var.text_title);
                        [col, row, mb] = ginput_mod(1);
                        if mb==1
                            col=round(col);row=round(row);
                            diff_r=ref_row-row; diff_c=ref_col-col;
                            if vertic_only==1
                                diff_c=0;
                            end
                            if diff_c<0  
                                data_temp.data1{ind}{ind2}=feval(data{1}.info.datatype,zeros(size_x,size_y));
                             elseif diff_c>0
                                data_temp.data1{ind}{ind2}=feval(data{1}.info.datatype,zeros(size_x,size_y));
                                data_temp.data1{ind}{ind2}(:,diff_c:end)=data{1}.data1{ind}{ind2}(:,1:end-diff_c+1); 
                            else
                                data_temp.data1{ind}{ind2}=data{1}.data1{ind}{ind2};
                            end
                            if diff_r<0
                                data_temp.data1{ind}{ind2}(1:end-abs(diff_r)+1,:)=data_temp.data1{ind}{ind2}(abs(diff_r):end,:);
                                data_temp.data1{ind}{ind2}(end-diff_r+1:end,:)=feval(data{1}.info.datatype,0);
                            elseif diff_r>0
                                data_temp.data1{ind}{ind2}(diff_r:end,:)=data_temp.data1{ind}{ind2}(1:end-diff_r+1,:); 
                                data_temp.data1{ind}{ind2}(1:diff_r-1,:)=feval(data{1}.info.datatype,0);
                            else
                                data_temp.data1{ind}{ind2}=data_temp.data1{ind}{ind2};
                            end   
                        end
                    end
                end
                % pak data2
                var.actual_frame=1;
                while var.actual_frame<=frames
                    imshow(data{1}.data2{var.actual_frame},'InitialMagnification',magni*100,'DisplayRange',var.maxcontrast1); 
                    colormap(gray);
                    var.text_title=['Data2: ' num2str(var.actual_frame) '/' num2str(frames)];
                    title('Parent',handles.FigureA.axes,var.text_title);        
                    [col, row, mb] = ginput_mod(1);
                    if mb==1
                        col=round(col);row=round(row);
                        diff_r=ref_row-row; diff_c=ref_col-col;
                        if vertic_only==1
                            diff_c=0;
                        end
                        if diff_c<0
                            data_temp.data2{var.actual_frame}=feval(data{1}.info.datatype,zeros(size_x,size_y));
                            data_temp.data2{var.actual_frame}(:,1:end-abs(diff_c)+1)=data{1}.data2{var.actual_frame}(:,abs(diff_c):end);
                        elseif diff_c>0
                            data_temp.data2{var.actual_frame}=feval(data{1}.info.datatype,zeros(size_x,size_y));
                            data_temp.data2{var.actual_frame}(:,diff_c:end)=data{1}.data2{var.actual_frame}(:,1:end-diff_c+1); 
                        else
                            data_temp.data2{var.actual_frame}=data{1}.data2{var.actual_frame};
                        end
                        if diff_r<0
                            tmp=data_temp.data2{var.actual_frame};
                            data_temp.data2{var.actual_frame}=feval(data{1}.info.datatype,zeros(size_x,size_y));
                            data_temp.data2{var.actual_frame}(1:end-abs(diff_r)+1,:)=tmp(abs(diff_r):end,:);
                            data_temp.data2{var.actual_frame}(end-diff_r+1:end,:)=feval(data{1}.info.datatype,0);
                        elseif diff_r>0
                            tmp=data_temp.data2{var.actual_frame};
                            data_temp.data2{var.actual_frame}=feval(data{1}.info.datatype,zeros(size_x,size_y));
                            data_temp.data2{var.actual_frame}(diff_r:end,:)=tmp(1:end-diff_r+1,:); 
                            data_temp.data2{var.actual_frame}(1:diff_r-1,:)=feval(data{1}.info.datatype,0);
                        else
                            data_temp.data2{var.actual_frame}=data_temp.data2{var.actual_frame};
                        end
                    var.actual_frame=var.actual_frame+1;
                    end
                end
                data{1}=data_temp;
                msgbox('Hotovo','Manualni registrace dokoncena.','modal');uiwait;
                set(handles.FigureA.button_backward,'Enable','on');
                set(handles.FigureA.button_forward,'Enable','on');
                set(handles.FigureA.button_man_reg,'Enable','on');  
                imshow(data{1}.data2{var.aktual_frame},'InitialMagnification',magni*100,'DisplayRange',var.maxcontrast1);
            case 'No'
                 % kdyz ne, tak ne
        end
    end
    %% Function ROI test
    
    function roi_test(hObject,eventdata)
            [BW,x_vect,y_vect]=roipoly();
            maska=double(BW); 
            data{1}.info.acq.skip_frames = 0;
            if data{1}.info.realna==1                       
            data{1}.info.acq.PhaseEncSteps = 20;
            data{1}.info.acq.TR_real       = 2.1;
            SI2con_SRFLASH_roi(data{1}.data1, data{1}.info, BW, data{1}.info.acq.skip_frames, data{1}.info.acq.PhaseEncSteps, data{1}.info.acq.TR_real); 
            else
            SI2con_2DFLASHlinear_roi(data{1}.data1, data{1}.info, BW, data{1}.info.acq.skip_frames);    
            end
    end

    %% Function CONVERSION DYNAMIC SEQUENCE
    
    function whole_conversion(hObject,eventdata)
        data{1}.info.acq.precontrast   = str2num(get(handles.edit_precontrastframes,'String'));
        if length(data{1}.info.acq.precontrast)==0
            helpdlg('Cela cisla!','Info');
        else
            [BW,x_vect,y_vect]=roipoly();
            maska=double(BW);
            doT1map = 1;
            doDynSeq = 1;
            data{1}.info.acq.precontrast   = round(str2num(get(handles.edit_precontrastframes,'String')));
            if data{1}.info.realna==1
                data{1}.info.acq.skip_frames = 0;
                data{1}.info.acq.PhaseEncSteps = 20;
                data{1}.info.acq.TR_real       = 2.1;
                [data{end}.data2, data{end}.info]= SI2con_SRFLASH_whole(data{1}.data1, data{1}.data2, data{1}.info, maska, data{1}.info.acq.skip_frames, data{1}.info.acq.PhaseEncSteps, data{1}.info.acq.TR_real, data{1}.info.acq.precontrast, doT1map, doDynSeq);
            else
                data{1}.info.acq.skip_frames = 3;
                [data{end}.data2, data{end}.info] = SI2con_2DFLASH_whole(data{1}.data1, data{1}.data2, data{1}.info, maska, data{1}.info.acq.skip_frames, data{1}.info.acq.precontrast, doT1map, doDynSeq);
            end
            intensity_vector=data{end}.data2{1,round(var.delka_sekvence/2)}(:); %get intensity values of middle slice in the series
            var.maxcontrast2=set_contrast(intensity_vector);
            data{end}.info.conversion_done=1;
            handles.priznak_vyber=0;
            handles.priznak_aif=0;
            helpdlg('Analyza dokoncena','Info');
        end;
    end

    %% Function AIF selection
    
    function aif_selection(hObject,eventdata)
        if handles.priznak_aif==1
            axes(handles.FigureA.axes);
            handles_vector=get(gca,'Children')
            if length(handles_vector)==1
            elseif length(handles_vector)==2 && handles.priznak_vyber==1
%                 delete(handles_vector(1));
            else
                delete(handles_vector(1));
            end
            data{2}.aif=[];
        end
        [BW,x_vect,y_vect]=roipoly();
        maska=double(BW);
        summask=sum(sum(maska));
        for ind=1:length(data{2}.data2)
            tmp=double(data{2}.data2{ind}).*maska;
            roi_0(ind)=sum(sum(tmp))/summask;
        end
        data{2}.aif{1,1}=roi_0;
        data{2}.aif{1,2}=sparse(logical(maska));
        data{2}.aif{1,3}=[x_vect,y_vect];
        figure(1111);plot(data{2}.aif{1,1});
        axes(handles.FigureA.axes);hold on;
%         line(x_vect,y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;
        line(x_vect,y_vect,'LineWidth',2,'Color',[0 1 0]);hold off;
        handles.priznak_aif=1;
        handles.priznak_perfanalyza_skoncena=0;
    end

    %% Function ROI selection
    
    function vyber_mROI(hObject,eventdata)
        answ='A';
        if handles.priznak_vyber==1
            answ=questdlg('Oblast zajmu byla jiz vybrana. Predchozi data budou prepsana. Chcete pokracovat?','Warning','Yes','No','No');
        end
        switch answ
            case 'No'
            case 'Yes'
                data{end}.tissue=[];
                data{end}.info.tissue.x_vector=[];
                data{end}.info.tissue.y_vector=[];
                axes(handles.FigureA.axes);
                handles_vector=get(gca,'Children')
                delete(handles_vector(1));
                [BW,x_vect,y_vect]=roipoly();
                data_working=data{end}.data2;
                nu_frames=length(data_working);
                [roi_x,roi_y]=find(BW);
                multiroi=cell(1,length(roi_x));
                for ind=1:length(roi_x)
                    maska=zeros(size(data{end}.data2{1}));
                    maska(roi_x(ind),roi_y(ind))=1;
                    for ind2=1:nu_frames
                        multiroi{ind}(ind2)=data_working{ind2}(roi_x(ind),roi_y(ind));
                    end
                    data{end}.tissue{ind,1}=multiroi{ind};
                    data{end}.tissue{ind,2}=sparse(logical(maska));
                    data{end}.tissue{ind,3}=[repmat(roi_x(ind),[5 1]) repmat(roi_y(ind),[5 1])];
                end
                multiroi
                axes(handles.FigureA.axes);hold on;
                line(x_vect,y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;
                data{end}.info.tissue.x_vect=x_vect;
                data{end}.info.tissue.y_vect=y_vect;
                data{end}.info.tissue.descr={'Curve [-]' 'Mask' 'Mask coordinates'};
                handles.priznak_vyber=1;
                handles.priznak_perfanalyza_skoncena=0;
            case 'A'
                [BW,x_vect,y_vect]=roipoly();
                data_working=data{end}.data2;
                nu_frames=length(data_working);
                [roi_x,roi_y]=find(BW);
                multiroi=cell(1,length(roi_x));
                for ind=1:length(roi_x)
                    maska=zeros(size(data{end}.data2{1}));
                    maska(roi_x(ind),roi_y(ind))=1;
                    for ind2=1:nu_frames
                        multiroi{ind}(ind2)=data_working{ind2}(roi_x(ind),roi_y(ind));
                    end
                    data{end}.tissue{ind,1}=multiroi{ind};
                    data{end}.tissue{ind,2}=sparse(logical(maska));
                    data{end}.tissue{ind,3}=[repmat(roi_x(ind),[5 1]) repmat(roi_y(ind),[5 1])];
                end
                multiroi
                axes(handles.FigureA.axes);hold on;
                line(x_vect,y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;
                data{end}.info.tissue.x_vect=x_vect;
                data{end}.info.tissue.y_vect=y_vect;
                data{end}.info.tissue.descr={'Curve [-]' 'Mask' 'Mask coordinates'};
                handles.priznak_vyber=1;
                handles.priznak_perfanalyza_skoncena=0;
        end
        
    end

    %% Function PERFUSION ANALYSIS
    
    function do_perfan(hObject,eventdata)
        spustenaokna=get(0,'Children');
        close(spustenaokna(2:end));
        if handles.priznak_vyber==1
            tissue_pom=data{2}.tissue;
            tissue_descr=data{2}.info.tissue.descr;
            clear data{2}.tissue;
            clear data{2}..info.tissue.descr;
            data{2}.tissue=tissue_pom(1:end,1:3);
            data{2}.info.tissue.descr=tissue_descr(1:3);
            selected_method_button=get(handles.FigureA.radio_button_perfanKety,'Value')
            if selected_method_button==1
                selected_method='Kety';
            else
                selected_method='Kety + vasculare phase';
            end;
            
            handle_statusbar=statusbar('Prubeh');
            % define functions and constansts following selected method
            switch selected_method
                case 'Kety'
                    model=@Kety_with_derivatives;
                    x_fixed=logical([0 0 0]); % if "1", parameter is fixed on its starting value
                    x_start(1,:)=[1 1 0]; % minuty
                    lb=[0 0 -Inf];
                    ub=[Inf Inf Inf];
                    rescale_param=[1 1 10];
                    x_start=x_start.*repmat(rescale_param,size(x_start,1),1);
                    data{end}.info.perfan.params={'Ktrans [ml/(ml min)]','ve [ml/ml]','BAT [min]'};
                case 'Kety + vasculare phase'
                    model=@Kety_vascular_with_derivatives;
                    % % x=[Ktrans ve vb delay]
                    x_fixed=logical([0 0 0 0]); % if "1", parameter is fixed on its starting value
                    x_start(1,:)=[1 0.5 0.1 0]; % minuty
                    lb=[0 0 1e-2 -Inf];
                    ub=[Inf Inf Inf Inf];
                    rescale_param=[1 1 1 10];
                    x_start=x_start.*repmat(rescale_param,size(x_start,1),1);
                    data{end}.info.perfan.params={'Ktrans [ml/(ml min)]','ve [ml/ml]','vb [ml/ml]','BAT [min]'};
            end;
            pom=data{end}.info.perfan.params;
            for n=1:length(pom)
                pom{n}=['std(' strrep(pom{n},' ',') ')];
            end
            data{end}.info.tissue.descr=cat(2,data{end}.info.tissue.descr,data{end}.info.perfan.params,pom,{'SSD', 'AIF', 'TRF', 'Model','Estimate details'});
            lb=lb.*rescale_param;
            ub=ub.*rescale_param;
            % get aif
            aif_pure=data{end}.aif{1,1};
            length_aif=length(aif_pure);
            aif=zeros(length_aif+mod(length_aif+1,2),1); %  - if length of aif is even, one zero is added at the begining of aif
            aif((length(aif)-length_aif+1):end)=aif_pure; % /
            length_aif=length(aif);
            %aif normalization
            norm_coeff=max(aif);
            aif_norm=aif/norm_coeff;
            % generation of time axis from info
            Ts=data{end}.info.acq.Ts/60;
            t=(0:length_aif-1)'*Ts;
            % optimization algorithm setup
            options=optimset('TolX',1e-10,'TolFun',1e-12,'Display','off','MaxFunEvals',1e10,...
                'Jacobian','off','MaxIter',500,'DiffMinChange',0.01,'DiffMaxChange',0.1,...
                'LargeScale','on','LevenbergMarquardt','off','Diagnostics','off',...
                'DerivativeCheck','off','TypicalX',0.1*ones(size(x_start(1,:))));%,'PlotFcns',@optimplotx,'PlotFcns',@optimplotfval,@optimplotx,'OutputFcn',@outfun
            data{end}.info.perfan.options=options; % store options to global info
            % cycle trough tissu curves
            no_of_parameters=size(x_start,2);
            no_of_starting_points=size(x_start,1);
            no_of_curves=size(data{end}.tissue,1);
            no_of_col=size(data{end}.tissue,2);
            handle_statusbar=statusbar(0,handle_statusbar);
            for n=1:no_of_curves;
                Cfit=zeros(length_aif,1);
                tmp=double(data{end}.tissue{n,1})'/norm_coeff;
                Cfit((length_aif-length(tmp)+1):end)=tmp;
                
                f = @(par)C_fitted_delay_minus_y(par,t,aif_norm,model,Cfit,rescale_param,x_fixed,x_start);
                mse_best=Inf;
                index_m=zeros(1,1,'uint8');
                for m=1:no_of_starting_points;
                    history=[];
                    [b,mse,r,exitflag,output,lambda,J] = lsqnonlin(f,x_start(m,~x_fixed),lb(~x_fixed),ub(~x_fixed),options);
                    [Q,R]=qr(J,0);
                    Rinv=inv(R);
                    COVB=full((Rinv*Rinv')*mse/(length(aif)-length(x_start(m,~x_fixed))));
                    index_m(mse_best>mse)=m;
                    mse_best(mse_best>mse)=mse;
                    data_results{m}=struct('par_estimate',b,...
                        'residual',r,'jacobian',J,'covariance_matrix',COVB,'mse',mse,...
                        'history',history,'output',output,'Start_point_No',index_m);
                end
                %store results
                param_to_store2=data_results{index_m}.par_estimate;
                param_to_store=zeros(1,length(x_fixed));
                param_to_store(~x_fixed)=param_to_store2;
                param_to_store(x_fixed)=x_start(x_fixed);
                param_std_to_store=zeros(1,length(x_fixed));
                param_std_to_store(~x_fixed)=sqrt(diag(data_results{index_m}.covariance_matrix))';
                param_std_to_store(x_fixed)=0;
                param_to_store=param_to_store./rescale_param; % return solution to basic units
                param_std_to_store=param_std_to_store./rescale_param; % return solution to basic units
                delay_transform=length_aif*Ts/(2*pi);                           % \
                param_to_store(end)=param_to_store(end)*delay_transform;        %  > transform delay to minutes
                param_std_to_store(end)=param_std_to_store(end)*delay_transform;% /
                data{end}.tissue(n,no_of_col+(1:no_of_parameters))=num2cell(param_to_store); % store parameter estimates
                data{end}.tissue(n,no_of_col+no_of_parameters+(1:no_of_parameters))=num2cell(param_std_to_store); % store std of parameter estimates
                data{end}.tissue(n,no_of_col+no_of_parameters+no_of_parameters+1)=num2cell(mse_best);
                pom=[data{end}.info.perfan.params;repmat({' '},1,no_of_parameters)];disp(cell2mat(pom(:)')); % disp(['F [ml/(ml min)]','E [-]','ve [ml/ml]','Tc [min]','BAT [min]'])
                disp(param_to_store)
                disp(param_std_to_store)
                disp('  ')
                best_data_results = cell(1,1);
                best_data_results{1} = data_results(index_m);
                data{end}.tissue(n,no_of_col+2*no_of_parameters+4)=best_data_results; % store details about solution (jacobian, covariance matrix, ...)
                data{end}.tissue{n,no_of_col+2*no_of_parameters+1+1}=aif_pure; % store aif for each curve
                retransform_param=ones(1,no_of_parameters);
                retransform_param(end)=delay_transform; % for C_fitted_delay to convert BAT back to phase delay
                pom=C_fitted_delay(cell2mat(data{end}.tissue(n,no_of_col+(1:no_of_parameters))),t,aif,model,retransform_param);
                data{end}.tissue{n,no_of_col+2*no_of_parameters+4}=pom((end-length(aif_pure)+1):end); % store modeled TRF
                data{end}.tissue{n,no_of_col+2*no_of_parameters+3}=model(param_to_store,t(1:length(aif_pure))); % store IRF (model)
                % working visualization
                figure(100)
                plot(t,[0 data{end}.tissue{n,1}],'b')
                hold on
                plot(t,pom,'r')
                legend('measured','fitted')
                title(selected_method)
                hold off                
                figure(101)
                plot(t,model(cell2mat(data{end}.tissue(n,no_of_col+(1:no_of_parameters))),t),'r')
                legend('fitted')
                title(selected_method)
                handle_statusbar=statusbar(n/no_of_curves,handle_statusbar);
            end
            helpdlg('Analyza dokoncena','Info');
            pause(0.5)
            delete(handle_statusbar);
            handles.priznak_perfanalyza_skoncena=1;
            data{end}.info.perfan.options=options; % store options to global info
            data{end}.info.perfan.functionname='perfan_MRI'; % store options to global info
            data{end}.info.perfan.svnver='unknown';
            data{end}.info.perfan.model=selected_method; % pharmacokinetic model used
            data{end}.info.perfan.ub=ub; % upper bound
            data{end}.info.perfan.lb=lb; % lower bound
            data{end}.info.perfan.rescale_param=rescale_param; % vector for rescaling parameters in structs
            data{end}.info.perfan.x_fixed=x_fixed; % vector defining fixed parameters
            data{end}.info.perfan.x_start=x_start; % matrix of starting points
            data{end}.info.perfan.norm_coeff=norm_coeff; % normalization coefficient
        else
            helpdlg('Vyber oblasti ROI!');
        end;
    end

    %% Function VISUALIZATION
    
    function do_visualization(hObject,eventdata)        
            spustenaokna=get(0,'Children');
            close(spustenaokna(2:end));            
            parameters_tissue=data{end}.info.tissue.descr;
            tissue=data{end}.tissue;
            var.mapy_parametru={};
            var.nazvy_parametru={};
            [curves_name,parameters_vizualization,parameters_tissue,mask,curves,concentration] = GetParamMaps(tissue,parameters_tissue);
            var.mapy_parametru=parameters_vizualization;
            var.nazvy_parametru=parameters_tissue;
            frame=data{end}.data2{var.aktual_frame}; 
            nmr_param_not_curves_counter=0;
            for nmr_param=1:length(parameters_vizualization)
                if parameters_vizualization{nmr_param}==0
                    nmr_param_not_curves_counter=nmr_param_not_curves_counter+1;
                end;
            end;
            nmr_param_not_curves=length(parameters_vizualization)-nmr_param_not_curves_counter;
            var.nmr_param_not_curves=nmr_param_not_curves;
            var.nmr_param_not_curves_counter=nmr_param_not_curves_counter;
            for pocet_parametru=1:length(parameters_vizualization)
                parametr=parameters_vizualization{pocet_parametru};
                parameter_name=parameters_tissue{pocet_parametru+3};
                if parametr==0
                else
                    VIZ_OUTPUT(parametr,parameter_name, frame, mask,curves,curves_name,concentration);
                end;
            end;        
    end

    %% Function Selection method
    
    function selection_method(hObject,eventdata)
        set(handles.FigureA.panel_visualization,'Visible','off');
        set(handles.FigureA.panel_conversion,'Visible','off');
        set(handles.FigureA.panel_aif_selection,'Visible','off');
        set(handles.FigureA.panel_roi_selection,'Visible','off');
        set(handles.FigureA.panel_perf_an,'Visible','off');
        set(handles.FigureA.panel_registration,'Visible','off');       
        set(handles.deti_visualization,'Visible','off' );
        set(handles.deti_conversion,'Visible','off' );
        set(handles.deti_aif_selection,'Visible','off' );
        set(handles.deti_roi_selection,'Visible','off' );
        set(handles.deti_registration,'Visible','off' );
        set(handles.deti_perf_an,'Visible','off' );
        spustenaokna=get(0,'Children');
        close(spustenaokna(2:end));
        if get(handles.FigureA.radio_button_conversion,'Value')
            
            if handles.priznak_nacteni==1
                set(handles.FigureA.panel_conversion,'Visible','on');
                set(handles.deti_conversion,'Visible','on' );                               
                imshow(data{1}.data2{var.aktual_frame},[var.maxcontrast1],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                set(handles.FigureA.button_backward, 'Visible','on');
                set(handles.FigureA.button_forward, 'Visible','on');
                set(handles.text_aktual_frame, 'Visible','on');
            else
                helpdlg('Nebyl vybran zadny soubor.','Info');
            end;
            
        end;       
        
        if get(handles.FigureA.radio_button_manual_registration,'Value')
            if handles.priznak_nacteni==0
                helpdlg('Nejprve musite nacist sekvenci!');
            else
                set(handles.FigureA.panel_registration,'Visible','on');
                set(handles.deti_registration,'Visible','on' );
                imshow(data{1}.data2{var.aktual_frame},[var.maxcontrast1],'InitialMagnification',3*100,'Parent',handles.FigureA.axes); 
                set(handles.FigureA.button_backward, 'Visible','on');
                set(handles.FigureA.button_forward, 'Visible','on');
                set(handles.text_aktual_frame, 'Visible','on');
            end;
        end;
        
        if get(handles.FigureA.radio_button_aif_selection,'Value')
            if handles.priznak_nacteni==0
                helpdlg('Nejprve musite nacist sekvenci!');
            else
                set(handles.FigureA.panel_aif_selection,'Visible','on');
                set(handles.deti_aif_selection,'Visible','on' );
                set(handles.deti_aif_selection,'Enable','on' );
                if data{end}.info.conversion_done==1                                        
                    imshow(data{end}.data2{var.aktual_frame},[var.maxcontrast2],'InitialMagnification',3*100,'Parent',handles.FigureA.axes)
                    if  handles.priznak_vyber==1 hold on; line(data{end}.info.tissue.x_vect,data{end}.info.tissue.y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;end
                    set(handles.FigureA.button_backward, 'Visible','on');
                    set(handles.FigureA.button_forward, 'Visible','on');
                    set(handles.text_aktual_frame, 'Visible','on');
                else
                    helpdlg('Proved konverzi!');
                    set(handles.deti_aif_selection,'Enable','off' );
                end;
            end;
        end;
        
        if get(handles.FigureA.radio_button_roi_selection,'Value')
            if handles.priznak_nacteni==0
                helpdlg('Nejprve musite nacist sekvenci!');
            else
                set(handles.FigureA.panel_roi_selection,'Visible','on');
                set(handles.deti_roi_selection,'Visible','on' );                
                set(handles.deti_roi_selection,'Enable','on' );
                if data{end}.info.conversion_done==1                                       
                    imshow(data{end}.data2{var.aktual_frame},[var.maxcontrast2],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                    if  handles.priznak_vyber==1 hold on; line(data{end}.info.tissue.x_vect,data{end}.info.tissue.y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;end
                    set(handles.FigureA.button_backward, 'Visible','on');
                    set(handles.FigureA.button_forward, 'Visible','on');
                    set(handles.text_aktual_frame, 'Visible','on');
                else
                    helpdlg('Proved konverzi!');
                    set(handles.deti_roi_selection,'Enable','off' );
                end;
            end;
        end;
        
        if get(handles.FigureA.radio_button_perf_an,'Value')
            if handles.priznak_nacteni==0
                helpdlg('Nejprve musite nacist sekvenci!');
            else
                set(handles.FigureA.panel_perf_an,'Visible','on');
                set(handles.deti_perf_an,'Visible','on' );
                set(handles.deti_perf_an,'Enable','on' );
                if data{end}.info.conversion_done==1 && handles.priznak_vyber==1 &&  handles.priznak_aif==1                                            
                    imshow(data{end}.data2{var.aktual_frame},[var.maxcontrast2],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                    if  handles.priznak_vyber==1 hold on; line(data{end}.info.tissue.x_vect,data{end}.info.tissue.y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;end
                    set(handles.FigureA.button_backward, 'Visible','on');
                    set(handles.FigureA.button_forward, 'Visible','on');
                    set(handles.text_aktual_frame, 'Visible','on');
                else
                    helpdlg('Nejsou vsechna data pro analyzu!');
                    set(handles.deti_perf_an,'Enable','off' );
                end;
            end;
        end;
        
        if get(handles.FigureA.radio_button_visualization,'Value')
                
            if handles.priznak_nacteni==0
                helpdlg('Nejprve musite nacist sekvenci!');
            else
                set(handles.FigureA.panel_visualization,'Visible','on');
                set(handles.deti_visualization,'Visible','on' );
                set(handles.deti_visualization,'Enable','on' );
                if data{end}.info.conversion_done==1 && handles.priznak_perfanalyza_skoncena==1
                    imshow(data{end}.data2{var.aktual_frame},[var.maxcontrast2],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                    if  handles.priznak_vyber==1 hold on; line(data{end}.info.tissue.x_vect,data{end}.info.tissue.y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;end
                    set(handles.FigureA.button_backward, 'Visible','on');
                    set(handles.FigureA.button_forward, 'Visible','on');
                    set(handles.text_aktual_frame, 'Visible','on');
                else
                    
                    set(handles.deti_visualization,'Enable','off' );
                    helpdlg('Není co vizualizovat!');                             
                end;
            end;
        end;
        
    end

 %% Function previous_image
    
    function previous_image(hObject,eventdata)
        
        
        if var.aktual_frame==1
            if (get(handles.FigureA.radio_button_conversion,'Value') && data{end}.info.conversion_done==0) || (get(handles.FigureA.radio_button_manual_registration,'Value') && data{end}.info.conversion_done==1) || (get(handles.FigureA.radio_button_manual_registration,'Value') && data{end}.info.conversion_done==0) || (get(handles.FigureA.radio_button_conversion,'Value') && data{end}.info.conversion_done==1)
                imshow(data{1}.data2{var.delka_sekvence},[var.maxcontrast1],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                var.aktual_frame=var.delka_sekvence;
                text_aktual=[num2str(var.aktual_frame) '/' num2str(var.delka_sekvence)];
                set(handles.text_aktual_frame,'String',text_aktual);
            elseif data{end}.info.conversion_done==1               
                imshow(data{end}.data2{var.delka_sekvence},[var.maxcontrast2],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                if  handles.priznak_vyber==1 hold on; line(data{end}.info.tissue.x_vect,data{end}.info.tissue.y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;end
                var.aktual_frame=var.delka_sekvence;
                text_aktual=[num2str(var.aktual_frame) '/' num2str(var.delka_sekvence)];
                set(handles.text_aktual_frame,'String',text_aktual);
            else
                helpdlg('Proved konverzi!');   
            end;
            
        else
            if (get(handles.FigureA.radio_button_conversion,'Value') && data{end}.info.conversion_done==0 ) ||  (get(handles.FigureA.radio_button_manual_registration,'Value') && data{end}.info.conversion_done==1) || (get(handles.FigureA.radio_button_manual_registration,'Value') && data{end}.info.conversion_done==0) || (get(handles.FigureA.radio_button_conversion,'Value') && data{end}.info.conversion_done==1)
                imshow(data{1}.data2{var.aktual_frame-1},[var.maxcontrast1],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                var.aktual_frame=var.aktual_frame-1;
                text_aktual=[num2str(var.aktual_frame) '/' num2str(var.delka_sekvence)];
                set(handles.text_aktual_frame,'String',text_aktual);
            elseif data{end}.info.conversion_done==1              
                imshow(data{end}.data2{var.aktual_frame-1},[var.maxcontrast2],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                if  handles.priznak_vyber==1 hold on; line(data{end}.info.tissue.x_vect,data{end}.info.tissue.y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;end
                var.aktual_frame=var.aktual_frame-1;
                text_aktual=[num2str(var.aktual_frame) '/' num2str(var.delka_sekvence)];
                set(handles.text_aktual_frame,'String',text_aktual);
            else
                helpdlg('Proved konverzi!');   
            end;
            
        end;
        
        
        
        
    end

%% Function next_image
    
    function next_image(hObject,eventdata)
        
      
        
        if var.aktual_frame==var.delka_sekvence
            if (get(handles.FigureA.radio_button_conversion,'Value') && data{end}.info.conversion_done==0) || (get(handles.FigureA.radio_button_manual_registration,'Value') && data{end}.info.conversion_done==1) || (get(handles.FigureA.radio_button_manual_registration,'Value') && data{end}.info.conversion_done==0) || (get(handles.FigureA.radio_button_conversion,'Value') && data{end}.info.conversion_done==1)
                imshow(data{1}.data2{1},[var.maxcontrast1],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                var.aktual_frame=1;
                text_aktual=[num2str(var.aktual_frame) '/' num2str(var.delka_sekvence)];
                set(handles.text_aktual_frame,'String',text_aktual);
            elseif data{end}.info.conversion_done==1
                imshow(data{end}.data2{1},[var.maxcontrast2],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                if  handles.priznak_vyber==1 hold on; line(data{end}.info.tissue.x_vect,data{end}.info.tissue.y_vect,'LineWidth',2,'Color',[1 0 0]);hold off;end
                var.aktual_frame=1;
                text_aktual=[num2str(var.aktual_frame) '/' num2str(var.delka_sekvence)];
                set(handles.text_aktual_frame,'String',text_aktual);
            else
                helpdlg('Proved konverzi!');
            end;
            
        else
            if (get(handles.FigureA.radio_button_conversion,'Value') && data{end}.info.conversion_done==0) || (get(handles.FigureA.radio_button_manual_registration,'Value') && data{end}.info.conversion_done==1) || (get(handles.FigureA.radio_button_manual_registration,'Value') && data{end}.info.conversion_done==0) || (get(handles.FigureA.radio_button_conversion,'Value') && data{end}.info.conversion_done==1)
                imshow(data{1}.data2{var.aktual_frame+1},[var.maxcontrast1],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                var.aktual_frame=var.aktual_frame+1;
                text_aktual=[num2str(var.aktual_frame) '/' num2str(var.delka_sekvence)];
                set(handles.text_aktual_frame,'String',text_aktual);
            elseif data{end}.info.conversion_done==1
                
                imshow(data{end}.data2{var.aktual_frame+1},[var.maxcontrast2],'InitialMagnification',3*100,'Parent',handles.FigureA.axes);
                if  handles.priznak_vyber==1 hold on; line(data{end}.info.tissue.x_vect,data{end}.info.tissue.y_vect,'LineWidth',2,'Color',[1 0 0]);hold off; end
                var.aktual_frame=var.aktual_frame+1;
                text_aktual=[num2str(var.aktual_frame) '/' num2str(var.delka_sekvence)];
                set(handles.text_aktual_frame,'String',text_aktual);
            else
                helpdlg('Proved konverzi!');
            end;
            
        end;
        
        
        
    end
    
    %% Function main close
    
    function main_close(hObject,eventdata)
        aa=get(0,'Children');
        aa=sort(aa,'descend');
        for ind=1:length(aa);
            delete(figure(aa(ind)));
        end
        clear global handles;
        % global variables delete, only global variable data is kept
        clear global data;
        clear global var;
    end
end