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

% Last Modified by GUIDE v2.5 29-May-2021 18:05:32

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @rp_flip_image_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @rp_flip_image_gui_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_flip_image_gui is made visible.
function rp_flip_image_gui_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_flip_image_gui (see VARARGIN)
handles.Cfg.DataDirs ={};
InitControlProperties(hObject, handles);

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

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = rp_flip_image_gui_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

function InitControlProperties(hObject, handles)
    handles.hContextMenu =uicontextmenu;
	set(handles.listGroup, 'UIContextMenu', handles.hContextMenu);	
    uimenu(handles.hContextMenu, 'Label', 'Add Directory', 'Callback', get(handles.addfolderbtn, 'Callback'));
	uimenu(handles.hContextMenu, 'Label', 'Remove selected directory', 'Callback', 'rp_flip_image_gui(''DeleteSelectedDataDir'',gcbo,[], guidata(gcbo))');
	uimenu(handles.hContextMenu, 'Label', 'Remove all data directories', 'Callback', 'rp_flip_image_gui(''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
% --- Executes on button press in addimagebtn.
% function addimagebtn_Callback(hObject, eventdata, handles)
% % hObject    handle to addimagebtn (see GCBO)
% % eventdata  reserved - to be defined in a future version of MATLAB
% % handles    structure with handles and user data (see GUIDATA)
% listgroup=handles.listGroup.String;
% [theImageName,theImagePath] =uigetfile({'*.nii';'*.img';'*.*'},'Please select an nii or img/hdr Image file');
% if theImageName~=0
%     listgroup=[listgroup;{[theImagePath theImageName]}];
%     handles.listGroup.String=listgroup;
% end



% --- Executes on button press in addfolderbtn.
function addfolderbtn_Callback(hObject, eventdata, handles)
% hObject    handle to addfolderbtn (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 run_btn.
function run_btn_Callback(hObject, eventdata, handles)
% hObject    handle to run_btn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
list_Group=get(handles.listGroup,'String');
OutputDir=get(handles.outedit,'String');
if OutputDir=='0'
    OutputDir=pwd;
end
prefix=get(handles.outprefixedit,'String');
for i=1:length(list_Group)
    crt_img_dir=list_Group{i};
    k=find(crt_img_dir=='#');
    Input=crt_img_dir(k(1)+1:end);
    if isdir(Input)
        [~,filename,~]=fileparts(Input);
    end
    
    rp_flip_images_4D(Input,OutputDir,prefix);
end


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


% --- Executes during object creation, after setting all properties.
function outprefixedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to outprefixedit (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 outedit_Callback(hObject, eventdata, handles)
% hObject    handle to outedit (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 outedit as text
%        str2double(get(hObject,'String')) returns contents of outedit as a double




% --- Executes during object creation, after setting all properties.
function outedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to outedit (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 outputbtn.
function outputbtn_Callback(hObject, eventdata, handles)
% hObject    handle to outputbtn (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
OutputDir =uigetdir('Please select the output directory: ');
set(handles.outedit,'String',OutputDir);
