function varargout = view_gui(varargin)
% VIEW_GUI M-file for view_gui.fig
% view the component and ranking of component
% Input: appConfig - structure containing all parameters necessary for
% group
%-----------------------------------------------------------
%   Copyright (C) 2009 Neuroimage Computing Group, State Key Laboratory of
%   Cognitive Neuroscience and Learning
%	Written by Gwen Chen
%	Version=1.0;
%	Release=20090806;
%  Last Revised by Gwen Chen
%-----------------------------------------------------------


gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @view_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @view_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 view_gui is made visible.
function view_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% open the window and configure the GUI
% 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 view_gui (see VARARGIN)

% open the GUI
handles.output = hObject;

appConfig=varargin{1};

subjectList={};
compList={};


compNum=appConfig.compNum;
subjectNum=length(appConfig.AppSubjectLabels);

% update the listbox
subjectList{1}='Aggregate';
subjectList{2}='Mean';
subjectList{3}='Tmap';
subjectList{4}='Std';
for i=1:subjectNum
    subjectList{i+4}=sprintf('Subject %d',i);
end

for i=1:compNum
    compList{i}=sprintf('Component %d',i);
end

set(handles.subjectList,'String',subjectList);
set(handles.componentList,'String',compList);
set(handles.compTypeStr,'visible','off');
set(handles.compTypeCom,'visible','off');
set(handles.templateFile,'Visible','off');
set(handles.templateStr,'Visible','off');
set(handles.selectFile,'Visible','off');
set(handles.templateFile,'String',fullfile(nic_rsdd_misc('WhereIs'),'template','nsingle_subj_T1_2_2_5.nii'));

handles.appConfig=appConfig;

% Update handles structure
guidata(hObject, handles);

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


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


