function varargout = select_folder(varargin)
%SELECT_FOLDER - Application M-file for bst_SelectFolder.fig
% function varargout = select_folder(varargin)
%  Modal GUI call,halts execution until response.
%    FOLDER = SELECT_FOLDER launch select_folder GUI, modal, 
%           wait for user to respond, return selected FOLDER or return empty.
%    SELECT_FOLDER('callback_name', ...) invoke the named callback, used
%           by the uicontrols

%<autobegin> ---------------------- 26-May-2004 11:34:19 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Utility - General
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\bst_color_scheme.m
%   toolbox\bst_message_window.m
%
% Subfunctions in this file, in order of occurrence in file:
%   load_listbox(handles);
%   varargout = Select_Callback(h, eventdata, handles, varargin)
%   varargout = Quit_Callback(h, eventdata, handles, varargin)
%   varargout = FolderListbox_Callback(h, eventdata, handles, varargin)
%   varargout = popup_drive_Callback(h, eventdata, handles, varargin)
%   varargout = popup_drive_ButtonDownFcn(h, eventdata, handles, varargin)
%   varargout = SelectFolder_ResizeFcn(h, eventdata, handles, varargin)
%
% Application data and their calls in this file:
%   'Folder'
%   'PWD'
%   
%   setappdata(fig,'Folder',[]);
%   setappdata(fig,'Folder',pwd);
%   setappdata(fig,'PWD',PWD);
%   
%   Folder = getappdata(fig,'Folder');
%   PWD = getappdata(fig,'PWD');
%
% 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 select_folder.fig
%   figure::SelectFolder "" uses CreateFcn for movegui center
%   figure::SelectFolder "" uses ResizeFcn for <automatic>
%   uicontrol:listbox:FolderListbox "" uses Callback for <automatic>
%   uicontrol:popupmenu:popup_drive "A:\" uses ButtonDownFcn for <automatic>
%   uicontrol:popupmenu:popup_drive "A:\" uses Callback for <automatic>
%   uicontrol:pushbutton:Quit "Cancel" uses Callback for <automatic>
%   uicontrol:pushbutton:Select "Select" uses Callback for <automatic>
%
% At Check-in: $Author: Mosher $  $Revision: 16 $  $Date: 5/26/04 10:02a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 24-May-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> ------------------------ 26-May-2004 11:34:19 -----------------------


% /---Script Authors-------------------------------------\
% |  *** Sylvain Baillet, Ph.D.                          |
% |  Cognitive Neuroscience & Brain Imaging Laboratory   |
% |  CNRS UPR640 - LENA                                  | 
% |  Hopital de la Salpetriere, Paris, France            |
% |  sylvain.baillet@chups.jussieu.fr                    |
% |                                                      |
% |  *** John C. Mosher, Ph.D.                           |
% |  Biophysics Group                                    |
% \------------------------------------------------------/
%  
% SB Date of creation: August 2001
% SB Date of modification: April 2002
% 16-Apr-2002 SB - function output argument is now the name of the selected folder. 
% JCM 23-May-2002 renamed all occurences in the toolbox from bst_SelectFolder to
%  select_folder (want to remove Caps, and use of bst_). Edited m-file for looks.
%  changed calling structure
% JCM 24-May-2002 major alteration again to make routine return Folder, so that
%  call is simply Folder = select_folder; Added resize function to keep listbox
%  at 10 points
%  
%---------------------------------------------------------------------------------------------------------------------------

% Last Modified by GUIDE v2.0 24-May-2002 17:02:59


