function [varargout]=nic_rsdd_inputData(varargin)
%  GUI for selecting files 
%-----------------------------------------------------------
%   Copyright (C) 2009 Neuroimage Computing Group, State Key Laboratory of
%   Cognitive Neuroscience and Learning
%	Written by Gwen Chen
%	Version=1.0;
%	Release=2009715;
%  Last Revised by Gwen Chen
%-----------------------------------------------------------
%

AOption='';
if(nargin<1)
    option='init';
else
    option=varargin{1};
end
global handles;
if(~isfield(handles,'listDirs'))
    handles.listDirs=cell(0,0);
end
switch upper(option),
    case 'INIT',
%         disp(sprintf('Welcome!'));
        handles=initControls();
        handles.prefix='';
        handles.listDirs=cell(0,0);
        uiwait(handles.ui.figMain);
         if(~isfield(handles,'listDirs1'))
            handles.listDirs1=cell(0,0);
        end
        listDirs=[handles.listDirs;handles.listDirs1];
        listLabels=[ones(size(handles.listDirs,1),1);ones(size(handles.listDirs1,1),1)*(2)];
        clear global handles;
        varargout{1}=listDirs;
        varargout{2}=listLabels;
      case 'INITDATA',
        handles=initControls();  
        set(handles.ui.groupSetting, 'Visible','off');
        subjectList=varargin{2};
        subjectLabel=varargin{3};
        sv=length(unique(subjectLabel));
        switch(sv)
            case 1
                 set(handles.ui.groupSetting, 'Visible','off');        
                 handles=initMainControlsOneGroup(handles);
                 handles.listDirs=subjectList;
                 SetListData(handles,handles.ui.listbox1);
            case 2
                 set(handles.ui.groupSetting, 'Visible','off');        
                 handles=initMainControls(handles);
                 handles.listDirs=subjectList(find(subjectLabel==1),:);
                 handles.listDirs1=subjectList(find(subjectLabel==2),:);
                 SetListData(handles,handles.ui.listbox1);
                 SetListData(handles,handles.ui.listbox2);
            otherwise
        end
       
        handles.prefix='';
        uiwait(handles.ui.figMain);
        if(~isfield(handles,'listDirs1'))
            handles.listDirs1=cell(0,0);
        end
        listDirs=[handles.listDirs;handles.listDirs1];
        listLabels=[ones(size(handles.listDirs,1),1);ones(size(handles.listDirs1,1),1)*(2)];
%         clear global handles;
        varargout{1}=listDirs;
        varargout{2}=listLabels;
        
    case 'CHANGEGROUP', %select the group
        sv=get(handles.ui.groupSetting, 'Value');       
        switch(sv)
            case 1
            case 2
                 set(handles.ui.groupSetting, 'Visible','off');        
                 handles=initMainControlsOneGroup(handles);
                 handles.listDirs=cell(0,0);
            case 3
                 set(handles.ui.groupSetting, 'Visible','off');        
                 handles=initMainControls(handles);
                 handles.listDirs1=cell(0,0);
            otherwise
        end
    case 'EDITPREFIX',%edit prefix
        handles.prefix=get(handles.ui.prefix,'String');
    case 'ADDADIRECTORY'%AddADirectory
         theDir =pwd;
        if(strcmpi(varargin{2},'listbox1'))
            if size(handles.listDirs, 1)>0
                 theDir =handles.listDirs{1,1};
            end
        else
             if size(handles.listDirs1, 1)>0
                 theDir =handles.listDirs1{1,1};
             elseif size(handles.listDirs, 1)>0
                 theDir =handles.listDirs{1,1};
             end  
        end
        theDir =uigetdir(theDir, 'Please select the data directory that contains the files: ');
        if ischar(theDir),
            if(strcmpi(varargin{2},'listbox1'))
                handles=SetDataDir(theDir,handles,handles.ui.listbox1);
            else
                handles=SetDataDir(theDir,handles,handles.ui.listbox2);
            end
        end
    case 'DELETESELECTEDDATADIR'%DeleteSelectedDataDir'
        if(strcmpi(varargin{2},'listbox1'))
               handles=DeleteSelectedDataDir(handles,handles.ui.listbox1);
        else
               handles=DeleteSelectedDataDir(handles,handles.ui.listbox2);
        end
    case 'KEYPRESS'%keypress
        if(strcmpi(varargin{2},'listbox1'))
               listbox1_KeyPressFcn(handles,handles.ui.listbox1);
        else
               listbox2_KeyPressFcn(handles,handles.ui.listbox2);
        end
    case 'RECURSIVEADDDATADIR'%RecursiveAddDataDir
         if(strcmpi(varargin{2},'listbox1'))
               handles=RecursiveAddDataDir(handles,handles.ui.listbox1);
        else
               handles=RecursiveAddDataDir(handles,handles.ui.listbox2);
        end
    case 'CLEARDATADIRECTORIES'%ClearDataDirectories
        if(strcmpi(varargin{2},'listbox1'))
               handles=ClearDataDirectories(handles,handles.ui.listbox1);
        else
               handles=ClearDataDirectories(handles,handles.ui.listbox2);
        end
     case 'SUBMIT',
       
       
        uiresume(handles.ui.figMain);
        delete(gcbf);
        
    case 'QUITALL',
