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

% Last Modified by GUIDE v2.5 17-Jul-2020 03:36:01

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @rp_MixedEffectsAnalysis_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @rp_MixedEffectsAnalysis_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_MixedEffectsAnalysis_gui is made visible.
function rp_MixedEffectsAnalysis_gui_OpeningFcn(hObject, eventdata, handles, varargin)
handles.Cfg.GroupDirs ={};
handles.Cfg.CovariateDirs ={};
handles.Cfg.OtherTxt = {};
handles.Cfg.MaskFile = '';
handles.Cfg.OutputDir=pwd;
handles.Cfg.OutputName='M';
handles.output = hObject;

% Make Display correct in linux - YAN Chao-Gan 111025 Added.
if ~ispc
    ZoomFactor=0.85;
    ObjectNames = fieldnames(handles);
    for i=1:length(ObjectNames);
        eval(['IsFontSizeProp=isprop(handles.',ObjectNames{i},',''FontSize'');']);
        if IsFontSizeProp
            eval(['PCFontSize=get(handles.',ObjectNames{i},',''FontSize'');']);
            FontSize=PCFontSize*ZoomFactor;
            eval(['set(handles.',ObjectNames{i},',''FontSize'',',num2str(FontSize),');']);
        end
    end
end

InitControlProperties(hObject, handles);
guidata(hObject, handles);



function varargout = rp_MixedEffectsAnalysis_gui_OutputFcn(hObject, eventdata, handles) 
varargout{1} = handles.output;


function btn_add_group_Callback(hObject, eventdata, handles)
lenC=size(handles.Cfg.GroupDirs);
if lenC(1) >=4
    msgbox('Only four groups are allowed in Mixed Effect Analysis.','Warning');
else
    if size(handles.Cfg.GroupDirs, 1)>0
        theDir =handles.Cfg.GroupDirs{1,1};
    else
        theDir =pwd;
    end
    theDir =uigetdir(theDir, 'Please select the data directory to compute: ');
    if ischar(theDir),
        SetDataDir(hObject, theDir,handles);
    end
end


function list_group_Callback(hObject, eventdata, handles)

function list_group_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in btn_compute.
function btn_compute_Callback(hObject, eventdata, handles)
lenG=size(handles.Cfg.GroupDirs);
lenC=size(handles.Cfg.CovariateDirs);
lenO=size(handles.Cfg.OtherTxt);
if lenG(1)>0
    for i=1:lenG(1)
        DependentDirs(i)=handles.Cfg.GroupDirs(i,1);
    end
else
    DependentDirs={};
end
if lenC(1)>0
    for i=1:lenC(1)
        CovariateDirs(i)=handles.Cfg.CovariateDirs(i,1);
    end
else
    CovariateDirs={};
end
if lenO(1)>0
    for i=1:lenO(1)
        OtherCovariates{i,1}=load(handles.Cfg.OtherTxt{i,1});
    end
else
    OtherCovariates={};
end
MaskFile=handles.Cfg.MaskFile;
outname=get(handles.edit_otnam, 'String');
OutputName=[handles.Cfg.OutputDir,filesep,outname];
% try
%     theOldColor=get(hObject,'BackgroundColor');
%     set(hObject,'Enable','off', 'BackgroundColor', 'red');
%     set(handles.btn_add_group,'Enable','off');
%     set(handles.btn_addcovimg,'Enable','off');
%     set(handles.btn_addothercov,'Enable','off');
%     set(handles.btn_mskfile,'Enable','off');
%     set(handles.btn_otdr,'Enable','off');
%     drawnow;
rp_MixedEffectsAnalysis_Image(DependentDirs,OutputName,...
    MaskFile,CovariateDirs,OtherCovariates);
%     set(hObject,'Enable','on', 'BackgroundColor', theOldColor);
%     set(handles.btn_add_group,'Enable','on');
%     set(handles.btn_addcovimg,'Enable','on');
%     set(handles.btn_addothercov,'Enable','on');
%     set(handles.btn_mskfile,'Enable','on');
%     set(handles.btn_otdr,'Enable','on');
drawnow;
% catch
%     msgbox ('Please match the dims','Tip');
% end


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


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


