function varargout = setup_gui(varargin)
% Configure the parameter of PCA, Mask, scatter removal in GUI window
% Input: 1: [compNumber,subjectNumber,voxelNumber]
% Output: a structure
%       cfg.pcaStepNum   - the number of step in PCA
%       cfg.pcsNum     -  an array containing the number of PCs reserved in
%                         every step
%       cfg.groupSize   - an array contraining the number of subject in one
%       group between 2 and pcaStepNum-1 step
%       cfg.scatter.removeScatter   - Whether to remove scatter
%       cfg.scatter.scatterThreshold    - the threshold to remove scatter
%       cfg.maskType    - the mask type
%       cfg.MaskFile    - the mask file
%
%-------------------------------------------------------------------------
%   Modified by Zhang Han to fix a start error "no field found" (2011/10/28)
%   Contact Zhang Han via E-mail: napoleon1982@gmail.com
%   Copyright (C) 2009
%   Neuroimage Computing Group, State Key Laboratory of
%   Cognitive Neuroscience and Learning, Beijing normal University
%	Written by Guiwen Chen
%	Version=1.0;
%	Release=20090912;
%------------------------------------------------------------------------
%
% SETUP_GUI M-file for setup_gui.fig
%      SETUP_GUI, by itself, creates a new SETUP_GUI or raises the existing
%      singleton*.
%
%      H = SETUP_GUI returns the handle to a new SETUP_GUI or the handle to
%      the existing singleton*.
%
%      SETUP_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SETUP_GUI.M with the given input arguments.
%
%      SETUP_GUI('Property','Value',...) creates a new SETUP_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before setup_gui_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to setup_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 setup_gui

% Last Modified by GUIDE v2.5 12-Sep-2009 21:18:35

% Begin initialization code - DO NOT EDIT

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @setup_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @setup_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 setup_gui is made visible.
function setup_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 setup_gui (see VARARGIN)

% Choose default command line output for setup_gui
handles.output = hObject;
% handles.input = hObject;
if(length(varargin)<1)
    varargin{1}=[20,30,200];
end


invar=varargin{1};

handles.compNum=invar(1);
handles.SubjectNum=invar(2);
handles.timepointNum=invar(3);

%% Initialize the parameter

handles.cfg=struct();

if(length(varargin)>2)
    dataReduction=varargin{3};
    handles.cfg=dataReduction;
    % remove the scatter
    if(~isfield(handles.cfg,'scatter'))
         handles.cfg.scatter.removeScatter=1;
         handles.cfg.scatter.scatterThreshold=0.7;
    end
    if(~isfield(handles.cfg,'samePCWithICA'))
        handles.cfg.samePCWithICA=1;
    end
else
    handles.cfg.maskType=1;
    handles.cfg.MaskFile ='';
    
    % determine the step of PCA by the number of step in PCA
    if(handles.SubjectNum==1)%one sample
        handles.cfg.pcaStepNum=1;
    elseif(handles.SubjectNum<10 && handles.SubjectNum>1)%2~9 samples
        handles.cfg.pcaStepNum=2;
    else %>=10 samples
        handles.cfg.pcaStepNum=3;
    end
    for i=1:handles.cfg.pcaStepNum
        handles.cfg.pcsNum(i)=handles.compNum; % all set as the number of component
    end
    for i=2:1:handles.cfg.pcaStepNum-1
        handles.cfg.groupSize(i-1)=4;% as default, the number of subjects in one group is set to 4
    end
    handles.cfg.samePCWithICA=1;% All the number of PCs is set the same as the number of component
    
    % initialize the parameter of removing scatter
    handles.cfg.scatter.removeScatter=1;
    handles.cfg.scatter.scatterThreshold=0.7;
end

global cfg;
cfg=handles.cfg;

if(length(varargin)>1)
Aoption=varargin{2};
switch lower(Aoption),
    case 'init',    % initialize,
        delete(hObject); % cloase the figure
        return;        
    otherwise,
end
end

% Update handles structure
guidata(hObject, handles);

initControls(hObject,handles); % initialize the control of GUI

% UIWAIT makes setup_gui wait for user response (see UIRESUME)
uiwait(handles.setupCfg);%
if(ishandle(handles.output))
    delete(handles.output); % cloase the figure
end


function initControls(hObject,  handles)
% initialize the controls with the data from the structure 'cfg'

set(handles.IsRemoveScatter,'Value', handles.cfg.scatter.removeScatter);
set(handles.scatterThreshold,'String', num2str(handles.cfg.scatter.scatterThreshold));
set(handles.pcaStepNum,'Value', handles.cfg.pcaStepNum);

pcaStepNum=get(handles.pcaStepNum,'Value');

if(handles.cfg.maskType==2)
    [folder fname fext]=fileparts(handles.cfg.MaskFile);
    set(handles.maskName,'String',[fname,fext]);
end
set(handles.maskType,'Value',handles.cfg.maskType);

if(handles.cfg.samePCWithICA==1)
    set(handles.samePCRadio,'Value',1);
    set(handles.specifyPCRadio,'Value',0);