%         disp(sprintf('Thank you!'));
        uiresume(handles.ui.figMain);
        varargout{1}='dd';
        delete(gcbf);
%         clear global handles;
    otherwise

end

return;


function SetListData(handles,object)
    listDirs={};
   if(object==handles.ui.listbox1)
        listDirs=handles.listDirs;
    elseif(object==handles.ui.listbox2)
        listDirs=handles.listDirs1;
    end
      displayString={};
      dirSize=size(listDirs,1);
      for i=1:dirSize
          displayString=[displayString;sprintf('[1:%d] %s',listDirs{i,2},listDirs{i,1})];
      end
            
      set(object,'String',displayString);
      set(object,'Value',dirSize);   
    if(object==handles.ui.listbox1)
        if(dirSize>1)
           set(handles.ui.sujectNum,'String',sprintf('%d subjects were selected',dirSize));
        else
            set(handles.ui.sujectNum,'String',sprintf('%d subject was selected',dirSize));
        end
    elseif(object==handles.ui.listbox2)
         if(dirSize>1)
           set(handles.ui.sujectNum1,'String',sprintf('%d subjects were selected',dirSize));
        else
            set(handles.ui.sujectNum1,'String',sprintf('%d subject was selected',dirSize));
        end
    end
return;

function handles=SetDataDir(ADir,handles,object,opt)
if ~ischar(ADir), return; end	

if(~exist('opt','var'))
    opt='0';
end
if(object==handles.ui.listbox1)
    listDirs=handles.listDirs;
elseif(object==handles.ui.listbox2)
    listDirs=handles.listDirs1;
end
dirSize=0;
if (~isequal(ADir , 0)) &&( (size(listDirs, 1)==0)||(0==length(strmatch(ADir,listDirs( : , 1),'exact' ) ) ))   
		 [theVolumnCount file] =CheckDataDir(ADir,handles.prefix );	
		if (theVolumnCount<=0 ),			
                if(length(opt)>0)
    				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
                return;
        else
            listDirs =[ listDirs;{ADir , 0,struct()}];%update the dir  
			listDirs{end,2} =theVolumnCount;

            listDirs{end,3} =file;
            
            displayString={};
            dirSize=size(listDirs,1);
            for i=1:dirSize
                displayString=[displayString;{sprintf('[1:%d] %s',listDirs{i,2},listDirs{i,1})}];
            end
            
            set(object,'String',displayString);
            set(object,'Value',dirSize);            
        end        
end
dirSize=size(listDirs,1);
if(object==handles.ui.listbox1)
    handles.listDirs= listDirs;
    if(dirSize>1)
       set(handles.ui.sujectNum,'String',sprintf('%d subjects were selected',dirSize));
    else
        set(handles.ui.sujectNum,'String',sprintf('%d subject was selected',dirSize));
    end