% --- Executes on button press in ExitBut.
function ExitBut_Callback(hObject, eventdata, handles)
% hObject    handle to ExitBut (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% delete(get(0, 'children'));
if(ishandle(handles.output))
    objs=findobj('-regexp','Name',[handles.appConfig.outPrefix,'_\w+']);

    if(~isempty(objs))
        delete(objs);
    end
    delete(handles.output);
end

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


% --- Executes during object creation, after setting all properties.
function SubjectList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SubjectList (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 selection change in ComponentList.
function ComponentList_Callback(hObject, eventdata, handles)
% hObject    handle to ComponentList (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 ComponentList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from ComponentList


% --- Executes during object creation, after setting all properties.
function ComponentList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ComponentList (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 selection change in viewType.
function viewType_Callback(hObject, eventdata, handles)
% select the viewing type 
% hObject    handle to viewType (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 viewType contents as cell array
%        contents{get(hObject,'Value')} returns selected item from viewType
h=get(hObject,'Value');
c=get(handles.compTypeCom,'Value');
if(h==3)
    set(handles.compTypeStr,'visible','on');
    set(handles.compTypeCom,'visible','on');
    set(handles.templateFile,'Visible','on');
    set(handles.templateStr,'Visible','on');
    set(handles.selectFile,'Visible','on');
    set(handles.subjectList,'Enable','on');
    set(handles.componentList,'Enable','off');
    set(handles.HdlExtractComp,'Visible','off');
    if(get(handles.compTypeCom,'Value')==2)
        set(handles.HdlExtractComp,'Visible','on');
    end
    if(c==1)
        set(handles.ButtSortComp,'Visible','on');
        set(handles.ButtIdenComp,'Visible','on');
    else
        set(handles.ButtSortComp,'Visible','off');
        set(handles.ButtIdenComp,'Visible','off');
    end
else
    set(handles.compTypeStr,'visible','off');
    set(handles.compTypeCom,'visible','off');
    set(handles.templateFile,'Visible','off');
    set(handles.templateStr,'Visible','off');
    set(handles.selectFile,'Visible','off');
    set(handles.HdlExtractComp,'Visible','off');
    
    set(handles.ButtSortComp,'Visible','off');
    set(handles.ButtIdenComp,'Visible','off');
end
if(h==1)
     set(handles.subjectList,'Enable','on');
    set(handles.componentList,'Enable','on');
elseif(h==2)
    set(handles.subjectList,'Enable','off');
    set(handles.componentList,'Enable','off');
end


% --- Executes during object creation, after setting all properties.
function viewType_CreateFcn(hObject, eventdata, handles)
% hObject    handle to viewType (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



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


% --- Executes during object creation, after setting all properties.
function templateFile_CreateFcn(hObject, eventdata, handles)
% hObject    handle to templateFile (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 selectTemplate.
function selectTemplate_Callback(hObject, eventdata, handles)
% hObject    handle to selectTemplate (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


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


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


% --- Executes during object creation, after setting all properties.
function subjectList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to subjectList (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 selection change in componentList.
function componentList_Callback(hObject, eventdata, handles)
% hObject    handle to componentList (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 componentList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from componentList


% --- Executes during object creation, after setting all properties.
function componentList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to componentList (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 selectFile.
function selectFile_Callback(hObject, eventdata, handles)
% hObject    handle to selectFile (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[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)
    set(handles.templateFile,'String',fullfile(pathname,filename));
else
    set(handles.templateFile,'String','');
end    
guidata(hObject,handles);    



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

subjectno=get(handles.subjectList,'value');
compno=get(handles.componentList,'value');
viewType=get(handles.viewType,'Value');

disp('---------------------------------------------------------------------');

outDir=handles.appConfig.outDir;
outPrefix=handles.appConfig.outPrefix;
compNum=handles.appConfig.compNum;
runTimes=handles.appConfig.runTimes;
subjectNum=length(handles.appConfig.AppSubjectLabels);


if(viewType==1)%show map after MDS (plot the points in 2-dim space)
    titles='';
    
    % load the data
    if(subjectno==1) % aggregate
        % agg
        icaOut=fullfile(outDir,'mat',sprintf('%s_ica.mat',outPrefix));% load ICA
        dd=load(icaOut,'dists');
        dists=dd.dists;
        dist=dists{compno};
        titles=sprintf('Aggregate, component %d',compno);
        
    elseif(subjectno>4) % indivudual component
        icaOut=fullfile(outDir,'mat',sprintf('%s_ica_br%d.mat',outPrefix,subjectno-4));% load ICA
        dd=load(icaOut,'dists');
        dists=dd.dists;
        dist=dists{compno};
        titles=sprintf('subject %d,component %d',subjectno-4,compno);
    else        
        return;
    end

    if(~isempty(dist))% Draw MDS map
        D=dist.rawDist;
        Y=dist.mds;
        DChanged=dist.scaleDist;

        figure;
        title(titles);
        subplot(2,1,1);
        len=size(Y,1)-1;
        plot(Y(1:len-1,1),Y(1:len-1,2),'b.',Y(len+1,1),Y(len+1,2),'ro');
        title(sprintf(['scale points using mds(',titles,')']));
        axis square;
        
        subplot(2,1,2);
        scatter(D,DChanged,'.','LineWidth',.1);% show the scatter map
        axis square;
        title('Scatter of raw dist and mdsScale dist');

        set(gcf,'Name',[outPrefix,'_mds scatter map']);
        
        if(isfield(dist,'rawDistTC'))%print the MDS map of Timecourse
            D=dist.rawDistTC;
            Y=dist.mdsTC;
            DChanged=dist.scaleDistTC;

            if(subjectno>1)
                figure;
                title([titles,'_TC']);
                subplot(2,1,1);
                len=size(Y,1)-1;
                plot(Y(1:len-1,1),Y(1:len-1,2),'b.',Y(len+1,1),Y(len+1,2),'ro');
                title(sprintf(['scale points using mds(',titles,')']));
                axis square;
%                 axis equal;
                
                subplot(2,1,2);
                scatter(D,DChanged,'.','LineWidth',.1);% show the scatter map
                axis square;
                
                title('Scatter of raw dist and mdsScale dist');

                set(gcf,'Name',[outPrefix,'_mds scatter map (TC)']);
            end
        end
    end
    
elseif(viewType==3)% view components
    
    viewCompType=get(handles.compTypeCom,'Value'); % how to display component
    parameters.viewType=viewCompType;
    if(viewCompType==1)%show all the components of a subject
        if(~isfield(handles,'sortPara'))
          handles.sortPara=nic_rsdd_getCompRanking(handles.appConfig);% How to rank the components
        end
        structuralFile=get(handles.templateFile,'String');
        if(isempty(structuralFile))
            errordlg('Please select the file of template');
            return;
        end
        
        parameters.structFile=structuralFile;
        parameters.compNumbers=[1:compNum];
        parameters.numComp=compNum;
        [data,imagVol] = nic_ReadNiftiImage(structuralFile);
        parameters.imagVol=imagVol;
        clear data;
        
        slicePlane='axial';
        % get the slices in mm for the corresponding plane
        [sliceParameters] = icatb_get_slice_def(imagVol, slicePlane);
        % get the slices in mm
        slices_in_mm = sliceParameters.slices;
        clear sliceParameters;
        % construct string
        slices_in_mm = nic_rsdd_constructString(slices_in_mm);
    
        parameters.compNumbers=[1:compNum];
        parameters.numComp=compNum;

        zipFilePath=outDir;
        if(subjectno==1)
            zipFileName=fullfile(outDir,[outPrefix,'_agg__component_ica_']);            
        elseif(subjectno==2)
            zipFileName=fullfile(outDir,[outPrefix,'_mean_all_component_ica_']);            
        elseif(subjectno==3)
            zipFileName=fullfile(outDir,[outPrefix,'_tmap__component_ica_']);     
        elseif(subjectno==4)
            zipFileName=fullfile(outDir,[outPrefix,'_std__component_ica_']);   
        elseif(subjectno>4)
                  
            labels=handles.appConfig.AppSubjectLabels;
            ulabel=unique(labels);
            if(length(ulabel)>1)
                ind=find(ulabel==labels(subjectno-4));
                zipFileName=fullfile(outDir,'output',sprintf('group%d',ind),sprintf([outPrefix,'_sub%03d_component_ica_s1_'],subjectno-4));
                zipFilePath=fullfile(outDir,'output',sprintf('group%d',ind));
            else
                zipFileName=fullfile(outDir,'output',sprintf([outPrefix,'_sub%03d_component_ica_s1_'],subjectno-4));
                zipFilePath=fullfile(outDir,'output');
            end            
        end
        
        % unzip files
        icatb_unzip([zipFileName,'.zip'], zipFilePath);

        compFiles1=dir([zipFileName,'*.img']);
        files_in_zip1=dir([zipFileName,'*.hdr']);
        if(length(compFiles1)<1)
            compFiles1=dir([zipFileName,'*.nii']);
        end
        
        volumnCount=length(compFiles1);
        compFiles=[];
        files_in_zip={};
        for i=1:volumnCount
             compFiles=[compFiles;fullfile(zipFilePath,compFiles1(i).name)];
             files_in_zip=[files_in_zip;fullfile(zipFilePath,compFiles1(i).name)];
        end
        
        volumnCount=length(files_in_zip1);
         for i=1:volumnCount
             files_in_zip=[files_in_zip;fullfile(zipFilePath,files_in_zip1(i).name)];
         end
         
        str=strrep(zipFileName,sprintf('_component_ica_'),'_timecourses_ica_');
        compFiles2=dir([str,'.img']);
        files_in_zip2=dir([str,'.hdr']);
        if(length(compFiles2)<1)
            compFiles2=dir([str,'*.nii']);
        end
         for i=1:length(compFiles2)
             files_in_zip=[files_in_zip;fullfile(zipFilePath,compFiles2(i).name)];
        end
         for i=1:length(files_in_zip2)
             files_in_zip=[files_in_zip;fullfile(zipFilePath,files_in_zip2(i).name)];
         end
         
        parameters.compFiles=compFiles;
        parameters.outputDir=zipFilePath;
        parameters.filesOutputDir=zipFilePath;    
        parameters.files_in_zip=files_in_zip;
        
        parameters.displayType='component explorer';
        
        parameters.imagevalues='Positive';
        parameters.converttozscores='Yes';
        parameters.thresholdvalue=1;
        parameters.imagesperfigure=4;
        parameters.anatomicalplane='axial';
        parameters.slicerangestr=slices_in_mm;
        parameters.slicerange=str2num(slices_in_mm);
        parameters.returnValue=2;
        parameters.convertToZ=1;
        parameters.compNumbers=handles.sortPara.rankingIndex;
        parameters.compScores=handles.sortPara.rankingScores;

        component_view_gui(parameters);
%         nic_icatb_componentExplore([],parameters);
    elseif(viewCompType==2)%a component of all subjects
        compNo=get(handles.componentList,'Value');
        structuralFile=get(handles.templateFile,'String');
        if(isempty(structuralFile))
            errordlg('Please select the file of template');
            return;
        end
        
        parameters.structFile=structuralFile;
        parameters.compNumbers=[1:compNum];
        parameters.numComp=compNum;
        [data,imagVol] = nic_ReadNiftiImage(structuralFile);
        parameters.imagVol=imagVol;
        clear data;
        
        slicePlane='axial';
        % get the slices in mm for the corresponding plane
        [sliceParameters] = icatb_get_slice_def(imagVol, slicePlane);
        % get the slices in mm
        slices_in_mm = sliceParameters.slices;
        clear sliceParameters;
        % construct string
        slices_in_mm = nic_rsdd_constructString(slices_in_mm);
    
        parameters.compNumbers=compno;
%         parameters.numComp=compNum;
        parameters.imagevalues='Positive';
        parameters.converttozscores='Yes';
        parameters.thresholdvalue=1;
        parameters.imagesperfigure=4;
        parameters.anatomicalplane='axial';
        parameters.slicerangestr=slices_in_mm;
        parameters.slicerange=str2num(slices_in_mm);
        parameters.returnValue=2;
        parameters.convertToZ=1;
        
        component_view_gui(parameters,handles.appConfig);
        
    elseif(viewCompType==3)%show a component of a subject
       %extract the files
            zipFilePath=outDir;
            if(subjectno==1)
                zipFileName=[outPrefix,'_agg__component_ica_'];            
            elseif(subjectno==2)
                    zipFileName=[outPrefix,'_mean_all_component_ica_'];            
                elseif(subjectno==3)
                    zipFileName=[outPrefix,'_tmap__component_ica_'];     
                elseif(subjectno==4)
                    zipFileName=[outPrefix,'_std__component_ica_'];   

             else
                 subjectn=subjectno-4;
                labels=handles.appConfig.AppSubjectLabels;
                ulabel=unique(labels);
                if(length(ulabel)>1)
                   ind=find(ulabel==labels(subjectn));
                   zipFileName=sprintf([outPrefix,'_sub%03d_component_ica_s1_'],subjectn);
                   zipFilePath=fullfile(outDir,'output',sprintf('group%d',ind));
                else
                   zipFileName=sprintf([outPrefix,'_sub%03d_component_ica_s1_'],subjectn);
                   zipFilePath=fullfile(outDir,'output');
                end   
             end
             if(isunix)
                 zipFileName1=fullfile(zipFilePath,[zipFileName '.zip']);
                 zipfile=sprintf([zipFileName,'%03d.*'],compno);
                 system(['unzip -jqu ',zipFileName1,' ',zipfile,' -d ',zipFilePath]);
             else
                  zipFileName1=fullfile(zipFilePath,[zipFileName '.zip']);
                  zipfile=sprintf([zipFileName,'%03d.*'],compno);
                   nic_unzipFile(zipFileName1,zipfile,zipFilePath);
             end
             
            zipFileName1=fullfile(zipFilePath,zipFileName);
            compFiles1=dir([zipFileName1,'*.img']);
            files_in_zip1=dir([zipFileName1,'*.hdr']);
            if(length(compFiles1)<1)
                compFiles1=dir([zipFileName1,'*.nii']);
            end
            volumnCount=length(compFiles1);
            compFiles=[];
            files_in_zip={};
            for ii=1:volumnCount
                  compFiles=fullfile(zipFilePath,compFiles1(ii).name);
                  files_in_zip=[files_in_zip;fullfile(zipFilePath,compFiles1(ii).name)];
            end
            for i=1:length(files_in_zip1)
                files_in_zip=[files_in_zip;fullfile(zipFilePath,files_in_zip1(i).name)];
            end
           
           
           cfg=nic_rsdd_sliceViewer_ParaSel();
           
           par=struct('converToZ',1,'returnValue',cfg.returnValue);
           
           hFig =nic_rest_sliceviewer('ShowImage','',par);
           tPath=fullfile(nic_rest_misc( 'WhereIsREST'),'Template', 'ch2.img');
           nic_rest_sliceviewer('UnderlayFile',tPath, hFig);
           nic_rest_sliceviewer('OverlayFile',compFiles, hFig);    
           nic_rest_sliceviewer('Overlay_SetThresholdValue',cfg.threshold, hFig);    
           
           % delete file
           for i=1:length(files_in_zip)
               if(exist(files_in_zip{i},'file'))
                delete(files_in_zip{i});
               end
           end
           
    end
%     parameters.sortParameters=2;
elseif(viewType==2)% ranking components
    nic_rsdd_showAggCompRanking(handles.appConfig);
end
guidata(hObject,handles);


% --- Executes on selection change in compTypeCom.
function compTypeCom_Callback(hObject, eventdata, handles)
% hObject    handle to compTypeCom (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 compTypeCom contents as cell array
%        contents{get(hObject,'Value')} returns selected item from compTypeCom
viewType=get(hObject,'Value');
h=get(handles.viewType,'Value');
set(handles.ButtSortComp,'Visible','off');
set(handles.ButtIdenComp,'Visible','off');
if(viewType==1)
    set(handles.subjectList,'Enable','on');
    set(handles.componentList,'Enable','off');
    set(handles.HdlExtractComp,'Visible','off');
    if(h==3)
        set(handles.ButtSortComp,'Visible','on');
        set(handles.ButtIdenComp,'Visible','on');
    end
elseif(viewType==2)
    set(handles.subjectList,'Enable','off');
    set(handles.componentList,'Enable','on');
    set(handles.HdlExtractComp,'Visible','on');
elseif(viewType==3)
    set(handles.subjectList,'Enable','on');
    set(handles.componentList,'Enable','on');
    set(handles.HdlExtractComp,'Visible','off');
end

% --- Executes during object creation, after setting all properties.
function compTypeCom_CreateFcn(hObject, eventdata, handles)
% hObject    handle to compTypeCom (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 HdlExtractComp.
function HdlExtractComp_Callback(hObject, eventdata, handles)
% extract a component of all subjects into a file folder
%
% hObject    handle to HdlExtractComp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

appConfig=handles.appConfig;
compno=get(handles.componentList,'Value');
outDir=appConfig.outDir;
cf=selectDirectory_gui('initDir',outDir);

if(~isfield(cf,'execute') || cf.execute==0)
    return;
end
outPrefix=appConfig.outPrefix;
compNum=appConfig.compNum;
runTimes=appConfig.runTimes;
subjectNum=length(appConfig.AppSubjectLabels);
numComp=subjectNum+3;

fileP=fullfile(outDir,'output');
counter=0;
TC=struct();
TC.subjectNumber=subjectNum;
TC.data=[];

for subji=1:numComp
    files_in_zip={};
    counter=counter+1;
     if(subji<4)
        zipFilePath=outDir;
        if(subji==1)
            zipFileName=[outPrefix,'_mean_all_component_ica_'];            
        elseif(subji==2)
            zipFileName=[outPrefix,'_tmap__component_ica_'];     
        elseif(subji==3)
            zipFileName=[outPrefix,'_std__component_ica_'];   
        end
        continue;
     else
        subjectn=subji-3;
        labels=appConfig.AppSubjectLabels;
        ulabel=unique(labels);
        if(length(ulabel)>1)
           ind=find(ulabel==labels(subjectn));  % fixed a bug 2012/7/12
           zipFileName=sprintf([outPrefix,'_sub%03d_component_ica_s1_'],subjectn);
           zipFilePath=fullfile(outDir,'output',sprintf('group%d',ind));
           if(~exist(fullfile(cf.outDir,sprintf('group%d',ind),'dir')))
               mkdir(fullfile(cf.outDir,sprintf('group%d',ind)));
           end
        else
           zipFileName=sprintf([outPrefix,'_sub%03d_component_ica_s1_'],subjectn);
           zipFilePath=fullfile(outDir,'output');
        end   
     end
     if(isunix)
         zipFileName1=fullfile(zipFilePath,[zipFileName '.zip']);
         zipfile=sprintf([zipFileName,'%03d.*'],compno);
         system(['unzip -jqu ',zipFileName1,' ',zipfile,' -d ',zipFilePath]);
         zipfile=sprintf([zipFileName,'.*'],compno);
         zipfile=strrep(zipfile,'_component_ica_','_timecourses_ica_');
         system(['unzip -jqu ',zipFileName1,' ',zipfile,' -d ',zipFilePath]); % extract timecourses
     else
          zipFileName1=fullfile(zipFilePath,[zipFileName '.zip']);
         zipfile=sprintf([zipFileName,'%03d.*'],compno);
         zipfile1=sprintf([zipFileName,'.*'],compno);
         zipfile1=strrep(zipfile1,'_component_ica_','_timecourses_ica_');
          nic_unzipFile(zipFileName1,zipfile,zipFilePath,zipfile1);
     end

    zipFileName1=fullfile(zipFilePath,zipFileName);
    compFiles1=dir([zipFileName1,'*.img']);
    files_in_zip1=dir([zipFileName1,'*.hdr']);
    if(length(compFiles1)<1)
        compFiles1=dir([zipFileName1,'*.nii']);
    end
    volumnCount=length(compFiles1);
    compFiles=[];
    files_in_zip={};
    for ii=1:volumnCount
          compFiles=[compFiles;fullfile(zipFilePath,compFiles1(ii).name)];
          files_in_zip=[files_in_zip;fullfile(zipFilePath,compFiles1(ii).name)];
    end
    volumnCount=length(files_in_zip1);
     for ii=1:volumnCount
         files_in_zip=[files_in_zip;fullfile(zipFilePath,files_in_zip1(ii).name)];
     end
     
     nic_waitbar(subji/numComp,sprintf('Extracting the components\nplease wait...'), 'Component extraction','Child');
    

     if ~isempty(files_in_zip) % move files
        for ii = 1:length(files_in_zip)
            str=files_in_zip{ii};
            if(exist(str,'file'))
                %delete(str);% delete the files
                str1=strrep(str,fullfile(outDir,'output'),cf.outDir);
                movefile(str,str1);% move the files to the target directory
            end
            % get the file name of timecourses
            [str1 str2 str3]=fileparts(str);
            str2=strrep(str2,'_component_ica_','_timecourses_ica_');
            if(~isempty(strmatch(str2(end-2:end),sprintf('%03d',compno))))
                str2=str2(1:end-3);
            end

            str=fullfile(str1,[str2,str3]);                   
            if(exist(str,'file'))
                if(~strcmpi(str3,'.hdr'))
                    tc=nic_ReadNiftiImage(str);
                    TC.data=[TC.data,tc(:,compno)];
                    TC.timecourseLength=size(tc,1);
                end
                delete(str); % delete files of timecourse
            end
        end
     end
end
save(fullfile(cf.outDir,sprintf(outPrefix,'_ica_timecourses_%03d.mat',compno)),'TC');
nic_waitbar;
    
function  nic_unzipFile(zipFileName,zipfile,zipFilePath,zipfile1)
% unzip files
    fileNames=unzip(zipFileName,zipFilePath);
    ln=dir(fullfile(zipFilePath,zipfile));
    if(exist('zipfile1','var'))
        ln1=dir(fullfile(zipFilePath,zipfile1));
        ln=[ln;ln1];
    end
    for i=1:length(fileNames)
        k=0;
        for j=1:length(ln)
            k=k+1;
           [fp,fn,fext]=fileparts(fileNames{i});
           fn=[fn,fext];
           if(strmatch(fn,ln(j).name)) 
             k=k-1;
              break;  
           end
        end
        if(k==length(ln))
            delete(fileNames{i});
        end
    end

return;




% --- Executes on button press in ButtSortComp.
function ButtSortComp_Callback(hObject, eventdata, handles)
% hObject    handle to ButtSortComp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
subjectno=get(handles.subjectList,'value');

disp('---------------------------------------------------------------------');

outDir=handles.appConfig.outDir;
outPrefix=handles.appConfig.outPrefix;
compNum=handles.appConfig.compNum;
runTimes=handles.appConfig.runTimes;
subjectNum=length(handles.appConfig.AppSubjectLabels);

para=nic_rsdd_sortPara();



disp('Sort components');





% --- Executes on button press in ButtIdenComp.
function ButtIdenComp_Callback(hObject, eventdata, handles)
% hObject    handle to ButtIdenComp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
subjectno=get(handles.subjectList,'value');

disp('---------------------------------------------------------------------');

outDir=handles.appConfig.outDir;
outPrefix=handles.appConfig.outPrefix;
compNum=handles.appConfig.compNum;
runTimes=handles.appConfig.runTimes;
subjectNum=length(handles.appConfig.AppSubjectLabels);
disp('Idendentify components');

[a] = nic_rsdd_idenfifyCompPara();

% extract files, unzip files
zipFileName=fullfile(outDir,[outPrefix,'_mean_all_component_ica_']);            
zipFileName=fullfile(outDir,[outPrefix,'_tmap__component_ica_']);     
zipFilePath=outDir;                 
icatb_unzip([zipFileName,'.zip'], zipFilePath);

        
threshold=1.5;

[ICNOs]=nic_removeNoiseComponent(compNum,dim,outPrefix,threshold,zipFilePath,a);


% 得到成分编号
% 并显示出来



