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

% Last Modified by GUIDE v2.5 08-Nov-2021 11:02:30

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GIGICA_OpeningFcn, ...
                   'gui_OutputFcn',  @GIGICA_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 GIGICA is made visible.
function GIGICA_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 GIGICA (see VARARGIN)

% Choose default command line output for GIGICA
set(hObject,'name','GIG-ICA')
handles.output = hObject;
 
currentPath=strrep(which(mfilename),strcat(mfilename,'.m'),'');

set(hObject,'userdata',currentPath);
set(handles.selectmask,'userdata','1');
 Release='Version_1.0';
    if ispc
        UserName =getenv('USERNAME');
    else
        UserName =getenv('USER');
    end
    Datetime=fix(clock);
    
    fprintf('Welcome: %s, %.4d-%.2d-%.2d %.2d:%.2d \n', UserName,Datetime(1),Datetime(2),Datetime(3),Datetime(4),Datetime(5));
    fprintf('GIGICA.\nRelease = %s\n',Release);
    fprintf('Contact duyuhui@sxu.edu.cn\n');
 
% text(0.5,0.5,'GIGICA',...
%     'Parent',handles.hA,...
%     'FontName','Times New Roman','FontSize',72,...
%     'FontAngle','Italic','FontWeight','Bold',...
%     'Rotation',90,...
%     'VerticalAlignment','Middle',...
%     'HorizontalAlignment','Center',...
%     'Color',[1 1 1]*0.6);

% Update handles structure
init(handles);
guidata(hObject, handles);

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


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



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


