function varargout = file_selection_win(varargin)
%FILE_SELECTION_WIN - Application M-file for file_selection_win.fig
% function varargout = file_selection_win(varargin)
%    FIG = FILE_SELECTION_WIN launch file_selection_win GUI.
%    FILE_SELECTION_WIN('callback_name', ...) invoke the named callback.
% This tool (window) returns files from a specified directory
% Useful to locate generic files with a known tag (like tess, channel, subject etc)
%
% It can only find files defined in find_brainstorm_files function
%
% It allows multiple selection of files
%
%
% Example:
%     filetype{1} = 'tess';
%     filetype{2} = 'channel';
%     loaddirectory = 'c:\brainstorm\subject';
%     [Files Filenames] = file_selection_win(filetype,loaddirectory);
% returns the full path of the file and the filename within structures

%<autobegin> ---------------------- 09-Jul-2004 22:17:04 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: GUI and Related
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\bst_color_scheme.m
%   toolbox\bst_layout.m
%   toolbox\find_brainstorm_files.m
%   toolbox\makeuswait.m
%
% Subfunctions in this file, in order of occurrence in file:
%   varargout = initialize_gui(h,eventdata,handles,varargin);
%   varargout = listbox1_Callback(h, eventdata, handles, varargin)
%   varargout = HDone_Callback(h, eventdata, handles, varargin)
%   varargout = Quit_Callback(h, eventdata, handles, varargin)
%
% Application data and their calls in this file:
%   'TileType'
%   'data'
%   
%   setappdata(fig,'TileType','T')
%   setappdata(fig,'data',data);
%   
%   data = getappdata(fig,'data');
%   data = getappdata(gcbf,'data');
%
% Figure Files opened by this function:
%   mfilename
%
%   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
%   <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure file_selection_win.fig
%   uicontrol:listbox:listbox1 "Hold On Please..." uses Callback for <automatic>
%   uicontrol:pushbutton:HDone "Done" uses Callback for <automatic>
%   uicontrol:pushbutton:Quit "Quit" uses Callback for <automatic>
%
% At Check-in: $Author: Mosher $  $Revision: 12 $  $Date: 7/09/04 8:42p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 09-Jul-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 09-Jul-2004 22:17:04 -----------------------


% Last Modified by GUIDE v2.5 09-Jul-2004 14:07:33

% /---Script Author--------------------------------------\
% |                                                      |
% | *** Dimitrios Pantazis, Ph.D. student                |
% | University of Southern California                    |
% |                                                      | 
% \------------------------------------------------------/
%  
% Date of creation: May 2004

% ----------------------------- Script History ---------------------------------
% 14-May-2004 DP  Creation
% 16-May-2004 JCM Commenting
% 17-May-2004 DP  More edits
% 18-May-2004 DP  Small fixes to make sure it always returns a structure, even
%                 an empty one.
% 25-May-2004 SB  Adding possibility to travel across folders by clicking on a folder name
% ----------------------------- Script History ---------------------------------


% All communication between functions is hdone using the 'data' structure 



if nargin == 2  % LAUNCH GUI

	fig = openfig(mfilename,'reuse');

    bst_color_scheme(fig);
    setappdata(fig,'TileType','T')
    bst_layout('align',fig,2,2,3)
    set(fig,'visible','on'); % .fig saved as invisible until ready
        
	% Generate a structure of handles to pass to callbacks, and store it. 
	handles = guihandles(fig);
	guidata(fig, handles);
    
    %the current subject folder is the second argument
    data.Filetypes = varargin{1};
    data.CurrentSubjectFolder = varargin{2};
    
    %save application data
    setappdata(fig,'data',data);

    %initialize
    initialize_gui(fig,[],handles,varargin{:});
    
  	% Wait for callbacks to run and window to be dismissed:
	uiwait(fig);

    if(~ishandle(fig)) %if figure is closed already
        varargout{1} = {[]};
        varargout{2} = {[]};
        return
    end
        
    data = getappdata(fig,'data');
    varargout{1} = data.outputFiles;
    varargout{2} = data.outputFilenames;
    close(fig);
    
    
    
    
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

	try
		if (nargout)
			[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
		else
			feval(varargin{:}); % FEVAL switchyard
		end
	catch
		disp(lasterr);
	end

end




% ------------------- Local Functions --------------------------
% ---------------------------------------------------------------
function varargout = initialize_gui(h,eventdata,handles,varargin);
% This function initializes GUI controls, as well as two structures, 'data' and 'changed'

makeuswait('start')
fig = handles.file_selection_win; % make sure we have the handle
handles = guidata(fig);
data = getappdata(fig,'data');

%check for files
Filenames = []; %initialize
Files = [];
for i = 1:size(data.Filetypes,2)
    [Filenames_i,ignore,Leader] = find_brainstorm_files(data.Filetypes{i},data.CurrentSubjectFolder);
    if (isempty(Filenames_i)) %if no files of this type
        continue
    end
    Filenames = [Filenames Filenames_i];
    clear Files_i;
    for j = 1:size(Filenames_i,2)
        Files_i{j} = fullfile(Leader,Filenames_i{j});
    end
    Files = [Files Files_i];
end    
    
if ~isempty(Filenames)
    set(handles.listbox1,'String',Filenames,'Max',length(Filenames),'Userdata',Leader)
else
    ErrorString = sprintf('No files were found in %s',data.CurrentSubjectFolder);
    set(handles.listbox1,'String',ErrorString)
    makeuswait('stop')
    return
end

data.Files = Files;
data.Filenames = Filenames;
setappdata(fig,'data',data);


makeuswait('stop')


% --------------------------------------------------------------------
function varargout = listbox1_Callback(h, eventdata, handles, varargin)
% Check whether use wants to change directory

data = getappdata(gcbf,'data');% Fetch original requested file types
try % to change of directory
    cd(data.Files{get(handles.listbox1,'Value')})
    % Then refresh file list
    tmp{1} = data.Filetypes;
    tmp{2} = pwd;
    initialize_gui(gcbf,[],handles,tmp{:});
catch
    % Do nothing
end
    



% --------------------------------------------------------------------
function varargout = HDone_Callback(h, eventdata, handles, varargin)

fig = handles.file_selection_win; % make sure we have the handle
handles = guidata(fig);
data = getappdata(fig,'data');

%if no files are present
if(~isfield(data,'Files'))
    data.outputFiles{1} = [];
    data.outputFilenames{1} = [];
    setappdata(fig,'data',data);
    uiresume;
    return
end


%selected files
fileNdx = get(handles.listbox1,'Value');

for i = 1:size(fileNdx,2)
    data.outputFiles{i} = data.Files{fileNdx(i)};
    data.outputFilenames{i} = data.Filenames{fileNdx(i)};
end


setappdata(fig,'data',data);

uiresume;


% --------------------------------------------------------------------
function varargout = Quit_Callback(h, eventdata, handles, varargin)

fig = handles.file_selection_win; % make sure we have the handle
handles = guidata(fig);
data = getappdata(fig,'data');

data.outputFiles{1} = [];
data.outputFilenames{1} = [];
setappdata(fig,'data',data);

uiresume;
