function varargout = molecule_name_dlg(varargin)
% MOLECULE_NAME_DLG Application M-file for molecule_name_dlg.fig

% Last Modified by GUIDE v2.0 15-Sep-2002 19:37:51

if nargout == 3
   % LAUNCH GUI

        MoleculeName = varargin{1};
	LocalCurrentDirectory = varargin{2};
   
	fig = openfig(mfilename, 'reuse');

	set(fig, 'Color', get(0, 'defaultUicontrolBackgroundColor'));
    
    set(fig, 'HandleVisibility', 'off')

	if strcmp(varargin{4},'Open')
	  set(fig, 'Name', ['H', char(252), 'ckel Lab: Open'])
	elseif strcmp(varargin{4},'Save')
	  set(fig, 'Name', ['H', char(252), 'ckel Lab: Save As'])
	end
	  
	% Generate a structure of handles to pass to callbacks, and store it. 
	handles = guihandles(fig);
	handles.MoleculeName = MoleculeName;
	handles.LocalCurrentDirectory = LocalCurrentDirectory;
	handles.cancel = 'no';
	guidata(fig, handles);

	dlg_pos_size = get(fig, 'Position');
	% dlg_pos_size = [left_dlg, bottom_dlg, width_dlg, height_dlg]
        new_dlg_pos = varargin{3};
	% new_dlg_pos = [new_left_dlg, new_bottom_dlg]
	new_dlg_pos_size = [new_dlg_pos(1) new_dlg_pos(2) ...
		dlg_pos_size(3) dlg_pos_size(4)];
	% Change the position but not the size.
	set(fig, 'Position', new_dlg_pos_size)
	
	set(handles.pushbuttonOpenSave, 'String', varargin{4})

	set(handles.editMoleculeName, 'String', '')

	if strcmp(varargin{4},'Open')
	  set(handles.text7, 'String', 'Look in:')
	  set(handles.text3, 'String', 'Open:')
	elseif strcmp(varargin{4},'Save')
	  set(handles.text7, 'String', 'Save in:')
	  set(handles.text3, 'String', 'Save As:')
	end
	
	set(handles.text8, 'String', LocalCurrentDirectory)
	
	% Populate the listboxes:
	load_listboxes(LocalCurrentDirectory, handles)
	
	set(fig, 'Visible', 'on')
	% The GUI is saved with the property 'Visible' set to 'off'
	
	% Make the GUI Figure Modal:
	set(fig, 'WindowStyle', 'modal')
	
	% Wait for callbacks to run and window to be dismissed:
	uiwait(fig);
	
	if ~ishandle(fig)   % Window has been manually deleted.
	  varargout{1} = varargin{1};
	  varargout{2} = varargin{2};
	  varargout{3} = 1;   % "Cancel"
	else
	  handles = guidata(fig);
	  if strcmp(handles.cancel, 'yes')   % Cancel button has been pressed.
	    varargout{1} = varargin{1};
	    varargout{2} = varargin{2};
	    varargout{3} = 1;   % "Cancel"
          else
	    varargout{1} = handles.MoleculeName;
	    varargout{2} = handles.LocalCurrentDirectory;
	    varargout{3} = 0;
	  end
	  delete(fig);   % Delete figure.
	end
	
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


%| ABOUT CALLBACKS:
%| GUIDE automatically appends subfunction prototypes to this file, and 
%| sets objects' callback properties to call them through the FEVAL 
%| switchyard above. This comment describes that mechanism.
%|
%| Each callback subfunction declaration has the following form:
%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)
%|
%| The subfunction name is composed using the object's Tag and the 
%| callback type separated by '_', e.g. 'slider2_Callback',
%| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.
%|
%| H is the callback object's handle (obtained using GCBO).
%|
%| EVENTDATA is empty, but reserved for future use.
%|
%| HANDLES is a structure containing handles of components in GUI using
%| tags as fieldnames, e.g. handles.figure1, handles.slider2. This
%| structure is created at GUI startup using GUIHANDLES and stored in
%| the figure's application data using GUIDATA. A copy of the structure
%| is passed to each callback.  You can store additional information in
%| this structure at GUI startup, and you can change the structure
%| during callbacks.  Call guidata(h, handles) after changing your
%| copy to replace the stored original so that subsequent callbacks see
%| the updates. Type "help guihandles" and "help guidata" for more
%| information.
%|
%| VARARGIN contains any extra arguments you have passed to the
%| callback. Specify the extra arguments by editing the callback
%| property in the inspector. By default, GUIDE sets the property to:
%| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))
%| Add any extra arguments after the last argument, before the final
%| closing parenthesis.



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