% --- Executes during object creation, after setting all properties.
function workdir_CreateFcn(hObject, eventdata, handles)
% hObject    handle to workdir (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 dirpath.
function dirpath_Callback(hObject, eventdata, handles)
% hObject    handle to dirpath (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
theDir=get(handles.workdir,'string');
theDir =uigetdir(theDir, 'Please select the working directory: ');
if ~isequal(theDir, 0)
    set(handles.workdir,'string',theDir);
    set(handles.sublist,'string','','value','default');
    initList(handles);
     h=findall(handles.list_menu,'type','uimenu');
     delete(h);
     uimenu(handles.list_menu,'label','remove selected participant','position',1,...
                'callback',{@reselect_Callback,handles});
else
    warndlg('Please select working directory','Warning Dialog');
    set(handles.workdir,'string','');
    set(handles.sublist,'String','');
    
end


% --- Executes on selection change in sublist.
function sublist_Callback(hObject, eventdata, handles)
% hObject    handle to sublist (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 sublist contents as cell array
%        contents{get(hObject,'Value')} returns selected item from sublist


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


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


% --- Executes during object creation, after setting all properties.
function subIC_CreateFcn(hObject, eventdata, handles)
% hObject    handle to subIC (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 reset.
function reset_Callback(hObject, eventdata, handles)
% hObject    handle to reset (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.workdir,'String',pwd);
set(handles.sublist,'string','','value','default');
set(handles.selectmask,'value',1);
set(handles.maskpath,'enable','off');
set(handles.maskbtn,'visible','off');
set(handles.outputpath,'string',pwd);
set(handles.subPC,'string','');
set(handles.subIC,'string','');
set(handles.maskpath,'string','');


% --- Executes on button press in done.
function done_Callback(hObject, eventdata, handles)
% hObject    handle to done (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 

workpath=get(handles.workdir,'string');
outpath=get(handles.outputpath,'string');

maskEnableState=get(handles.maskpath,'enable');
switch (get(handles.selectmask,'userdata'))
    case '1'
         error('Please select brain mask!');
         exit;
    case '2'
         mask=get(handles.maskpath,'string');
%          copyfile()
    case '3'
         mask='';
end
 



PCnum=get(handles.subPC,'string');
ICnum=get(handles.subIC,'string');
calcuIC.currentPath=get(handles.figure1,'userdata');
if ~isempty(workpath)&&~isempty(outpath)&&~isempty(PCnum)&&~isempty(ICnum)
    calcuIC.sub=get(handles.sublist,'string');
    calcuIC.workpath=workpath;
    calcuIC.outpath=outpath;
    calcuIC.mask=mask;
    calcuIC.PCnum=str2double(PCnum);
    calcuIC.ICnum=str2double(ICnum);
    calcuIC.mini_corr_top=get(handles.top,'string');
    calcuIC.mini_corr_all=get(handles.brain,'string');
    calcuIC.mini_corr_but=get(handles.bottom,'string');
    disp('calculate IC...........');
    if ~isempty(mask)
        maskpath=fullfile(outpath,'BrainMask');
        if ~exist(maskpath,'dir')
            mkdir(maskpath);
        end
           copyfile(mask,maskpath);
    end
    GIG_calculateIC(calcuIC);
    
elseif isempty(workpath)
    error('Please select working directory!');
    exit; 
elseif isempty(outpath)
    error('Please select output path!');
    exit;
elseif isempty(PCnum)
    error('Please input subject-level pc number !');
    exit;
elseif isempty(ICnum)
    error('Please input ic number !');
    exit;
end


function outputpath_Callback(hObject, eventdata, handles)


function outputpath_CreateFcn(hObject, eventdata, handles)

% 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 outputbutton_Callback(hObject, eventdata, handles)

theDir=get(handles.outputpath,'string');
theDir =uigetdir(theDir, 'Please select the output directory: ');
if ~isequal(theDir, 0)
    set(handles.outputpath,'string',theDir);
else
    warndlg('Please select output path','Warning Dialog');
    set(handles.outputpath,'string','');
    
end


%% external functions
function init(handles)
set(handles.workdir,'string',pwd);
set(handles.outputpath,'string',pwd);
set(handles.sublist,'string','');
function initList(handles)
    dirpath=get(handles.workdir,'string');
    subDir=dir(dirpath);
    subDir(1:2)=[]; 
    subDirCell=struct2cell(subDir);
    if ~isempty(subDir)%Load folder only
        n = find(cell2mat(subDirCell(5,:))==0);%Delete the file
         if ~isempty(n)
            subDirCell(:,n)=[];
        end
    end
    for i =1:size(subDirCell,2)%the number of the folder
         index=get(handles.sublist,'value');
         set(handles.sublist,'String',strvcat(get(handles.sublist,'string'),subDirCell{1,i}),'Value',max(index,1))
    end
 function reselect_Callback(hObject, eventdata, handles)
 
subDirlist=get(handles.sublist,'string');

if ~isempty(subDirlist)
    index=get(handles.sublist,'value');
    strs=get(handles.sublist,'string');%character array
    strs(index,:)='';
    set(handles.sublist,'string',strs,'Value',max(1,index-1));%You have to set the value here
end


function list_menu_Callback(hObject, eventdata, handles)


function rmselect_Callback(hObject, eventdata, handles)


function maskpath_Callback(hObject, eventdata, handles)


function maskpath_CreateFcn(hObject, eventdata, handles)

% 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 maskbtn_Callback(hObject, eventdata, handles)
[maskname,maskpath,index]=uigetfile('*.nii','please select mask');
if 0~=index
    mask=fullfile(maskpath,maskname);
    set(handles.maskpath,'string',mask);
    
else
    warndlg('please select mask file','Warning Dialog');
    set(handles.maskpath,'string','');
end    

    


function selectmask_Callback(hObject, eventdata, handles)
 sel=get(hObject,'value');
    switch sel
        case 1
            set(handles.maskpath,'enable','off');
            set(handles.maskpath,'string','');
            set(handles.maskbtn,'visible','off');
            set(handles.selectmask,'userdata','1');
            
           set(handles.threshold,'visible','off');
        case 2
            %use your mask
            set(handles.maskpath,'enable','on');
            set(handles.maskbtn,'visible','on');
           set(handles.selectmask,'userdata','2');
           
           set(handles.threshold,'visible','off');
        case 3
            set(handles.maskpath,'enable','off');
            set(handles.maskbtn,'visible','off');
            set(handles.maskpath,'string','');
            
           set(handles.selectmask,'userdata','3');
           set(handles.threshold,'visible','on');
            
    end

function selectmask_CreateFcn(hObject, eventdata, handles)

% Hint: popupmenu 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 viewbutton_Callback(hObject, eventdata, handles)
viewer;

function reset_CreateFcn(hObject, eventdata, handles)


function top_Callback(hObject, eventdata, handles)


function top_CreateFcn(hObject, eventdata, handles)

% 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 brain_Callback(hObject, eventdata, handles)


function brain_CreateFcn(hObject, eventdata, handles)

% 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 bottom_Callback(hObject, eventdata, handles)


function bottom_CreateFcn(hObject, eventdata, handles)

% 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 help_Callback(hObject, eventdata, handles)
    str='Since good normalization of fMRI data to standard brain template is' ;...
     'necessary to group ICA,we proposed a method to evaluate the normalization';...
     'quality of fMRI data by comparing the individual brain mask with the group brain mask.';...
     ...
     'First, using the 3D image in the first time point of fMRI data, the  ';...
     'individual mask was calculated for each subject by setting the brain ';...
     'voxels showing greater values than 90% of the whole-brain mean to 1. ';...
      ...
     'Then, we generated a group mask by setting voxels included in more than 90% of the individual masks to 1.';...
      ...
      'After that, the spatial correlations between the group mask and the individual mask were evaluated for each subject.The spatial correlations ';...
      'were calculated using the voxels within the top 10 slices of the mask, within the bottom 10 slices of the mask, and within the whole mask, respectively, resulting in three correlation values for each subject.' ;...
      'If a subject had correlations larger than <html><b>0.75</b></html> (default) for the top 10 slices, larger than 0.55 (default) for the bottom 10 slices, and larger than 0.8 (default) for the whole mask, we included this subject for further fMRI analysis. ';...
      'Finally, the group mask of each dataset was computed again based on the selected subjects'' masks. ';...
      '...';...
      'According to our procedure, you can choose different parameters to exclude some subjects. ';
      'Please cite the NeuroMark paper if you use the toolbox.';...
      '(NeuroMark: An automated and adaptive ICA based pipeline to identify reproducible fMRI markers of brain disorders).';
 a=msgbox({
     'Since good normalization of fMRI data to standard brain template is' ;...
     'necessary to group ICA,we proposed a method to evaluate the normalization';...
     'quality of fMRI data by comparing the individual brain mask with the group brain mask.';...
     ...
     'First, using the 3D image in the first time point of fMRI data, the  ';...
     'individual mask was calculated for each subject by setting the brain ';...
     'voxels showing greater values than 90% of the whole-brain mean to 1. ';...
      ...
     'Then, we generated a group mask by setting voxels included in more than 90% of the individual masks to 1.';...
      ...
      'After that, the spatial correlations between the group mask and the individual mask were evaluated for each subject.The spatial correlations ';...
      'were calculated using the voxels within the top 10 slices of the mask, within the bottom 10 slices of the mask, and within the whole mask, respectively, resulting in three correlation values for each subject.' ;...
      'If a subject had correlations larger than 0.75 (default) for the top 10 slices, larger than 0.55 (default) for the bottom 10 slices, and larger than 0.8 (default) for the whole mask, we included this subject for further fMRI analysis. ';...
      'Finally, the group mask of each dataset was computed again based on the selected subjects'' masks. ';...
 
      'According to our procedure, you can choose different parameters to exclude some subjects. ';
      'Please cite the following paper if you use the toolbox.';...
      '(Yuhui Du, Yong Fan. Group information guided ICA for fMRI data analysis.Neuroimage 69, 157-197).';
 },'Help'); 
set(a.Children(1),'string','OK')
    
    
    
