function varargout = rp_get_intersection_mask(varargin)
% RP_GET_INTERSECTION_MASK MATLAB code for rp_get_intersection_mask.fig
%      RP_GET_INTERSECTION_MASK, by itself, creates a new RP_GET_INTERSECTION_MASK or raises the existing
%      singleton*.
%
%      H = RP_GET_INTERSECTION_MASK returns the handle to a new RP_GET_INTERSECTION_MASK or the handle to
%      the existing singleton*.
%
%      RP_GET_INTERSECTION_MASK('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RP_GET_INTERSECTION_MASK.M with the given input arguments.
%
%      RP_GET_INTERSECTION_MASK('Property','Value',...) creates a new RP_GET_INTERSECTION_MASK or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before rp_get_intersection_mask_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to rp_get_intersection_mask_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 rp_get_intersection_mask

% Last Modified by GUIDE v2.5 20-Aug-2021 20:54:29
% Modified by LI Zi-qi 210831
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @rp_get_intersection_mask_OpeningFcn, ...
                   'gui_OutputFcn',  @rp_get_intersection_mask_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(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 rp_get_intersection_mask is made visible.
function rp_get_intersection_mask_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 rp_get_intersection_mask (see VARARGIN)

% Choose default command line output for rp_get_intersection_mask
handles.Cfg.DataDirs ={};
handles.output = hObject;
InitControlProperties(hObject, handles);
% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = rp_get_intersection_mask_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 on selection change in listGroup.
function listGroup_Callback(hObject, eventdata, handles)
% hObject    handle to listGroup (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns listGroup contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listGroup


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

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


% --- Executes on button press in addfodrbtn.
function addfodrbtn_Callback(hObject, eventdata, handles)
% hObject    handle to addfodrbtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if size(handles.Cfg.DataDirs, 1)>0
		theDir =handles.Cfg.DataDirs{1,1};
else
		theDir =pwd;
end
listgroup=get(handles.listGroup,'String');
theDir =uigetdir(theDir,'Please select the Image directory: ');
if theDir~=0
    image_list=dir_NameList(theDir);
    sum_num_nii=0;
    sum_num_img=0;
    for i=1:length(image_list)
        crt_image_path=[theDir filesep image_list{i}];
        [~,~,ext]=fileparts(crt_image_path);
        if ~isempty(ext)
            if strcmp(ext,'.nii')
                sum_num_nii=sum_num_nii+1;
            elseif strcmp(ext,'.img') || strcmp(ext,'.hdr')
                sum_num_img=sum_num_img+1;
            else
                error('Please input nii or img/hdr files!');
            end
        else
            error('input folder only have nii or img/hdr images!');
        end
    end
    sum_num=sum_num_img/2+sum_num_nii;
    listgroup=[listgroup;{[num2str(sum_num) '#' theDir]}];
    set(handles.listGroup,'String',listgroup);
end
SetDataDir(hObject, theDir,handles);

% --- Executes on button press in compute_btn.
function compute_btn_Callback(hObject, eventdata, handles)
% hObject    handle to compute_btn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Prefix=get(handles.prefix_edit,'String');
OutputDir=get(handles.Output_edit,'String');
InputList=get(handles.listGroup,'String');
MaskFile=get(handles.MaskFileEdit,'String');
for i=1:length(InputList)
    tmpInputDir=InputList{i};
    pos=find(tmpInputDir=='#');
    crt_Input=tmpInputDir(pos(1)+1:end);
    rp_intersection_mask_run(crt_Input,MaskFile,OutputDir,Prefix,i);
end


function prefix_edit_Callback(hObject, eventdata, handles)
% hObject    handle to prefix_edit (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 prefix_edit as text
%        str2double(get(hObject,'String')) returns contents of prefix_edit as a double


% --- Executes during object creation, after setting all properties.
function prefix_edit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to prefix_edit (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function Output_edit_Callback(hObject, eventdata, handles)
% hObject    handle to Output_edit (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 Output_edit as text
%        str2double(get(hObject,'String')) returns contents of Output_edit as a double


% --- Executes during object creation, after setting all properties.
function Output_edit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Output_edit (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in Output_btn.
function Output_btn_Callback(hObject, eventdata, handles)
% hObject    handle to Output_btn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
theDirPath =uigetdir('Please select output folder');
set(handles.Output_edit,'String',theDirPath);


function InitControlProperties(hObject, handles)
    handles.hContextMenu =uicontextmenu;
	set(handles.listGroup, 'UIContextMenu', handles.hContextMenu);	
    uimenu(handles.hContextMenu, 'Label', 'Add a directory', 'Callback', get(handles.addfodrbtn, 'Callback'));	
	uimenu(handles.hContextMenu, 'Label', 'Remove selected directory', 'Callback', 'rp_get_intersection_mask(''DeleteSelectedDataDir'',gcbo,[], guidata(gcbo))');
	uimenu(handles.hContextMenu, 'Label', 'Remove all data directories', 'Callback', 'rp_get_intersection_mask(''ClearDataDirectories'',gcbo,[], guidata(gcbo))');
	
	
	% Save handles structure	
	guidata(hObject,handles);
    
function SetDataDir(hObject, ADir,handles)	
	if ~ischar(ADir), return; end	
	theOldWarnings =warning('off', 'all');
    % if (~isequal(ADir , 0)) &&( (size(handles.Cfg.DataDirs, 1)==0)||(0==seqmatch({ADir} ,handles.Cfg.DataDirs( : , 1) ) ) )
	if rp_misc('GetMatlabVersion')>=7.3,
		ADir =strtrim(ADir);
	end	
	if (~isequal(ADir , 0)) &&( (size(handles.Cfg.DataDirs, 1)==0)||(0==length(strmatch(ADir,handles.Cfg.DataDirs( : , 1),'exact' ) ) ))
        handles.Cfg.DataDirs =[ {ADir , 0}; handles.Cfg.DataDirs];%update the dir    
% 		theVolumnCount =rp_CheckDataDir(handles.Cfg.DataDirs{1,1} );	
        theVolumnCount =Get_4DImage_Count(handles.Cfg.DataDirs{1,1} );	
        
		if (theVolumnCount<=0),
			if isappdata(0, 'FC_DoingRecursiveDir') && getappdata(0, 'FC_DoingRecursiveDir'), 
			else
				fprintf('There is no data or non-data files in this directory:\n%s\nPlease re-select\n\n', ADir);
				errordlg( sprintf('There is no data or non-data files in this directory:\n\n%s\n\nPlease re-select', handles.Cfg.DataDirs{1,1} )); 
			end
			handles.Cfg.DataDirs(1,:)=[];
			if size(handles.Cfg.DataDirs, 1)==0
				handles.Cfg.DataDirs=[];
			end	%handles.Cfg.DataDirs = handles.Cfg.DataDirs( 2:end, :);%update the dir        
		else
			handles.Cfg.DataDirs{1,2} =theVolumnCount;
		end	
	
        guidata(hObject, handles);
        UpdateDisplay(handles);
    end
	warning(theOldWarnings);    


function Count=Get_4DImage_Count(InputDir)
Count=length(dir_NameList(InputDir));


function DeleteSelectedDataDir(hObject, eventdata, handles)	
	theIndex =get(handles.listGroup, 'Value');
	if prod(size(handles.Cfg.DataDirs))==0 ...
		|| size(handles.Cfg.DataDirs, 1)==0 ...
		|| theIndex>size(handles.Cfg.DataDirs, 1),
		return;
	end
	theDir     =handles.Cfg.DataDirs{theIndex, 1};
	theVolumnCount=handles.Cfg.DataDirs{theIndex, 2};
	tmpMsg=sprintf('Delete\n\n "%s" \nVolumn Count :%d ?', theDir, theVolumnCount);
	if strcmp(questdlg(tmpMsg, 'Delete confirmation'), 'Yes')
		if theIndex>1,
			set(handles.listGroup, 'Value', theIndex-1);
		end
		handles.Cfg.DataDirs(theIndex, :)=[];
		if size(handles.Cfg.DataDirs, 1)==0
			handles.Cfg.DataDirs={};
		end	
		guidata(hObject, handles);
		UpdateDisplay(handles);
    end
function ClearDataDirectories(hObject, eventdata, handles)	
	if prod(size(handles.Cfg.DataDirs))==0 ...
		|| size(handles.Cfg.DataDirs, 1)==0,		
		return;
	end
	tmpMsg=sprintf('Attention!\n\n\nDelete all data directories?');
	if strcmpi(questdlg(tmpMsg, 'Clear confirmation'), 'Yes'),		
		handles.Cfg.DataDirs(:)=[];
		if prod(size(handles.Cfg.DataDirs))==0,
			handles.Cfg.DataDirs={};
		end	
		guidata(hObject, handles);
		UpdateDisplay(handles);
    end
    
function UpdateDisplay(handles)
	if size(handles.Cfg.DataDirs,1)>0	
		theOldIndex =get(handles.listGroup, 'Value');
		set(handles.listGroup, 'String',  GetInputDirDisplayList(handles) , 'Value', 1);
		theCount =size(handles.Cfg.DataDirs,1);
        if ~isempty(theOldIndex)
            if (theOldIndex>0) && (theOldIndex<= theCount)
                set(handles.listGroup, 'Value', theOldIndex);
            end
        else
            warning('list Group is empty!');
        end
	else
		set(handles.listGroup, 'String', '' , 'Value', 0);
    end

function Result=GetInputDirDisplayList(handles)
	Result ={};
	for x=size(handles.Cfg.DataDirs, 1):-1:1
		Result =[{sprintf('%d#%s',handles.Cfg.DataDirs{x, 2},handles.Cfg.DataDirs{x, 1})} ;Result];
    end



function MaskFileEdit_Callback(hObject, eventdata, handles)
% hObject    handle to MaskFileEdit (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 MaskFileEdit as text
%        str2double(get(hObject,'String')) returns contents of MaskFileEdit as a double


% --- Executes during object creation, after setting all properties.
function MaskFileEdit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MaskFileEdit (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in MaskFileBtn.
function MaskFileBtn_Callback(hObject, eventdata, handles)
% hObject    handle to MaskFileBtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[thefilename,thefilepath] =uigetfile({'*.nii';'*.img'},'Please select a maskfile');
set(handles.MaskFileEdit,'String',[thefilepath thefilename]);
[Outdata,VoxDim,Header]=rp_readfile([thefilepath thefilename]);
if size(Outdata,4)~=1
    warndlg('The input is not 3d mask!');
end
Volume=reshape(Outdata,size(Outdata,1)*size(Outdata,2)*size(Outdata,3),1);
Volume=roundn(Volume,-2);
num1=length(find(Volume==1));
num0=length(find(Volume==0));
allnum=size(Volume,1)*size(Volume,2)*size(Volume,3);
if allnum~=(num1+num0)
    errordlg('The input is not a mask!');
end