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

% Last Modified by GUIDE v2.5 05-Mar-2007 10:42:25

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @choose_directory_OpeningFcn, ...
                   'gui_OutputFcn',  @choose_directory_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 choose_directory is made visible.
function choose_directory_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to choose_directory (see VARARGIN)

% Choose default command line output for choose_directory
handles.output = hObject;


if nargin == 4,
    initial_dir = pwd;
elseif nargin == 5
    if exist(varargin{2},'dir')
        initial_dir = varargin{2};
    else
        errordlg('Input argument must be a valid directory','Input Argument Error!')
        return
    end
end

handles.code_dir = pwd;
handles.initial_dir = initial_dir;
% Update handles structure
guidata(hObject, handles);

% Populate the listbox
load_listbox(initial_dir, handles)



% UIWAIT makes choose_directory wait for user response (see UIRESUME)
 uiwait(handles.figure1);

% ------------------------------------------------------------
% Read the current directory and sort the names
% ------------------------------------------------------------
function load_listbox(dir_path, handles)
cd(dir_path)
dir_struct = dir(dir_path);
numdirs = 0;
numfiles = 0;
for i = 1:length(dir_struct)
    if dir_struct(i).isdir
        if ~strcmp(dir_struct(i).name,'.')
            numdirs = numdirs + 1;
            dirs_struct(numdirs) = dir_struct(i);
        end
    else
        numfiles = numfiles + 1;
        if numfiles < 301
            files_struct(numfiles) = dir_struct(i);
        end
    end
end

[dir_sorted_names,dir_sorted_index] = sortrows({dirs_struct.name}');
if numfiles ~= 0
    [file_sorted_names,file_sorted_index] = sortrows({files_struct.name}');
else
    file_sorted_names = [];
    file_sorted_index = [];
end
handles.dir_names = dir_sorted_names;
handles.file_names = file_sorted_names;
%handles.is_dir = [dir_struct.isdir];
handles.dir_sorted_index = [dir_sorted_index];
handles.file_sorted_index = [file_sorted_index];
guidata(handles.figure1,handles)
set(handles.list_dir,'String',handles.dir_names, 'Value',1)
set(handles.file_preview,'String',handles.file_names, 'Value',1)
    
set(handles.curdir,'String',pwd)
cd(handles.code_dir);


% --- Outputs from this function are returned to the command line.
function varargout = choose_directory_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

close(handles.figure1)

% --- Executes on selection change in list_dir.
function list_dir_Callback(hObject, eventdata, handles)
% hObject    handle to list_dir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns list_dir contents as cell array
%        contents{get(hObject,'Value')} returns selected item from list_dir

get(handles.figure1,'SelectionType');
if strcmp(get(handles.figure1,'SelectionType'),'open')
	index_selected = get(handles.list_dir,'Value');
	file_list = get(handles.list_dir,'String');	
	filename = file_list{index_selected};
%	if  handles.is_dir(handles.sorted_index(index_selected))
    cd(get(handles.curdir,'String'))
    cd(filename)
    set(handles.curdir,'String',pwd)
    cd(handles.code_dir)
    load_listbox(get(handles.curdir,'String'),handles)

end


% --- Executes during object creation, after setting all properties.
function list_dir_CreateFcn(hObject, eventdata, handles)
% hObject    handle to list_dir (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 okbutton.
function okbutton_Callback(hObject, eventdata, handles)
% hObject    handle to okbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%cd(get(handles.curdir,'String'))
handles.output = get(handles.curdir,'String');
guidata(handles.figure1, handles);

uiresume(handles.figure1);
%close(handles.figure1)



% --- Executes on button press in cancelbutton.
function cancelbutton_Callback(hObject, eventdata, handles)
% hObject    handle to cancelbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%cd(handles.initial_dir)
handles.output = handles.initial_dir;
guidata(handles.figure1, handles);
uiresume(handles.figure1);
%close(handles.figure1)


% --- Executes on selection change in file_preview.
function file_preview_Callback(hObject, eventdata, handles)
% hObject    handle to file_preview (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns file_preview contents as cell array
%        contents{get(hObject,'Value')} returns selected item from file_preview


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

	dir_name = get(handles.curdir,'String');	

	if  isdir(dir_name)
       load_listbox(dir_name,handles)
    else
        errordlg(' Directory not found','File Error');
    end
    