if strcmp(get(handles.figure1, 'SelectionType'), 'open') % Double click.
  index_selected = get(handles.listboxDirectories, 'Value');
  new_directory = handles.directory_names{index_selected};
  current_directory = pwd;
  cd (handles.LocalCurrentDirectory)
  cd (new_directory)
  handles.LocalCurrentDirectory = pwd;
  cd (current_directory)
  guidata(handles.figure1, handles)   % Save the handles structure.
  % Populate the listboxes:
  load_listboxes(handles.LocalCurrentDirectory, handles)
end



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

set(handles.listboxFiles, 'Max', 1, 'Min', 0)
% Disable multiple selection.

index_selected = get(handles.listboxFiles, 'Value');

handles.MoleculeName = handles.hcl_names{index_selected};

guidata(handles.figure1, handles)   % Save the handles structure.

if strcmp(get(handles.figure1, 'SelectionType'), 'normal') % Single click.
  set(handles.editMoleculeName, 'String', handles.MoleculeName)
elseif strcmp(get(handles.figure1, 'SelectionType'), 'open') % Double click.
  uiresume(handles.figure1);
end



% --------------------------------------------------------------------
function varargout = pushbuttonOpenSave_Callback(h, eventdata, handles, varargin)
handles.MoleculeName = get(handles.editMoleculeName, 'String');
handles.MoleculeName = deblank(handles.MoleculeName);
reverse = handles.MoleculeName(length(handles.MoleculeName):-1:1);
if (~strncmpi(reverse,'lch.',4))
   handles.MoleculeName = [handles.MoleculeName, '.hcl'];
end
guidata(handles.figure1, handles)   % Save the handles structure.
uiresume(handles.figure1);



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

handles.cancel = 'yes';
guidata(handles.figure1, handles)   % Save the handles structure.

uiresume(handles.figure1);



% --------------------------------------------------------------------
function varargout = editMoleculeName_Callback(h, eventdata, handles, varargin)
% We don't do "uiresume" here.



% --------------------------------------------------------------------
function load_listboxes(LocalCurrentDirectory, handles)

LCD_struct = dir(LocalCurrentDirectory);

directory_indices = find([LCD_struct.isdir]);
file_indices = find(1 - [LCD_struct.isdir]);

directories_struct = LCD_struct(directory_indices);
files_struct = LCD_struct(file_indices);

file_names = {files_struct.name}';
hcl_indicators = zeros(size(file_indices));
for i=1:length(file_indices)
  name = file_names{i};
  name = lower(name);   % Convert to lower case.
  name = deblank(name); % Remove trailing spaces.
  if length(name) >= 5
    ext = name((length(name)-3):length(name));
    if strcmp(ext, '.hcl')
      hcl_indicators(i) = 1;
    end
  end
end

hcl_indices = find(hcl_indicators);
hcl_struct = files_struct(hcl_indices);

[sorted_directory_names, sorted_directory_index] = sortrows({directories_struct.name}');
[sorted_hcl_names, sorted_hcl_index] = sortrows({hcl_struct.name}');

handles.directory_names = sorted_directory_names;

handles.hcl_names = sorted_hcl_names;

value_of_current_dir = find(strcmp(sorted_directory_names, '.'));

set(handles.listboxDirectories, 'String', handles.directory_names, ...
    'Value', value_of_current_dir, 'Max', 1, 'Min', 0)
set(handles.listboxFiles, 'String', handles.hcl_names, ...
    'Value', [], 'Max', 2, 'Min', 0)
% Max - Min <= 1 means that multiple selection is disabled.

set(handles.text8, 'String', LocalCurrentDirectory)
set(handles.editMoleculeName, 'String', '')

guidata(handles.figure1, handles)   % Save the handles structure.
