function currdir = UIGetDirectory(OutputDirectory,NameStr,CurrINI)
% UIGetDirectory: Displays a dialog window that fetches a directory.
%
% USAGE:
%
%       currdir = UIGetDirectory(OutputDirectory,NameStr,CurrINI)
%
% REQUIRED INPUT:  OutputDirectory (string vector or integer). If a string then
%                                  if should be a proper directory. Integers between
%                                  1 and 5 are also possible.
%
% OPTIONAL INPUT:  NameStr (string vector) with the figure name.
%
%                  CurrINI (structure) with intialization information.
%
% OPTIONAL OUTPUT: SelectedDirectory (string vector) with a proper directory.
%
%
%                       Written by: Anders Warne
%                                   New Area Wide Model Project
%                                   DG-R/EMO
%                                   European Central Bank (ECB)
%                                   Email: anders.warne@ecb.europa.eu
%                                   Copyright © 2006-2008 European Central Bank.
%
%                       First version: August 18, 2006.
%                        This version: December 19, 2008.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LICENSE INFORMATION:
%
%      YADA is free software: you can redistribute it and/or modify
%      it under the terms of the GNU General Public License as published by
%      the Free Software Foundation, either version 3 of the License, or
%      (at your option) any later version.
%
%      This program is distributed in the hope that it will be useful,
%      but WITHOUT ANY WARRANTY; without even the implied warranty of
%      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%      GNU General Public License for more details.
%
%      You should have received a copy of the GNU General Public License
%      along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%      YADA is released under the GNU General Public License, Version 3,
%      29 June 2007 <http://www.gnu.org/licenses/>. The current release of
%      the program was last modified by the ECB on the "This version" date
%      above.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CHANGELOG:
%
% * 11-5-2007:  Updated the documentation.
%
% * 1-8-2007:   Made sure that the correct MirrorImage and MakeTrans functions are called.
%
% * 9-11-2007:  Updated the documentation.
%
% * 10-1-2008:  Changed the last drawnow call to pause(0.02).
%
% * 23-5-2008:  Updated the documentation.
%
% * 10-11-2008: Made sure that the directory string can't hold double slashes.
%
% * 19-12-2008: Updated the documentation.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