elseif(object==handles.ui.listbox2)
    handles.listDirs1= listDirs;
     if(dirSize>1)
       set(handles.ui.sujectNum1,'String',sprintf('%d subjects were selected',dirSize));
    else
        set(handles.ui.sujectNum1,'String',sprintf('%d subject was selected',dirSize));
    end
end
return;
% check the dir, get the size of image in the dir
function [volumnCount file]=CheckDataDir(ADataDir,prefix)
    if(strcmp(prefix,'*')==1)
        prefix='';
    end
    theFilenames = dir(fullfile(ADataDir,[prefix,'*']));
	theHdrFiles=dir(fullfile(ADataDir,[prefix,'*.hdr']));
	theImgFiles=dir(fullfile(ADataDir,[prefix,'*.img']));
    file=struct();
    
	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		
    isNiiFormat=0;
    if(length(theHdrFiles)==0)
        theImgFiles=dir(fullfile(ADataDir,[prefix,'*.nii']));
        isNiiFormat=1;
    end
    
    if(~isNiiFormat)
        if(length(prefix)>0)
            scount=1;
        else
            scount=3;
        end
        nVolumn = 0;		
        for count = scount: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
        volumnCount=nVolumn;
    else
        volumnCount=length(theImgFiles);
    end
    name=[];
    for i=1:volumnCount
         name=[name;fullfile(ADataDir,theImgFiles(i).name)];
    end
    file.name=name;
  

% delete a dir from the list
function  handles=DeleteSelectedDataDir(handles,object)
    listDirs={};
    if(object==handles.ui.listbox1)
        listDirs=handles.listDirs;
    elseif(object==handles.ui.listbox2)
        listDirs=handles.listDirs1;
    end
    theIndex =get(object, 'Value');
	if prod(size(listDirs))==0 ...
		|| size(listDirs, 1)==0 ...
		|| theIndex>size(listDirs, 1),
		return;
	end
	theDir     =listDirs{theIndex, 1};
	theVolumnCount= listDirs{theIndex, 2};
	tmpMsg=sprintf('Delete\n\n "%s" \nVolumn Count :%d ?', theDir, theVolumnCount);
	if strcmp(questdlg(tmpMsg, 'Delete confirmation'), 'Yes')
		if theIndex>1,
			set(object, 'Value', theIndex-1);
		end
		listDirs(theIndex, :)=[];
		if size(listDirs, 1)==0
			listDirs={};
        end	
        displayString={};
        dirSize=size(listDirs,1);
        for i=1:dirSize
            displayString=[displayString;sprintf('[1:%d] %s',listDirs{i,2},listDirs{i,1})];
        end
        set(object,'String',displayString);
        set(object,'Value',dirSize);
    end
    dirSize=size(listDirs,1);
    if(object==handles.ui.listbox1)
        handles.listDirs= listDirs;
        if(dirSize>1)
           set(handles.ui.sujectNum,'String',sprintf('%d subjects were selected',dirSize));
        else
            set(handles.ui.sujectNum,'String',sprintf('%d subject was selected',dirSize));
        end
    elseif(object==handles.ui.listbox2)
        handles.listDirs1= listDirs;
         if(dirSize>1)
           set(handles.ui.sujectNum1,'String',sprintf('%d subjects were selected',dirSize));
        else
            set(handles.ui.sujectNum1,'String',sprintf('%d subject was selected',dirSize));
        end
    end  
 return;
 
 function handles=RecursiveAddDataDir(handles,object)
    listDirs={};
    theDir=pwd;
    if(object==handles.ui.listbox1)
        listDirs=handles.listDirs;
         if size(listDirs, 1)>0
          theDir =listDirs{1,1};
       end
    elseif(object==handles.ui.listbox2)
        listDirs=handles.listDirs1;
        if size(listDirs, 1)>0
          theDir =listDirs{1,1};
       elseif size(listDirs, 1)>0
           theDir =listDirs{1,1};
       end  
    end
	theDir =uigetdir(theDir, 'Please select the parent data directory of many sub-folders containing EPI data for ICA: ');
	if ischar(theDir),
		setappdata(0, 'ICA_DoingRecursiveDir', 1);
		theOldColor =get(object, 'BackgroundColor');
		set(object, 'BackgroundColor', [ 0.7373    0.9804    0.4784]);
		try
			handles=RecursiveDir(theDir,handles,object);
		catch
			nic_rsdd_misc('Exception');
		end	
		set(object, 'BackgroundColor', theOldColor);
		rmappdata(0, 'ICA_DoingRecursiveDir');
	end	
 return;
 
