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

% Last Modified by GUIDE v2.5 23-Aug-2021 21:16:38

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

% Choose default command line output for SelectSub
handles.output = hObject;
set(hObject,'name','ViewComponents')
set(handles.currentPath,'string',pwd);
set(handles.sublist,'String','');
set(handles.compid,'string','','value',1);
set(handles.selecttemp,'value',1);
set(handles.regionnumber,'value',1);

    movegui(hObject, 'center'); 
% UIWAIT makes SelectSub wait for user response (see UIRESUME)
% uiwait(handles.figure1);
guidata(hObject, handles);
 

function initList(handles)
    dirpath=get(handles.currentPath,'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


% Update handles structure

% --- Outputs from this function are returned to the command line.
function varargout = SelectSub_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 currentPath_Callback(hObject, eventdata, handles)


function currentPath_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 workdirbtn_Callback(hObject, eventdata, handles)
 
theDir=get(handles.currentPath,'string');
dirname=uigetdir(theDir,'Please select the result path: ');
 
set(handles.sublist,'String','','value',1);
flag=0;
if ~isequal(dirname,0)
    set(handles.currentPath,'String',dirname);
    outputList=dir(dirname);
    outputList(1:2)=[]; 
    
    
    for i=1:length(outputList)
        if isequal(outputList(i).name,'ComponentsOutput')
            sublist=dir(fullfile(dirname,filesep,outputList(i).name));
            sublist(1:2)=[];
            flag=1;  
            break;
        end


    end

    if flag==1
        for i=1:length(sublist)
            index=get(handles.sublist,'value');
            set(handles.sublist,'String',strvcat(get(handles.sublist,'string'),sublist(i).name),'Value',max(index,1));
%             
%             fig_title=FileName;
        
        end
        tDmatlist='';
        sub_name=get(handles.sublist,'string');
        sub_id=get(handles.sublist,'value');
        filename=strcat(dirname,filesep,'ComponentsOutput',filesep,sub_name(sub_id,:),filesep,'IC');
        filelist=dir(filename);
        filelist(1:2)=[];
        for i=1:length(filelist)
            if endsWith(filelist(i).name,'nii')
                tDmatlist=strvcat(tDmatlist,filelist(i).name);
            end
        end
        if ~isempty(tDmatlist)
            labellist=[];
            for i=1:size(tDmatlist,1)
                [dd, FileName, extn] = fileparts(deblank(tDmatlist(i,:)));
%                 [dd, label_number] = icatb_parseExtn(extn);
                 k=strfind(FileName,'_');
                 label= FileName(k(end)+1:end);
                 labellist=[labellist,str2num(label)];
                 
                 
                 
%                 currentLabel = [FileName, ',', num2str(label_number)];
                 
            end
            labellist=unique(labellist);
            list='';
            for i=1:length(labellist)
                list=strcat(list,num2str(labellist(i)),',');
            end
            list(end)='';
            set(handles.compid,'string',list);
        end
            
    else
        error('there is not exist output component');
        exit;
    end
else
%     set(handles.currentPath,'String',get(handles.currentPath,'String'));
    
end




function sublist_Callback(hObject, eventdata, handles)


function sublist_CreateFcn(hObject, eventdata, handles)

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


function selecttemp_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 regionnumber_Callback(hObject, eventdata, handles)


function regionnumber_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 ok_Callback(hObject, eventdata, handles)

  sub_id=get(handles.sublist,'value');
    sub_name=get(handles.sublist,'string');
    compid=get(handles.compid,'string');
    outputpath=get(handles.currentPath,'string');
% handle the compid

    compID=splitStr(compid);

    message.sub_id=sub_id;
    message.sub_name=sub_name;

    message.outputpath=outputpath;
    message.compID=compID;

    
      %orth parameters
      
      
        fig_dir=fileparts(which('GIGICA'));
        structFile = fullfile(fig_dir, 'template\ch2better_aligned2EPI.nii');
        image_values='positive and negative';
        convert_to_zscores='yes';
        threshold=3;
        load coldhot coldhot ;
        cmap = coldhot(1:4:end, :);
        fnamelist='';
        matlist='';
        templatelist='';
        
        
        for i=1:length(compID)
            fname=strcat(outputpath,filesep,'ComponentsOutput',filesep,sub_name(sub_id,:),filesep,'IC',filesep,sub_name(sub_id,:),'_IC_',num2str(compID(i)),'.nii');
            fnamelist=strvcat(fnamelist,fname);
            
            mat=strcat(outputpath,filesep,'ComponentsOutput',filesep,sub_name(sub_id,:),filesep,'TC',filesep,sub_name(sub_id,:),'_TC_',num2str(compID(i)),'.mat');
            matlist=strvcat(matlist,mat);
            
            
            temp=strcat(get(handles.currentPath,'string'),filesep,'GrouplevelICA',filesep,'Group-level Component',32,num2str(compID(i)),'.nii');
            templatelist=strvcat(templatelist,temp);
            
        end
            fname=strcat(outputpath,filesep,'ComponentsOutput',filesep,sub_name(sub_id,:),filesep,'IC',filesep,sub_name(sub_id,:),'_IC_',num2str(compID(1)),'.nii');

            mat=strcat(outputpath,filesep,'ComponentsOutput',filesep,sub_name(sub_id,:),filesep,'TC',sub_name(sub_id,:),'_TC_',num2str(compID(1)),'.mat');
             
            temp=templatelist(1,:);
             [dd, FileName, extn] = fileparts(deblank(fname));
            
            fig_title=FileName;
            
            
            %template parameters
            
            [tempPath,tempNum]=templateSelcect(handles);
            
            template=fullfile(fig_dir, tempPath);
           
            
            ica_orth_views(fname,mat, 'structfile', structFile, 'image_values',...
                image_values,'convert_to_zscores', convert_to_zscores, 'threshold', threshold, 'set_to_max_voxel', 1, ...
            'labels', '', 'fig_title', fig_title, 'cmap', cmap,'fnamelist',fnamelist,'matlist',matlist,...
            'template',template,'tempNum',tempNum,'templatelist',templatelist,'temp',temp);
   
  function [tempPath,tempNum]= templateSelcect(handles)
    
 tempType=get(handles.selecttemp,'value');
 switch tempType
     case 2
         tempPath=strcat('template',filesep,'AAL',filesep,'aal.nii');
     case 3
         tempPath=strcat('template',filesep,'AAL3',filesep,'AAL3v1.nii');
     case 4
         tempPath=strcat('template',filesep,'BNA',filesep,'BNA_MPM_thr25_1.25mm.nii');
     otherwise
         error('please select atlas!');
         exit;
 end
  tempNumID=get(handles.regionnumber,'value');
  switch tempNumID
     case 2
         tempNum=1;
     case 3
         tempNum=2;
     case 4
         tempNum=3;
     otherwise
         error('please select region number!');
         exit;
  end
function CompID= splitStr(compid)
    compid=strtrim(compid);%Remove leading and trailing Spaces
    compid=strrep(compid,' ',',');

    remain=compid;
    num=0;
    while remain
    [token,remain]=strtok(remain,',');
    CompID(num+1,:)=str2num(token);
    num=num+1;
end 
   


function compid_Callback(hObject, eventdata, handles)


function text10_CreateFcn(hObject, eventdata, handles)

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

% 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