if strcmp(OutputDirectory(1,size(OutputDirectory,2)),'\')==1;
   OutputDirectory = OutputDirectory(1,1:size(OutputDirectory,2)-1);
end;
if nargin>1;
   NameStr = StringTrim(NameStr(1,:));
else;
   NameStr = '';
   CurrINI = [];
end;
%
if (nargin==0)|(ischar(OutputDirectory)==1);
   realscrsz = get(0,'ScreenSize');
   %
   fig = figure('NumberTitle', 'off', ...
      'MenuBar', 'none', ...
      'Name',NameStr, ...
      'Resize', 'off', ...
      'Color',get(0,'defaultuicontrolbackgroundcolor'), ...
      'Units','pixels', ...
      'Position', [(realscrsz(3)-373)/2 (realscrsz(4)-390)/2 373 390], ...
      'WindowStyle','modal', ...
      'Visible','off', ...
      'CloseRequestFcn','set(gcf,''Userdata'',''Cancel''); drawnow; drawnow;', ...
      'Tag','GetDirectoryWindow');
   %
   if MatlabNumber>=7.0;
      set(fig,'DockControl','off');
   end;
   %
   imageaxes = axes('Units','pixels', ...
      'Box','on', ...
      'TickLength',[0 0], ...
      'CameraUpVector',[0 1 0], ...
      'Color',get(0,'defaultuicontrolbackgroundcolor'), ...
      'Position',[20 348 39 39], ...
      'XTickLabelMode','manual', ...
      'YTickLabelMode','manual', ...
      'Tag','AxisLogo', ...
      'XColor',get(0,'defaultuicontrolbackgroundcolor'), ...
      'YColor',get(0,'defaultuicontrolbackgroundcolor'), ...
      'ZColor',get(0,'defaultuicontrolbackgroundcolor'));
   %
   ImageStructure = ReadImages;
   bgcolor = get(0,'defaultuicontrolbackgroundcolor');
   %
   image('CData',MirrorImage(MakeTrans(ImageStructure.allimages.explore_image,[160 160 164],bgcolor)),'Clipping','off','Parent',imageaxes);
   %
   uicontrol('Style', 'Text', ...
      'String','Current Directories:', ...
      'HorizontalAlignment', 'left', ...
      'FontSize',CurrINI.gui_fontsize, ...
      'FontName',CurrINI.gui_fontname, ...
      'FontWeight',CurrINI.gui_fontweight, ...
      'FontAngle',CurrINI.gui_fontangle, ...
      'Position', [20 320 100 20], ...
      'UserData',CurrINI, ...
      'Tag','BrowseText');
   %
   hedit = uicontrol('Style', 'Edit', ...
      'String',OutputDirectory, ...
      'UserData',OutputDirectory, ...
      'HorizontalAlignment', 'left', ...
      'BackgroundColor',[1 1 1], ...
      'Position',[80 60 273 25], ...
      'FontSize',CurrINI.gui_fontsize, ...
      'FontName',CurrINI.gui_fontname, ...
      'FontWeight',CurrINI.gui_fontweight, ...
      'FontAngle',CurrINI.gui_fontangle, ...
      'Tag','PWDText', ...
      'Callback','UIGetDirectory(5)');
   %
   DirList = dir(OutputDirectory);
   [void,ind] = sort({DirList.name});
   DirList = DirList(ind);
   DirName = { DirList.name }';
   finddir = find(cat(1, DirList.isdir));
   finddir = finddir(2:size(finddir,1),:);
   DirName = DirName(finddir);
   %
   hlist = uicontrol('Style', 'Listbox', ...
      'String', DirName, ...
      'BackgroundColor', 'w', ...
      'Position', [20 100 333 220], ...
      'Callback', 'UIGetDirectory(1)', ...
      'FontSize',CurrINI.gui_fontsize+2, ...
      'FontName',CurrINI.gui_fontname, ...
      'FontWeight',CurrINI.gui_fontweight, ...
      'FontAngle',CurrINI.gui_fontangle, ...
      'Max', 1, ...
      'Tag', 'DirectoryContentListbox');
   %
   uicontrol('Style', 'Text', ...
      'String','Directory:', ...
      'HorizontalAlignment', 'left', ...
      'FontSize',CurrINI.gui_fontsize, ...
      'FontName',CurrINI.gui_fontname, ...
      'FontWeight',CurrINI.gui_fontweight, ...
      'FontAngle',CurrINI.gui_fontangle, ...
      'Position', [20 60 60 20], ...
      'Tag','ChosenDirectoryText');
   %
   ok_btn = uicontrol('Style', 'Pushbutton', ...
      'String', 'OK', ...
      'FontSize',CurrINI.gui_fontsize, ...
      'FontName',CurrINI.gui_fontname, ...
      'FontWeight',CurrINI.gui_fontweight, ...
      'FontAngle',CurrINI.gui_fontangle, ...
      'Callback', 'UIGetDirectory(2)', ...
      'Position', [80 15 88 30]);
   %
   uicontrol('Style', 'Pushbutton', ...
      'String', 'Cancel', ...
      'FontSize',CurrINI.gui_fontsize, ...
      'FontName',CurrINI.gui_fontname, ...
      'FontWeight',CurrINI.gui_fontweight, ...
      'FontAngle',CurrINI.gui_fontangle, ...
      'Callback', 'UIGetDirectory(3)', ...
      'Position', [172.5 15 88 30]);
   %
   uicontrol('Style', 'Pushbutton', ...
      'String', 'New Directory', ...
      'FontSize',CurrINI.gui_fontsize, ...
      'FontName',CurrINI.gui_fontname, ...
      'FontWeight',CurrINI.gui_fontweight, ...
      'FontAngle',CurrINI.gui_fontangle, ...
      'Callback', 'UIGetDirectory(4)', ...
      'Position', [265 15 88 30]);
   %
   set(fig,'Visible','on');
   drawnow;
   if MatlabNumber>=7;
      uicontrol(ok_btn);
   end;
   %
   waitfor(fig, 'Userdata');
   %
   switch get(fig, 'Userdata');
      case 'OK';
         currentdir = get(hedit, 'String');
      case 'Cancel';
         currentdir = 0;
      end;
      if nargout==1;
         if ischar(currentdir)==1;
            currdir = [currentdir '\'];
         else;
            currdir = currentdir;
         end;
      end;
      delete(fig);
      drawnow;
      pause(0.02);
else;
   switch OutputDirectory;
   case 1;
      if strcmp(get(gcf, 'SelectionType'), 'open'),
         hfig  = findobj('Tag', 'GetDirectoryWindow');
         hlist = findobj(hfig, 'Tag', 'DirectoryContentListbox');
         hedit = findobj(hfig, 'Tag', 'PWDText');
         hlist_val = get(hlist, 'Value');
         hlist_str = get(hlist, 'String');
         hlist_dir = char(hlist_str{hlist_val});
         if ischar(hlist_dir)==1;
            hlist_dir = StringTrim(hlist_dir(1,:));
         end;
         OutputDirectory = get(hedit,'String');
         if strcmp(hlist_dir,'..')==1;
            currentdir = GetPath(OutputDirectory);
            if (strcmp(currentdir(1,size(currentdir,2)),'\')==1)|(strcmp(currentdir(1,size(currentdir,2)),'/')==1);
               currentdir = currentdir(1,1:size(currentdir,2)-1);
            end;
         else;
            currentdir = [OutputDirectory '\' hlist_dir];
         end;
         currentdir = strrep(currentdir,'\\','\');
         DirList = dir(currentdir);
         [void,ind] = sort({DirList.name});
         DirList = DirList(ind);
         DirName = { DirList.name }';
         finddir = find(cat(1, DirList.isdir));
         finddir = finddir(2:size(finddir,1),:);
         DirName = DirName(finddir);
         set(hlist,'String',DirName,'Value', 1);
         set(hedit,'String',currentdir,'UserData',currentdir);
      end;
   case 2;
      set(gcf, 'Userdata', 'OK');
   case 3;
      set(gcf, 'Userdata', 'Cancel');
   case 4;
      BrowseText = findobj('Type','uicontrol','Tag','BrowseText');
      CurrINI = get(BrowseText,'UserData');
      [action,new_directory] = EditDLG('Create New Directory','Enter Name:','new-dir',500,CurrINI);
      new_directory = strrep(new_directory,' ','');
      new_directory = strrep(new_directory,'*','');
      new_directory = strrep(new_directory,'''','');
      new_directory = strrep(new_directory,'"','');
      new_directory = strrep(new_directory,'#','');
      new_directory = strrep(new_directory,'(','');
      new_directory = strrep(new_directory,')','');
      new_directory = strrep(new_directory,'[','');
      new_directory = strrep(new_directory,']','');
      new_directory = strrep(new_directory,'{','');
      new_directory = strrep(new_directory,'}','');
      new_directory = strrep(new_directory,'~','');
      new_directory = strrep(new_directory,'`','');
      new_directory = strrep(new_directory,'´','');
      new_directory = strrep(new_directory,'[','');
      new_directory = strrep(new_directory,'\','');
      new_directory = strrep(new_directory,'/','');
      new_directory = strrep(new_directory,'<','');
      new_directory = strrep(new_directory,'>','');
      new_directory = strrep(new_directory,'|','');
      new_directory = strrep(new_directory,':','');
      new_directory = strrep(new_directory,';','');
      new_directory = strrep(new_directory,'?','');
      new_directory = strrep(new_directory,'!','');
      if strcmp(action,'OK')==1;
         hfig  = findobj('Tag','GetDirectoryWindow');
         hlist = findobj(hfig,'Tag','DirectoryContentListbox');
         hedit = findobj(hfig,'Tag','PWDText');
         hlist_str = get(hlist,'String');
         base_directory = get(hedit,'String');
         newdir = 1;
         for i=1:size(hlist_str,1);
            hlist_diri = char(hlist_str{i});
            if strcmp(lower(new_directory),lower(hlist_diri))==1;
               newdir = 0;
               break;
            end;
         end;
         if isempty(new_directory)==1;
            newdir = 2;
         end;
         create_dir = '';
         if newdir==1;
            create_dir = [base_directory '\' new_directory '\'];
            currentdir = [base_directory '\' new_directory];
            if isempty(create_dir)==0;
               mystatus = MakeDir(base_directory,new_directory);
               if mystatus>0;
                  DirList = dir(currentdir);
                  [void,ind] = sort({DirList.name});
                  DirList = DirList(ind);
                  DirName = { DirList.name }';
                  finddir = find(cat(1, DirList.isdir));
                  finddir = finddir(2:size(finddir,1),:);
                  DirName = DirName(finddir);
                  set(hlist,'String',DirName,'Value', 1);
                  set(hedit,'String',currentdir,'UserData',currentdir);
               else;
                  set(hedit,'String',get(hedit,'UserData'));
               end;
            end;
         elseif newdir==2;
            this_text = 'You didn''t select a name for the directory!';
            About(this_text,'error','Bad Directory Name',120,500);
         else;
            this_text = ['The directory ' new_directory ' already exists. Please select another name!'];
            About(this_text,'error','Bad Directory Name',120,500);
         end;
      end;
   case 5;
      hfig  = findobj('Tag','GetDirectoryWindow');
      hlist = findobj(hfig,'Tag','DirectoryContentListbox');
      hedit = findobj(hfig,'Tag','PWDText');
      hlist_str = get(hlist,'String');
      new_directory = get(hedit,'String');
      if isempty(new_directory)==1;
         currentdir = get(hedit,'UserData');
         set(hedit,'String',currentdir);
         return;
      end;
      new_directory = new_directory(1,:);
      new_directory = strrep(new_directory,' ','');
      new_directory = strrep(new_directory,'*','');
      new_directory = strrep(new_directory,'''','');
      new_directory = strrep(new_directory,'"','');
      new_directory = strrep(new_directory,'#','');
      new_directory = strrep(new_directory,'(','');
      new_directory = strrep(new_directory,')','');
      new_directory = strrep(new_directory,'[','');
      new_directory = strrep(new_directory,']','');
      new_directory = strrep(new_directory,'{','');
      new_directory = strrep(new_directory,'}','');
      new_directory = strrep(new_directory,'~','');
      new_directory = strrep(new_directory,'`','');
      new_directory = strrep(new_directory,'´','');
      new_directory = strrep(new_directory,'[','');
      new_directory = strrep(new_directory,'<','');
      new_directory = strrep(new_directory,'>','');
      new_directory = strrep(new_directory,'|','');
      new_directory = strrep(new_directory,';','');
      new_directory = strrep(new_directory,'?','');
      new_directory = strrep(new_directory,'!','');
      if isempty(new_directory)==1;
         currentdir = get(hedit,'UserData');
         set(hedit,'String',currentdir);
         return;
      end;
      if (strcmp(new_directory(1,size(new_directory,2)),'\')==1)|(strcmp(new_directory(1,size(new_directory,2)),'\')==1);
         new_directory = new_directory(1,1:size(new_directory,2)-1);
      end;
      DirList = dir(new_directory);
      if size(DirList,1)>=1;
         %
         % we are dealing with an existing directory
         %
         [void,ind] = sort({DirList.name});
         DirList = DirList(ind);
         DirName = { DirList.name }';
         finddir = find(cat(1, DirList.isdir));
         finddir = finddir(2:size(finddir,1),:);
         DirName = DirName(finddir);
         set(hlist,'String',DirName,'Value',1);
         set(hedit,'String',new_directory,'UserData',new_directory);
      else;
         %
         % we may be dealing with a new directory
         %
         check_path = GetPath(new_directory);
         if isempty(check_path)==1;
            %
            % treat new_directory as a subdirectory
            %
            show_dir = [get(hedit,'UserData') '\' new_directory];
            base_dir = get(hedit,'UserData');
            add_dir = new_directory;
            new_directory = [get(hedit,'UserData') '\' new_directory '\'];
         else;
            %
            % check to make sure that check_path is a valid path
            %
            check_dir = dir(check_path);
            base_dir = get(hedit,'UserData');
            add_dir = strrep(new_directory,base_dir,'');
            if strcmp(add_dir(1,1),'\')==1;
               add_dir = add_dir(1,2:length(add_dir));
            end;
            if size(check_dir)>=1;
               show_dir = new_directory;
               new_directory = [new_directory '\'];
            else;
               set(hedit,'String',get(hedit,'UserData'));
               this_text = strvcat('The path you entered',' ',['   ' new_directory],' ','is not valid. Please try again!');
               About(this_text,'error','Bad Path...',120,500);
               return;
            end;
         end;
         %
         % check if user wants to create the new directory
         %
         this_text = strvcat('Are you sure you want to create the directory:',' ',['   ' show_dir '?']);
         answer = Query(this_text,'question',120,'Create New Directory...',500);
         if strcmp(lower(answer),'yes')==1;
            mystatus = MakeDir(base_dir,add_dir);
            if mystatus>0;
               DirList = dir(show_dir);
               [void,ind] = sort({DirList.name});
               DirList = DirList(ind);
               DirName = { DirList.name }';
               finddir = find(cat(1, DirList.isdir));
               finddir = finddir(2:size(finddir,1),:);
               DirName = DirName(finddir);
               set(hlist,'String',DirName,'Value',1);
               set(hedit,'String',show_dir,'UserData',show_dir);
            else;
               set(hedit,'String',get(hedit,'UserData'));
            end;
         else;
            set(hedit,'String',get(hedit,'UserData'));
         end;
      end;
   end;
end;

%
% end of UIGetDirectory.m
%