function Result=RecursiveDir(ADataDir,handles,object)
    handles=SetDataDir(ADataDir,handles,object,[]);
	pause(0.05);
	
	theFileList = dir(ADataDir);	
	ImgDirList ={};
	for x = 1:size(struct2cell(theFileList),2),
	    if theFileList(x).isdir && (~ strcmpi(theFileList(x).name,'.')) && (~ strcmpi(theFileList(x).name,'..')),
			ImgDirList=[ImgDirList; {theFileList(x).name}];            
	    end
	end	
	Result =handles;
	
	for x = 1:size(ImgDirList,1),
        handles=SetDataDir(fullfile(ADataDir,ImgDirList{x}),handles,object,[]);   
		handles=RecursiveDir(fullfile(ADataDir,ImgDirList{x}), handles,object);
    end	
    Result =handles;
return;


 % delete all dirs from the list
function  handles=ClearDataDirectories(handles,object)
    listDirs={};
    if(object==handles.ui.listbox1)
        listDirs=handles.listDirs;
    elseif(object==handles.ui.listbox2)
        listDirs=handles.listDirs1;
    end
   if prod(size(listDirs))==0 ...
		|| size(listDirs, 1)==0,		
		return;
	end
	tmpMsg=sprintf('Attention!\n\n\nDelete all data directories?');
	if strcmpi(questdlg(tmpMsg, 'Clear confirmation'), 'Yes'),		
		listDirs(:)=[];
		if prod(size(listDirs))==0,
			listDirs={};
        end	
        set(object,'String',{});
	end	
     dirSize=size(listDirs,1);
    if(object==handles.ui.listbox1)
        handles.listDirs= listDirs;
        if(dirSize>1)
           set(handles.ui.sujectNum,'String',sprintf('%d subjects were selected',dirSize));
        else
            set(handles.ui.sujectNum,'String',sprintf('%d subject was selected',dirSize));
        end
    elseif(object==handles.ui.listbox2)
        handles.listDirs1= listDirs;
         if(dirSize>1)
           set(handles.ui.sujectNum1,'String',sprintf('%d subjects were selected',dirSize));
        else
            set(handles.ui.sujectNum1,'String',sprintf('%d subject was selected',dirSize));
        end
    end    
 return;
 
function Result=initControls()

DefaultColorBackground =[1 1 1]*.8;

theFig =figure('Units', 'pixel', 'Toolbar', 'none', 'MenuBar', 'none', ...
					'NumberTitle', 'off', 'Visible', 'off', ... 
					'Name', 'Please select the group size', ...
					'Position', [0,0,500, 500], 'Resize','off', ...
					'Color', DefaultColorBackground , ...
					'DeleteFcn', sprintf('nic_rsdd_inputData(''QuitAll'');')  );
movegui(theFig, 'center'); 
Result.ui.figMain=theFig;
Result.ui.groupSetting=uicontrol(theFig,'Style','popupmenu', 'Position',[90 430 300 45],...
		'String',{'Please select the number of group';'There is one group';'There are two groups'},'ToolTipString','', ...
		'Callback', sprintf('nic_rsdd_inputData(''ChangeGroup'');'), ...
		'FontSize',12, 'FontWeight','normal') ;