else
    set(handles.samePCRadio,'Value',0); % as the same with the number of component
    set(handles.specifyPCRadio,'Value',1);% spefify PCs in every step
end


offsetY =200; 
backcolor=[0.925,0.914,0.847];
forcolor=[1 1 1];
handles.pcsNum=[];

   % the edit control 
for i=1:pcaStepNum
    uicontrol(handles.setupCfg,'Style','Text','Tag','pcnum','Position',[20 offsetY-30 240 20],...
		'String',sprintf('Number of PC (step %d)',i),'fontSize',10,...
        'BackgroundColor', backcolor);
    
    handles.pcsNum(i)=uicontrol(handles.setupCfg,'Style','edit','Position',[270 offsetY-30 80 23],...
		'String',sprintf('%d',handles.cfg.pcsNum(i)),'fontSize',10,'BackgroundColor', forcolor);
    if(handles.cfg.samePCWithICA==1)
        set(handles.pcsNum(i),'enable','off');
    else
        set(handles.pcsNum(i),'enable','on');
    end
    
    offsetY=offsetY-35;
end

for i=2:1:pcaStepNum-1
    uicontrol(handles.setupCfg,'Style','Text','Tag','pcstep','Position',[20 offsetY-30 240 20],...
		'String',sprintf('Number of subjects in one group (step %d)',i),'fontSize',10,...
        'BackgroundColor', backcolor);
    
    handles.groupSize(i-1)=uicontrol(handles.setupCfg,'Style','edit','Position',[270 offsetY-30 80 23],...
		'String',sprintf('%d',handles.cfg.groupSize(i-1)),'fontSize',10,'BackgroundColor', forcolor);    
    offsetY=offsetY-35; 
    
end

set(handles.cfgOK,'Units', 'pixels','Position',[150 offsetY-40 60 25]);
set(handles.cfgCancel,'Units', 'pixels','Position',[350 offsetY-40 60 25]);

guidata(hObject, handles);

return;


% --- Outputs from this function are returned to the command line.
function varargout = setup_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
if(isfield(handles,'cfg'))
    varargout{1} = handles.cfg;
else
    global cfg;
    varargout{1} = cfg;
    clear global cfg;
end
% delete(handles.setupCfg);