% --- Executes during object creation, after setting all properties.
function edit_otdr_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_otdr (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 btn_otdr.
function btn_otdr_Callback(hObject, eventdata, handles)
theDir =handles.Cfg.OutputDir;
theDir =uigetdir(theDir, 'Please select the output directory: ');
if ~isequal(theDir, 0)
    set_otdr(hObject,handles, theDir);
end

function set_otdr(hObject, handles, ADir)
if 7==exist(ADir,'dir')
    handles.Cfg.OutputDir =ADir;
    set(handles.edit_otdr,'String',ADir);
    guidata(hObject, handles);
    UpdateDisplay(handles);
end


% --- Executes on button press in btn_help.
function btn_help_Callback(hObject, eventdata, handles)
        msgbox({'Mixed Effect Analysis:';...
            'Perform the within-subject between-subject mixed effect anlaysis.';...
            'The order of the group images should be: Group1Condition1; Group1Condition2; Group2Condition1; Group2Condition2';...
            '*_ConditionEffect_T.nii/gii - the T values of condition differences (corresponding to the first condition minus the second condition) (WithinSubjectFactor)';...
            '*_Interaction_F.nii/gii - the F values of interaction (BetweenSubjectFactor by WithinSubjectFactor)';...
            '*_Group_TwoT.nii/gii - the T values of group differences (corresponding to the first group minus the second group). Of note: the two conditions will be averaged first for each subject. (BetweenSubjectFactor)';...
            'The degree of freedom information is stored in the header of the output image file.';...
            },'Help');


% --- Executes on button press in btn_addcovimg.
function btn_addcovimg_Callback(hObject, eventdata, handles)
lenC=size(handles.Cfg.CovariateDirs);
if lenC(1) >=4
    msgbox('Only four group of covariate images are allowed in Mixed Effect Analysis.','Warning');
else
    if size(handles.Cfg.CovariateDirs, 1)>0
        theDir =handles.Cfg.CovariateDirs{1,1};
    else
        theDir =pwd;
    end
    theDir =uigetdir(theDir, 'Please select the data directory to compute: ');
    if ischar(theDir),

        SetICDataDir(hObject, theDir,handles);
    end
end


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


% --- Executes during object creation, after setting all properties.
function lst_covimg_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lst_covimg (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 btn_addothercov.
function btn_addothercov_Callback(hObject, eventdata, handles)
lenC=size(handles.Cfg.OtherTxt);
if lenC(1) >=4
    msgbox('Only four text covariates files are allowed in Mixed Effect Analysis.','Warning');
else
    [filename, pathname] = uigetfile({'*.txt', 'Text covariates (*.txt)';}, ...
        'Pick a user''s  txt');
    if ~(filename==0)
        handles.Cfg.OtherTxt =[ handles.Cfg.OtherTxt;{[pathname filename]}];
        guidata(hObject,handles);
    end
    UpdateDisplay(handles);
end


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


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


% --- Executes during object creation, after setting all properties.
function edit_mskfile_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_mskfile (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 btn_mskfile.
function btn_mskfile_Callback(hObject, eventdata, handles)
[filename, pathname] = uigetfile({'*.img;*.nii;*.nii.gz','Brain Image Files (*.img;*.nii;*.nii.gz)';'*.*', 'All Files (*.*)';}, ...
    'Pick a user''s  mask');
if ~(filename==0)
    handles.Cfg.MaskFile =[pathname filename];
    set(handles.edit_mskfile, 'String', handles.Cfg.MaskFile); 
    guidata(hObject,handles);
end

function InitControlProperties(hObject, handles)
handles.hContextMenu =uicontextmenu;
set(handles.list_group, 'UIContextMenu', handles.hContextMenu);
uimenu(handles.hContextMenu, 'Label', 'Add a group', 'Callback', get(handles.btn_add_group, 'Callback'));
uimenu(handles.hContextMenu, 'Label', 'Remove selected group', 'Callback', 'rp_MixedEffectsAnalysis_gui(''DeleteSelectedG'',gcbo,[], guidata(gcbo))');
uimenu(handles.hContextMenu, 'Label', '=============================');
uimenu(handles.hContextMenu, 'Label', 'Remove all data groups', 'Callback', 'rp_MixedEffectsAnalysis_gui(''ClearG'',gcbo,[], guidata(gcbo))');

handles.hContextMenui =uicontextmenu;
set(handles.lst_covimg, 'UIContextMenu', handles.hContextMenui);
uimenu(handles.hContextMenui, 'Label', 'Add a covariate', 'Callback', get(handles.btn_addcovimg, 'Callback'));
uimenu(handles.hContextMenui, 'Label', 'Remove selected covariate', 'Callback', 'rp_MixedEffectsAnalysis_gui(''DeleteSelectedIC'',gcbo,[], guidata(gcbo))');
uimenu(handles.hContextMenui, 'Label', '=============================');
uimenu(handles.hContextMenui, 'Label', 'Remove all covariates', 'Callback', 'rp_MixedEffectsAnalysis_gui(''ClearIC'',gcbo,[], guidata(gcbo))');

handles.hContextMenui =uicontextmenu;
set(handles.list_addcov, 'UIContextMenu', handles.hContextMenui);
uimenu(handles.hContextMenui, 'Label', 'Add a covariate', 'Callback', get(handles.btn_addothercov, 'Callback'));
uimenu(handles.hContextMenui, 'Label', 'Remove selected covariate', 'Callback', 'rp_MixedEffectsAnalysis_gui(''DeleteSelectedOC'',gcbo,[], guidata(gcbo))');
uimenu(handles.hContextMenui, 'Label', '=============================');
uimenu(handles.hContextMenui, 'Label', 'Remove all covariates', 'Callback', 'rp_MixedEffectsAnalysis_gui(''ClearOC'',gcbo,[], guidata(gcbo))');

set(handles.edit_mskfile, 'String', handles.Cfg.MaskFile);
set(handles.edit_otdr, 'String', handles.Cfg.OutputDir);
set(handles.edit_otnam, 'String', handles.Cfg.OutputName);
guidata(hObject,handles);


function SetDataDir(hObject, ADir,handles)
if ~ischar(ADir), return; end
theOldWarnings =warning('off', 'all');
if rp_misc('GetMatlabVersion')>=7.3,
    ADir =strtrim(ADir);
end
if (~isequal(ADir , 0)) &&( (size(handles.Cfg.GroupDirs, 1)==0)||(0==length(strmatch(ADir,handles.Cfg.GroupDirs( : , 1),'exact' ) ) ))
    handles.Cfg.GroupDirs =[handles.Cfg.GroupDirs;{ADir , 0}];%update the dir
    tmpSize=size(handles.Cfg.GroupDirs);
    theVolumnCount =rp_CheckDataDir(handles.Cfg.GroupDirs{tmpSize(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',ADir ));
        end
        handles.Cfg.GroupDirs(tmpSize(1),:)=[];
        if size(handles.Cfg.GroupDirs, 1)==0
            handles.Cfg.GroupDirs=[];
        end
    else
        handles.Cfg.GroupDirs{tmpSize(1),2} =theVolumnCount;
    end
    guidata(hObject, handles);
    UpdateDisplay(handles);
end
warning(theOldWarnings);

function SetICDataDir(hObject, ADir,handles)
if ~ischar(ADir), return; end
theOldWarnings =warning('off', 'all');
if rp_misc('GetMatlabVersion')>=7.3,
    ADir =strtrim(ADir);
end
if (~isequal(ADir , 0)) &&( (size(handles.Cfg.CovariateDirs, 1)==0)||(0==length(strmatch(ADir,handles.Cfg.CovariateDirs( : , 1),'exact' ) ) ))
    handles.Cfg.CovariateDirs =[handles.Cfg.CovariateDirs;{ADir , 0}];%update the dir
    tmpSize=size(handles.Cfg.CovariateDirs);
    theVolumnCount =rp_CheckDataDir(handles.Cfg.CovariateDirs{tmpSize(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',ADir ));
        end
        handles.Cfg.CovariateDirs(tmpSize(1),:)=[];
        if size(handles.Cfg.CovariateDirs, 1)==0
            handles.Cfg.CovariateDirs=[];
        end
    else
        handles.Cfg.CovariateDirs{tmpSize(1),2} =theVolumnCount;
    end
    guidata(hObject, handles);
    UpdateDisplay(handles);
end
warning(theOldWarnings);

function SetOCDataDir(hObject, ADir,handles)
if ~ischar(ADir), return; end
theOldWarnings =warning('off', 'all');
if rp_misc('GetMatlabVersion')>=7.3,
    ADir =strtrim(ADir);
end
if (~isequal(ADir , 0)) &&( (size(handles.Cfg.OtherTxt, 1)==0)||(0==length(strmatch(ADir,handles.Cfg.OtherTxt( : , 1),'exact' ) ) ))
    handles.Cfg.OtherTxt =[handles.Cfg.OtherTxt;{ADir , 0}];%update the dir
    tmpSize=size(handles.Cfg.OtherTxt);
    theVolumnCount =CheckTDataDir(handles.Cfg.OtherTxt{tmpSize(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',ADir ));
        end
        handles.Cfg.OtherTxt(tmpSize(1),:)=[];
        if size(handles.Cfg.OtherTxt, 1)==0
            handles.Cfg.OtherTxt=[];
        end
    else
        handles.Cfg.OtherTxt{tmpSize(1),2} =theVolumnCount;
    end
    guidata(hObject, handles);
    UpdateDisplay(handles);
end
warning(theOldWarnings);

function UpdateDisplay(handles)
if size(handles.Cfg.GroupDirs,1)>0
    theOldIndex =get(handles.list_group, 'Value');
    set(handles.list_group, 'String',  GetInputDirDisplayList(handles) , 'Value', 1);
    theCount =size(handles.Cfg.GroupDirs,1);
    if (theOldIndex>0) && (theOldIndex<= theCount)
        set(handles.list_group, 'Value', theOldIndex);
    end
else
    set(handles.list_group, 'String', '' , 'Value', 0);
end

if size(handles.Cfg.CovariateDirs)>0
    theOldIndexi =get(handles.lst_covimg, 'Value');%here
    set(handles.lst_covimg, 'String',  GetInputICDisplayList(handles) , 'Value', 1);
    theCount =size(handles.Cfg.CovariateDirs,1);
    if (theOldIndexi>0) && (theOldIndexi<= theCount)
        set(handles.lst_covimg, 'Value', theOldIndexi);
    end
else
    set(handles.lst_covimg, 'String', '' , 'Value', 0);
end

if size(handles.Cfg.OtherTxt)>0
    theOldIndext =get(handles.list_addcov, 'Value');%here
    set(handles.list_addcov, 'String',  GetInputOCDisplayList(handles) , 'Value', 1);
    theCount =size(handles.Cfg.OtherTxt,1);
    if (theOldIndext>0) && (theOldIndext<= theCount)
        set(handles.list_addcov, 'Value', theOldIndext);
    end
else
    set(handles.list_addcov, 'String', '' , 'Value', 0);
end



function Result=GetInputDirDisplayList(handles)
Result ={};
for x=size(handles.Cfg.GroupDirs, 1):-1:1
    switch x
        case 1 
            g=1;c=1;
        case 2
            g=1;c=2;
        case 3
            g=2;c=1;
        case 4
            g=2;c=2;
    end
    Result =[{sprintf('G%dC%d: %d img %s',g,c,handles.Cfg.GroupDirs{x, 2},handles.Cfg.GroupDirs{x, 1})} ;Result];
end

function Result=GetInputICDisplayList(handles)
Result ={};
for x=size(handles.Cfg.CovariateDirs, 1):-1:1
    switch x
        case 1 
            g=1;c=1;
        case 2
            g=1;c=2;
        case 3
            g=2;c=1;
        case 4
            g=2;c=2;
    end
    Result =[{sprintf('C_G%dC%d : %d img %s',g,c,handles.Cfg.CovariateDirs{x, 2},handles.Cfg.CovariateDirs{x, 1})} ;Result];
end

function Result=GetInputOCDisplayList(handles)
Result ={};
for x=size(handles.Cfg.OtherTxt, 1):-1:1
    switch x
        case 1 
            g=1;c=1;
        case 2
            g=1;c=2;
        case 3
            g=2;c=1;
        case 4
            g=2;c=2;
    end
    Result =[{sprintf('TC_G%dC%d: 1 txt %s',g,c,handles.Cfg.OtherTxt{x})} ;Result];
end

function [nVolumn]=CheckDataDir(ADataDir)
theFilenames = dir(ADataDir);
theHdrFiles=dir(fullfile(ADataDir,'*.hdr'));
theImgFiles=dir(fullfile(ADataDir,'*.img'));
if ~length(theHdrFiles)==length(theImgFiles)
    nVolumn =-1;
    fprintf('%s, *.{hdr,img} should be pairwise. Please re-examin them.\n', ADataDir);
    errordlg('*.{hdr,img} should be pairwise. Please re-examin them.');
    return;
end
count = 3; nVolumn = 0;
for count = 3:size(struct2cell(theFilenames),2)
    if	(length(theFilenames(count).name)>4) && ...
            strcmpi(theFilenames(count).name(end-3:end) , '.hdr')
        if strcmpi(theFilenames(count).name(1:end-4) ...                %hdr
                , theFilenames(count+1).name(1:end-4) )     %img
            nVolumn = nVolumn + 1;
        else
            nVolumn =-1;
            fprintf('%s, *.{hdr,img} should be pairwise. Please re-examin them.\n', ADataDir);
            errordlg('*.{hdr,img} should be pairwise. Please re-examin them.');
            break;
        end
    end
end

function [nVolumn]=CheckTDataDir(ADataDir)
theFilenames = dir(ADataDir);
theTxtFiles=dir(fullfile(ADataDir,'*.txt'));
count = 3; nVolumn = 0;
for count = 3:size(struct2cell(theFilenames),2)
    if	(length(theFilenames(count).name)>4) && ...
            strcmpi(theFilenames(count).name(end-3:end) , '.txt')
        nVolumn = nVolumn + 1;
    end
end


function DeleteSelectedG(hObject, eventdata, handles)
theIndex =get(handles.list_group, 'Value');
if prod(size(handles.Cfg.GroupDirs))==0 ...
        || size(handles.Cfg.GroupDirs, 1)==0 ...
        || theIndex>size(handles.Cfg.GroupDirs, 1),
    return;
end
theDir     =handles.Cfg.GroupDirs{theIndex, 1};
theVolumnCount=handles.Cfg.GroupDirs{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.list_group, 'Value', theIndex-1);
    end
    handles.Cfg.GroupDirs(theIndex, :)=[];
    if size(handles.Cfg.GroupDirs, 1)==0
        handles.Cfg.GroupDirs={};
    end
    guidata(hObject, handles);
    UpdateDisplay(handles);
end

function DeleteSelectedIC(hObject, eventdata, handles)
theIndex =get(handles.lst_covimg, 'Value');
if prod(size(handles.Cfg.CovariateDirs))==0 ...
        || size(handles.Cfg.CovariateDirs, 1)==0 ...
        || theIndex>size(handles.Cfg.CovariateDirs, 1),
    return;
end
theDir     =handles.Cfg.CovariateDirs{theIndex, 1};
theVolumnCount=handles.Cfg.CovariateDirs{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.lst_covimg, 'Value', theIndex-1);
    end
    handles.Cfg.CovariateDirs(theIndex, :)=[];
    if size(handles.Cfg.CovariateDirs, 1)==0
        handles.Cfg.CovariateDirs={};
    end
    guidata(hObject, handles);
    UpdateDisplay(handles);
end

function DeleteSelectedOC(hObject, eventdata, handles)
theIndex =get(handles.list_addcov, 'Value');
if prod(size(handles.Cfg.OtherTxt))==0 ...
        || theIndex>size(handles.Cfg.OtherTxt, 1),
    return;
end
theDir     =handles.Cfg.OtherTxt{theIndex};
tmpMsg=sprintf('Delete\n\n "%s" \n?', theDir);
if strcmp(questdlg(tmpMsg, 'Delete confirmation'), 'Yes')
    if theIndex>1,
        set(handles.list_addcov, 'Value', theIndex-1);
    end
    handles.Cfg.OtherTxt(theIndex, :)=[];
    if size(handles.Cfg.OtherTxt)==0
        handles.Cfg.OtherTxt={};
    end
    guidata(hObject, handles);
    UpdateDisplay(handles);
end

function ClearG(hObject, eventdata, handles)
if prod(size(handles.Cfg.GroupDirs))==0 ...
        || size(handles.Cfg.GroupDirs, 1)==0,
    return;
end
tmpMsg=sprintf('Attention!\n\n\nDelete all data directories?');
if strcmpi(questdlg(tmpMsg, 'Clear confirmation'), 'Yes'),
    handles.Cfg.GroupDirs(:)=[];
    if prod(size(handles.Cfg.GroupDirs))==0,
        handles.Cfg.GroupDirs={};
    end
    guidata(hObject, handles);
    UpdateDisplay(handles);
end

function ClearIC(hObject, eventdata, handles)
if prod(size(handles.Cfg.CovariateDirs))==0 ...
        || size(handles.Cfg.CovariateDirs, 1)==0,
    return;
end
tmpMsg=sprintf('Attention!\n\n\nDelete all data directories?');
if strcmpi(questdlg(tmpMsg, 'Clear confirmation'), 'Yes'),
    handles.Cfg.CovariateDirs(:)=[];
    if prod(size(handles.Cfg.CovariateDirs))==0,
        handles.Cfg.CovariateDirs={};
    end
    guidata(hObject, handles);
    UpdateDisplay(handles);
end

function ClearOC(hObject, eventdata, handles)
if prod(size(handles.Cfg.OtherTxt))==0 ...
        || size(handles.Cfg.OtherTxt, 1)==0,
    return;
end
tmpMsg=sprintf('Attention!\n\n\nDelete all data directories?');
if strcmpi(questdlg(tmpMsg, 'Clear confirmation'), 'Yes'),
    handles.Cfg.OtherTxt(:)=[];
    if prod(size(handles.Cfg.OtherTxt))==0,
        handles.Cfg.OtherTxt={};
    end
    guidata(hObject, handles);
    UpdateDisplay(handles);
end