set(theFig, 'Visible', 'on');

return;

function Result=initMainControls(handles)
Result=handles;
theFig=handles.ui.figMain;
set(theFig,'Name','Select the files');            
movegui(theFig, 'center');
uicontrol(theFig,'Style','text', 'Position',[20 460 300 25],...
		'String','Please input the prefix of FileName to filter files:','ToolTipString','', ...
		'FontSize',12, 'FontWeight','normal') ;
handles.ui.prefix=uicontrol(theFig,'Style','edit', 'Position',[330 460 50 25],...
		'String','','ToolTipString','', ...
        'Callback',sprintf('nic_rsdd_inputData(''EditPrefix'');'),...
		'FontSize',12, 'FontWeight','normal') ;
    
uicontrol(theFig,'Style','text', 'Position',[50 420 100 25],...
		'String','Group 1','ToolTipString','', ...
		'FontSize',10, 'FontWeight','bold') ;
uicontrol(theFig,'Style','text', 'Position',[320 420 100 25],...
		'String','Group 2','ToolTipString','', ...
		'FontSize',10, 'FontWeight','bold') ;
handles.ui.listbox1=uicontrol(theFig,'Style','listbox', 'Position',[20 130 200 280],...
		'String','','ToolTipString','', ...
		'FontSize',8, 'FontWeight','normal','KeyPressFcn',  'nic_rsdd_inputData(''keyPress'',''listbox1'')') ;
handles.ui.listbox2=uicontrol(theFig,'Style','listbox', 'Position',[270 130 200 280],...
		'String','','ToolTipString','', ...
		'FontSize',8, 'FontWeight','normal','KeyPressFcn',  'nic_rsdd_inputData(''keyPress'',''listbox2'')') ;
    
handles.ui.hContextMenu =uicontextmenu;
set(handles.ui.listbox1, 'UIContextMenu', handles.ui.hContextMenu);	
uimenu(handles.ui.hContextMenu, 'Label', 'Add a directory', 'Callback', 'nic_rsdd_inputData(''AddADirectory'',''listbox1'')');	
uimenu(handles.ui.hContextMenu, 'Label', 'Add recursively all sub-folders of a directory', 'Callback', 'nic_rsdd_inputData(''RecursiveAddDataDir'',''listbox1'')');
uimenu(handles.ui.hContextMenu, 'Label', '----------------------------');	
uimenu(handles.ui.hContextMenu, 'Label', 'Remove selected directory', 'Callback', 'nic_rsdd_inputData(''DeleteSelectedDataDir'',''listbox1'')');
uimenu(handles.ui.hContextMenu, 'Label', 'Clear all data directories', 'Callback', 'nic_rsdd_inputData(''ClearDataDirectories'',''listbox1'')');

handles.ui.hContextMenu1 =uicontextmenu;
set(handles.ui.listbox2, 'UIContextMenu', handles.ui.hContextMenu1);	
uimenu(handles.ui.hContextMenu1, 'Label', 'Add a directory', 'Callback', 'nic_rsdd_inputData(''AddADirectory'',''listbox2'')');	
uimenu(handles.ui.hContextMenu1, 'Label', 'Add recursively all sub-folders of a directory', 'Callback', 'nic_rsdd_inputData(''RecursiveAddDataDir'',''listbox2'')');
uimenu(handles.ui.hContextMenu1, 'Label', '----------------------------');	
uimenu(handles.ui.hContextMenu1, 'Label', 'Remove selected directory', 'Callback', 'nic_rsdd_inputData(''DeleteSelectedDataDir'',''listbox2'')');
uimenu(handles.ui.hContextMenu1, 'Label', 'Clear all data directories', 'Callback', 'nic_rsdd_inputData(''ClearDataDirectories'',''listbox2'')');


handles.ui.sujectNum=uicontrol(theFig,'Style','text', 'Position',[30 95 180 20],...
		'String','0 subject was selected','ToolTipString','', ...
		'FontSize',12, 'FontWeight','normal');
    