% --- Executes on selection change in maskType.
function maskType_Callback(hObject, eventdata, handles)
% select the mask
% hObject    handle to maskType (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

maskType=get(hObject,'Value');% get the type

if(maskType==2) % specify the mask
   % start to select mask file
   [filename, pathname] = uigetfile({'*.img;*.nii', 'All Mask files (*.img; *.nii)'; ...
												'*.nii','NIFTI masks (*.nii)'; ...
												'*.img', 'Analyze or NIFTI masks(*.img)'}, ...
												'Please specify a file of mask');
    if ~(filename==0)
        handles.cfg.MaskFile =[pathname filename];
        set(handles.maskName,'String',filename);
        handles.cfg.maskType=2;
        guidata(hObject,handles);    
    else
        set(handles.maskType,'Value',1);
    end    
else
    set(handles.maskName,'String','');
    set(handles.maskName,'String','');
    handles.cfg.MaskFile ='';
    handles.cfg.maskType=1;
    guidata(hObject,handles);
end


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

% 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


% --- Executes on selection change in pcaStepNum.
function pcaStepNum_Callback(hObject, eventdata, handles)
% select the number of step, update the controls in the window
% hObject    handle to pcaStepNum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

pcaStepNumRaw=handles.cfg.pcaStepNum;
for i=1:pcaStepNumRaw
    delete(handles.pcsNum(i));
end

for i=2:1:pcaStepNumRaw-1
    delete(handles.groupSize(i-1));
end

pcaStepNum=get(handles.pcaStepNum,'Value');

handles.cfg.pcaStepNum=pcaStepNum;

offsetY =200; 
backcolor=[0.925,0.914,0.847];
forcolor=[1,1,1];
handles.pcsNum=[];

h = findobj(handles.setupCfg,'Tag','pcnum');

delete(h);
h = findobj(handles.setupCfg,'Tag','pcstep');
delete(h);

% the control to input the number of PCs in every step
for i=1:pcaStepNum
    uicontrol(handles.setupCfg,'Style','Text','Tag','pcnum','Position',[20 offsetY-30 240 20],...
		'String',sprintf('Number of PC (step %d)',i),'fontSize',10,...
        'BackgroundColor', backcolor);
    
    if(i>length(handles.cfg.pcsNum))
        compNu=20;
    else
        compNum=handles.cfg.pcsNum(i);
    end
    handles.pcsNum(i)=uicontrol(handles.setupCfg,'Style','edit','Position',[270 offsetY-30 80 23],...
		'String',sprintf('%d',compNum),'fontSize',10,'BackgroundColor', forcolor);
     if(handles.cfg.samePCWithICA==1)
        set(handles.pcsNum(i),'enable','off');
    else
        set(handles.pcsNum(i),'enable','on');
    end
    offsetY=offsetY-35;
end

% the control to input the number of samples in 2~n-1 group
for i=2:1:pcaStepNum-1
    uicontrol(handles.setupCfg,'Style','Text','Tag','pcstep','Position',[20 offsetY-30 240 20],...
		'String',sprintf('Number of subjects in one group (step %d)',i),'fontSize',10,...
        'BackgroundColor', backcolor);
    if(~isfield(handles.cfg,'groupSize') || i-1>length(handles.cfg.groupSize))
        handles.cfg.groupSize(i-1)=4;
    end
    handles.groupSize(i-1)=uicontrol(handles.setupCfg,'Style','edit','Position',[270 offsetY-30 80 23],...
		'String',sprintf('%d',handles.cfg.groupSize(i-1)),'fontSize',10,'BackgroundColor', forcolor);    
    offsetY=offsetY-35; 
    
end

set(handles.cfgOK,'Units', 'pixels','Position',[150 offsetY-40 60 25]);
set(handles.cfgCancel,'Units', 'pixels','Position',[350 offsetY-40 60 25]);

guidata(hObject, handles);




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

% 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





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

pcaStepNum=get(handles.pcaStepNum,'Value');

handles.cfg.pcaStepNum=pcaStepNum;
for i=1:pcaStepNum
    handles.cfg.pcsNum(i)=str2num(get(handles.pcsNum(i),'String'));
end

for i=2:1:pcaStepNum-1
    handles.cfg.groupSize(i-1)=str2num(get(handles.groupSize(i-1),'String'));
end
handles.cfg.scatter.removeScatter=get(handles.IsRemoveScatter,'Value');
handles.cfg.scatter.scatterThreshold=str2num(get(handles.scatterThreshold,'String'));

guidata(hObject,handles);
global cfg;
cfg=handles.cfg;
uiresume(handles.setupCfg);
if(ishandle(handles.output))
    delete(handles.output);
end

% --- Executes on button press in cfgCancel.
function cfgCancel_Callback(hObject, eventdata, handles)
% press the button 'Cancel'
% hObject    handle to cfgCancel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
uiresume(handles.setupCfg);
if(ishandle(handles.output))
    delete(handles.output);
end


% --- Executes during object deletion, before destroying properties.
function setupCfg_DeleteFcn(hObject, eventdata, handles)
% hObject    handle to setupCfg (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(isfield(handles,'setupCfg'))
    uiresume(handles.setupCfg);
end
if(isfield(handles,'output'))   % modified by Zhang Han 2011/10/28
    delete(handles.output);
end


% --- Executes on button press in IsRemoveScatter.
function IsRemoveScatter_Callback(hObject, eventdata, handles)
% whether to remove some unstable component
% hObject    handle to IsRemoveScatter (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

thre=get(hObject,'Value');
if(thre==1)
    set(handles.scatterThreshold,'Enable','on');
elseif(thre==0)
    set(handles.scatterThreshold,'Enable','off');
end




function ScatterThreshold_Callback(hObject, eventdata, handles)
% hObject    handle to ScatterThreshold (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 ScatterThreshold as text
%        str2double(get(hObject,'String')) returns contents of ScatterThreshold as a double
thre=get(hObject,'String');
if(thre>1 || thre<0)
    errordlg('Please set the threshold correctly (0~1)');
end


% --- Executes during object creation, after setting all properties.
function ScatterThreshold_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ScatterThreshold (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 scatterThreshold_Callback(hObject, eventdata, handles)
% hObject    handle to scatterThreshold (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 scatterThreshold as text
%        str2double(get(hObject,'String')) returns contents of scatterThreshold as a double
the=str2double(get(hObject,'String'));
if(the<=0 && the>=1)
    errordlg('Please set the threshold correctly (0~1)');
end


% --- Executes during object creation, after setting all properties.
function scatterThreshold_CreateFcn(hObject, eventdata, handles)
% hObject    handle to scatterThreshold (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 samePCRadio.
function samePCRadio_Callback(hObject, eventdata, handles)
% select the option of 'same pc with number of component'
% hObject    handle to samePCRadio (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of samePCRadio
handles.cfg.samePCWithICA=1;
set(handles.samePCRadio,'Value',1);
set(handles.specifyPCRadio,'Value',0);

pcaStepNum=get(handles.pcaStepNum,'Value');

for i=1:pcaStepNum    
     if(handles.cfg.samePCWithICA==1)
        set(handles.pcsNum(i),'enable','off');
    else
        set(handles.pcsNum(i),'enable','on');
     end
end

guidata(hObject,handles);

% --- Executes on button press in specifyPCRadio.
function specifyPCRadio_Callback(hObject, eventdata, handles)
% select the option of 'spefify the number PCs'
% hObject    handle to specifyPCRadio (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of specifyPCRadio
handles.cfg.samePCWithICA=0;
set(handles.samePCRadio,'Value',0);
set(handles.specifyPCRadio,'Value',1);
pcaStepNum=get(handles.pcaStepNum,'Value');
for i=1:pcaStepNum    
     if(handles.cfg.samePCWithICA==1)
        set(handles.pcsNum(i),'enable','off');
    else
        set(handles.pcsNum(i),'enable','on');
     end
end

guidata(hObject,handles);