if nargin == 0  % LAUNCH GUI
    
   fig = openfig(mfilename,'reuse'); % only one instance

   % Generate a structure of handles to pass to callbacks, and store it. 
   handles = guihandles(fig);
   guidata(fig, handles);
   
   
   % customizations
   
   movegui(fig,'center');
   bst_color_scheme(fig);
   set(fig,'visible','on');

      
   set(handles.FolderListbox,'fontname','default'); % better than fixedwidth
   
   % where are we in the path
   PWD = pwd;
   setappdata(fig,'PWD',PWD); % store it, we'll return there if cancelled.   
   
   setappdata(fig,'Folder',[]); % initialize the output of this GUI.
   
   load_listbox(handles); % load up the GUI
   
   if(ispc),
      % PC users have the unique problem of hopping over to other drives
      set(handles.popup_drive,'visible','on');
      set(handles.text_drive,'Visible','on'); % the text label of the popup
      drive_letters = cell(26,1); % capital letters
      for i = 1:26,
         drive_letters{i} = sprintf('%c:\\',i+64);
      end
      set(handles.popup_drive,'String',drive_letters);
      current_drive = PWD(1:3); % where we are now
      Val = strmatch(upper(current_drive),drive_letters); % find in the list
      set(handles.popup_drive,'Val',Val); % set list appropriately
   else
      % other platforms move between disks from the root level
      set(handles.popup_drive,'visible','off'); % not needed, meaningless
      set(handles.text_drive,'Visible','off'); % text label
   end
   

   % JCM 24-May-2002, changed to return the Folder directly
   % The GUI is displayed, waiting for the user to interact
   
   uiwait(fig); % wait for user to close it
   if(ishandle(fig)),
      % user has selected a folder, figure still exists
      Folder = getappdata(fig,'Folder');
      close(fig);
   else
      % figure was cancelled
      Folder = []; % return empty
   end
   
   varargout{1} = Folder;
   
   
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
   
   try
      [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
   catch
      disp(lasterr);
   end
   
end




% --------------------------- LOCAL FUNCTIONS ------------------------
% -------------------- LOAD THE LISTBOX WITH FOLDERS -----------------
function load_listbox(handles);
% load the list of the pwd directories into the listbox

fig = handles.SelectFolder;
set(fig,'pointer','watch'); % large directories cause noticeable delay

d = dir;
d = d(find([d.isdir])); % Show only directories
[ignore,sorti] = sort(lower({d.name})); % sort
str1 = {d.name}; % unsorted cell array list
str1 = str1(sorti); % sorted without respect to capitalization

% update the GUI
set(handles.FolderListbox,'String',str1,'Value',1,'Listboxtop',1);
set(handles.text_pwd,'String',pwd);

set(fig,'pointer','arrow'); % large directories cause noticeable delay





% ------------------------------ CALLBACKS ---------------------------
% -------------------- USER HAS SELECTED DESIRED DIRECTORY -----------
function varargout = Select_Callback(h, eventdata, handles, varargin)

fig = handles.SelectFolder;

str1 = get(handles.FolderListbox,'String'); % all of the strings
Selection = get(handles.FolderListbox,'Value'); % which one

% we want the full folder name
cd(str1{Selection})

setappdata(fig,'Folder',pwd); % assign the directory in the calling workspace

uiresume(fig); % resume the status of this fig, if anyone is waiting for it

% at this point, the calling routine should getappdata and close this figure





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

fig = handles.SelectFolder;

PWD = getappdata(fig,'PWD'); % return to where we started
cd(PWD);

close(fig);





% ---------------------- LISTBOX CALLBACK ----------------------------
function varargout = FolderListbox_Callback(h, eventdata, handles, varargin)
% User has clicked on item in the directory list

fig = handles.SelectFolder; % handle
SelectionType = get(fig,'SelectionType'); % what kind of button click

switch lower(SelectionType)
case 'normal' % single click, do nothing
   % user is just clicking around, may be ready to hit Select button
otherwise % other kind of click
   % user wants to move to into that directory
   set(fig,'pointer','watch'); % large directories cause noticeable delay
   str1 = get(handles.FolderListbox,'String'); % all of the strings
   Selection = get(handles.FolderListbox,'Value'); % which one

   if(~strcmp(str1{Selection},'.')), % if not the present directory
      % no need to cd to the present directory, only if it is different
      %  (saves time on long loads)
      cd(str1{Selection});
      load_listbox(handles); % load up the listbox with the new data
   end
   
   set(fig,'pointer','arrow');
end




% ------------------ CHANGE THE DRIVE LETTER --------------------------
function varargout = popup_drive_Callback(h, eventdata, handles, varargin)

% if this is a pc, then this popup is visible, to allow the user to switch
%  between disk drives. Only PC people have this problem.

drive_letters = get(h,'String'); % the drive letters
Val = get(h,'Val'); % the letter selected

try
   cd(drive_letters{Val});
   % it worked, load it up
   load_listbox(handles);
catch
   % invalid drive
   PWD = pwd;
   current_drive = PWD(1:3); % where we are now
   oldval = strmatch(upper(current_drive),drive_letters);
   set(h,'Val',oldval);
end




% --------------------------- HELP FOR CHANGE DRIVE BUTTON ------------------
function varargout = popup_drive_ButtonDownFcn(h, eventdata, handles, varargin)

par1 = ['Select new drive letter from the list. If an error occurs in changing to ',...
      'the new drive (e.g. invalid drive letter), returns to the existing drive ',...
      'letter.'];
bst_message_window('wrap',{'','HELP FOR DRIVE POPUP','',par1});




% --------------------------------------------------------------------
function varargout = SelectFolder_ResizeFcn(h, eventdata, handles, varargin)
% after the user has resized, set the listbox font back to 10 point

handles = guihandles(h); % just in case

Fixed(1).h = handles.FolderListbox;
Fixed(1).pts = 10;

Fixed(end+1).h = handles.text_pwd;
Fixed(end).pts = 10;

if(0), % these look better left to auto scale
   Fixed(end+1).h = handles.TitleText;
   Fixed(end).pts = 12;
   
   Fixed(end+1).h = handles.Quit;
   Fixed(end).pts = 10;
   
   Fixed(end+1).h = handles.Select;
   Fixed(end).pts = 10;
end

for i = 1:length(Fixed)
   
   set(Fixed(i).h,'fontunits','points')
   set(Fixed(i).h,'fontsize',Fixed(i).pts);
   set(Fixed(i).h,'fontunits','points');
   
end