handles.ui.sujectNum1=uicontrol(theFig,'Style','text', 'Position',[300 95 180 20],...
		'String','0 subject was selected','ToolTipString','', ...
		'FontSize',12, 'FontWeight','normal');
    
uicontrol(theFig,'Style','pushbutton', 'Position',[230 40 60 30],...
		'String','OK','ToolTipString','OK', ...
		'Callback', sprintf('nic_rsdd_inputData(''submit'');'), ...
		'FontSize',14, 'FontWeight','normal', 'ForegroundColor','k') ;
    
Result=handles;
	
return;


function listbox1_KeyPressFcn( handles,hObject)
	%Delete the selected item when 'Del' is pressed
    key =get(handles.ui.figMain, 'currentkey');
    if seqmatch({key},{'delete', 'backspace'})
        DeleteSelectedDataDir(handles,hObject);
    end   

function listbox2_KeyPressFcn(handles,hObject)
	%Delete the selected item when 'Del' is pressed
    key =get(handles.ui.figMain, 'currentkey');
    if seqmatch({key},{'delete', 'backspace'})
        DeleteSelectedDataDir(handles,hObject);
    end   
    

function Result=initMainControlsOneGroup(handles)
theFig=handles.ui.figMain;
set(theFig,'Name','Select the files');            
% movegui(theFig, 'center');
uicontrol(theFig,'Style','text', 'Position',[20 460 300 25],...
		'String','Please input the prefix of FileName to filter files:','ToolTipString','', ...
		'FontSize',12, 'FontWeight','normal') ;
handles.ui.prefix=uicontrol(theFig,'Style','edit', 'Position',[330 460 50 25],...
		'String','','ToolTipString','', ...
       'Callback',sprintf('nic_rsdd_inputData(''EditPrefix'');'),...
		'FontSize',12, 'FontWeight','normal') ;
    
uicontrol(theFig,'Style','text', 'Position',[100 420 300 25],...
		'String','select files','ToolTipString','', ...
		'FontSize',10, 'FontWeight','bold') ;
handles.ui.listbox1=uicontrol(theFig,'Style','listbox', 'Position',[100 130 300 280],...
		'String','','ToolTipString','', ...
		'FontSize',8, 'FontWeight','normal','KeyPressFcn',  'nic_rsdd_inputData(''keyPress'',''listbox1'')') ;
handles.ui.hContextMenu =uicontextmenu;
set(handles.ui.listbox1, 'UIContextMenu', handles.ui.hContextMenu);	
uimenu(handles.ui.hContextMenu, 'Label', 'Add a directory', 'Callback', 'nic_rsdd_inputData(''AddADirectory'',''listbox1'',''listbox1'')');	
uimenu(handles.ui.hContextMenu, 'Label', 'Add recursively all sub-folders of a directory', 'Callback', 'nic_rsdd_inputData(''RecursiveAddDataDir'',''listbox1'')');
uimenu(handles.ui.hContextMenu, 'Label', '------------------');	
uimenu(handles.ui.hContextMenu, 'Label', 'Remove selected directory', 'Callback', 'nic_rsdd_inputData(''DeleteSelectedDataDir'',''listbox1'')');
uimenu(handles.ui.hContextMenu, 'Label', 'Clear all data directories', 'Callback', 'nic_rsdd_inputData(''ClearDataDirectories'',''listbox1'')');

handles.ui.sujectNum=uicontrol(theFig,'Style','text', 'Position',[150 100 200 25],...
		'String','0 subject was selected','ToolTipString','', ...
		'FontSize',12, 'FontWeight','normal');
    
uicontrol(theFig,'Style','pushbutton', 'Position',[230 40 60 30],...
		'String','OK','ToolTipString','OK', ...
		'Callback', sprintf('nic_rsdd_inputData(''submit'');'), ...
		'FontSize',14, 'FontWeight','normal', 'ForegroundColor','k') ;
    
Result=handles;
	
return;



